md5帮助类

、引入库

using System.Security.Cryptography;//引用Md5转换功能

、计算字符串的Md5值 

        public static string GetMD5WithString(String input)
        {
            MD5 md5Hash = MD5.Create();
            // 将输入字符串转换为字节数组并计算哈希数据
            byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input));
            // 创建一个 Stringbuilder 来收集字节并创建字符串
            StringBuilder str = new StringBuilder();
            // 循环遍历哈希数据的每一个字节并格式化为十六进制字符串
            ; i < data.Length; i++)
            {
                str.Append(data[i].ToString("x2"));//加密结果"x2"结果为32位,"x3"结果为48位,"x4"结果为64位
            }
            // 返回十六进制字符串
            return str.ToString();
        } 

、计算文件的Md5值
         static public string GetMD5WithFilePath(string filePath)
         {
             FileStream file = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
             MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
             byte[] hash_byte = md5.ComputeHash(file);
             string str = System.BitConverter.ToString(hash_byte);
             str = str.Replace("-", "");
             return str;
         }

文件和文本的MD5

Post通用方法

public static string CreatePostHttpResponse(string url, IDictionary<string, string> parameters)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "POST";

            if (request.Method == "POST")
            {

                //如果需要POST数据
                ))
                {
                    request.ContentType = "application/x-www-form-urlencoded";
                    StringBuilder buffer = new StringBuilder();
                    ;
                    foreach (string key in parameters.Keys)
                    {
                        )
                        {
                            buffer.AppendFormat("&{0}={1}", key, parameters[key]);
                        }
                        else
                        {
                            buffer.AppendFormat("{0}={1}", key, parameters[key]);
                        }
                        i++;
                    }
                    byte[] data = Encoding.UTF8.GetBytes(buffer.ToString());
                    using (Stream stream = request.GetRequestStream())
                    {
                        stream.Write(data, , data.Length);
                    }
                }
            }
            else
            {
                request.ContentLength = ;
            }

            //声明一个HttpWebRequest请求
            request.Timeout = ;
            //设置连接超时时间
            request.Headers.Set("Pragma", "no-cache");

            string result = String.Empty;
            Encoding encoding = Encoding.UTF8;
            using (WebResponse wr = request.GetResponse())
            {
                System.IO.Stream respStream = wr.GetResponseStream();
                System.IO.StreamReader reader = new System.IO.StreamReader(respStream, encoding);
                //在这里对接收到的页面内容进行处理
                result = reader.ReadToEnd();
            }

            return result;

        }

Post

Post Raw方式请求

 /// <summary>
        /// RAW方式Post
        /// </summary>
        /// <param name="url"></param>
        /// <param name="querystring"></param>
        /// <returns></returns>
        public static string CreatePostHttpResponse(string url, string param, string contentType = "")
        {
            string strURL = url;
            System.Net.HttpWebRequest request;
            request = (System.Net.HttpWebRequest)WebRequest.Create(strURL);
            request.Method = "POST";
            if (string.IsNullOrEmpty(contentType))
            {
                request.ContentType = "application/json;charset=UTF-8"; // or whatever - application/json, etc, etc
            }
            else
            {
                request.ContentType = contentType;
            }
            string paraUrlCoded = param;
            byte[] payload;
            payload = System.Text.Encoding.UTF8.GetBytes(paraUrlCoded);
            request.ContentLength = payload.Length;
            Stream writer = request.GetRequestStream();
            writer.Write(payload, , payload.Length);
            writer.Close();
            System.Net.HttpWebResponse response;
            response = (System.Net.HttpWebResponse)request.GetResponse();
            System.IO.Stream s;
            s = response.GetResponseStream();
            string StrDate = "";
            string strValue = "";
            StreamReader Reader = new StreamReader(s, Encoding.UTF8);
            while ((StrDate = Reader.ReadLine()) != null)
            {
                strValue += StrDate + "\r\n";
            }
            return strValue;
        }

RAW

Get通用方法

 public static string GetHttpResponse(string url, int Timeout)
        {
            string retString = string.Empty;
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = "GET";
                request.ContentType = "text/html;charset=UTF-8";
                request.UserAgent = null;
                request.Timeout = Timeout;
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream myResponseStream = response.GetResponseStream();
                StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
                retString = myStreamReader.ReadToEnd();
                myStreamReader.Close();
                myResponseStream.Close();
            }
            catch (Exception ex)
            {
                LogHelper.Log(ex);
                throw;//错误打回上层
            }
            return retString;
        }

使用log4net的log帮助类

using log4net;
using System;
[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config", ConfigFileExtension = "config", Watch = true)]
namespace Log4NetManager
{
    public static class LogHelper
    {
        private static ILog log = LogManager.GetLogger("LogHelper");
        private static ILog log_Normal = LogManager.GetLogger("LogHelperNormal");
        public static void Write(string msg, LogLev lev)
        {
            switch (lev)
            {
                case LogLev.Debug:
                    log_Normal.Debug(msg);
                    break;
                case LogLev.Error:
                    log.Error(msg);
                    break;
                case LogLev.Fatal:
                    log.Fatal(msg);
                    break;
                case LogLev.Info:
                    log_Normal.Info(msg);
                    break;
                case LogLev.Warn:
                    log_Normal.Warn(msg);
                    break;
                default:
                    break;
            }
        }
        public static void Write(string msg, LogLev lev, params object[] parm)
        {
            switch (lev)
            {
                case LogLev.Debug:
                    log_Normal.DebugFormat(msg, parm);
                    break;
                case LogLev.Error:
                    log.ErrorFormat(msg, parm);
                    break;
                case LogLev.Fatal:
                    log.FatalFormat(msg, parm);
                    break;
                case LogLev.Info:
                    log_Normal.InfoFormat(msg, parm);
                    break;
                case LogLev.Warn:
                    log_Normal.WarnFormat(msg, parm);
                    break;
                default:
                    break;
            }
        }
        public static void Write(Exception ex, LogLev lev)
        {
            switch (lev)
            {
                case LogLev.Debug:
                    log_Normal.Debug(ex);
                    break;
                case LogLev.Error:
                    log.Error(ex);
                    break;
                case LogLev.Fatal:
                    log.Fatal(ex);
                    break;
                case LogLev.Info:
                    log_Normal.Info(ex);
                    break;
                case LogLev.Warn:
                    log_Normal.Warn(ex);
                    break;
                default:
                    break;
            }
        }
        public static void Log(Exception ex)
        {
            Write("方法:{0} 消息:{1} 类:{2} 堆:{3} ", LogLev.Fatal, ex.TargetSite, ex.Message,ex.Source, ex.StackTrace);
        }
        public static void Log(Exception ex,int fmodelid)
        {
            Write("方法:{0} 消息:{1} 类:{2} 堆:{3} fmodelid:{4}", LogLev.Fatal, ex.TargetSite, ex.Message, ex.Source, ex.StackTrace,fmodelid);
        }
    }
}

LogHelper

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using log4net;

namespace Log4NetManager
{
    public enum LogLev
    {
        Debug,
        Error,
        Fatal,
        Info,
        Warn
    }
}

LogLev

<log4net>
  <logger name="LogHelper">
    <level value="ALL" />
    <appender-ref ref="Appender" />
  </logger>
  <logger name="LogHelperNormal">
    <level value="ALL" />
    <appender-ref ref="NormalAppender" />
  </logger>
  <appender name="Appender" type="log4net.Appender.RollingFileAppender">
    <!--日志文件名开头-->
    <param name="File" value="Log\\" />
    <!--是否追加到文件,默认为true,通常无需设置-->
    <param name="AppendToFile" value="true" />
    <param name=" />
    <param name=" />
    <param name="StaticLogFileName" value="false" />
    <!--日期的格式,每天换一个文件记录,如不设置则永远只记录一天的日志,需设置-->
    <param name="DatePattern" value="yyyyMMdd&quot;_Exception.log&quot;" />
    <param name="RollingStyle" value="Date" />
    <layout type="log4net.Layout.PatternLayout">
      <param name="ConversionPattern" value="&lt;HR COLOR=red&gt;%n异常时间:%d [%t] &lt;BR&gt;%n异常级别:%-5p &lt;BR&gt;%n异 常 类:%c [%x] &lt;BR&gt;%n%m &lt;BR&gt;%n &lt;HR Size=1&gt;"  />
    </layout>
  </appender>
  <appender name="NormalAppender" type="log4net.Appender.RollingFileAppender">
    <param name="File" value="Log\\" />
    <param name="AppendToFile" value="true" />
    <param name=" />
    <param name=" />
    <param name="StaticLogFileName" value="false" />
    <param name="DatePattern" value="yyyyMMdd&quot;_Normal.log&quot;" />
    <param name="RollingStyle" value="Date" />
    <layout type="log4net.Layout.PatternLayout">
      <param name="ConversionPattern" value="&lt;HR COLOR=blue&gt;%n日志时间:%d [%t] &lt;BR&gt;%n日志级别:%-5p &lt;BR&gt;%n日 志 类:%c [%x] &lt;BR&gt;%n%m &lt;BR&gt;%n &lt;HR Size=1&gt;"  />
    </layout>
  </appender>
</log4net>

log4net.config

微信支付签名帮助类

using Log4NetManager;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;

namespace UnifiedPayment.Core
{
    public class SignHelper
    {
        /// <summary>
        /// 获取Sign
        /// </summary>
        /// <param name="parameters">参数 会自动过滤空数据 里面不能再传入key键</param>
        /// <param name="secretkey">智游宝秘钥</param>
        /// <returns></returns>
        public static string GetSign(IDictionary<string, string> parameters, string secretkey)
        {
            var res = string.Empty;
            try
            {
                var keys = parameters.Where(c => !string.IsNullOrEmpty(c.Value) && !string.IsNullOrEmpty(c.Key)).Select(c => c.Key).ToArray();//去除空结果内容
                //处理输入参数根据ASCII码排序
                Array.Sort(keys, string.CompareOrdinal);
                var temp = new List<string>();
                foreach (var item in keys)
                {
                    foreach (var key in parameters)
                    {
                        if (item == key.Key)
                        {
                            temp.Add($"{key.Key}={key.Value}");
                            break;
                        }
                    }
                }
                temp.Add($"key={secretkey}");
                res = GetMD5(string.Join("&", temp));
            }
            catch (Exception ex)
            {
                LogHelper.Log(ex);
                throw;
            }
            return res;
        }
        /// <summary>
        /// 获取Sign
        /// </summary>
        /// <param name="parameters">参数 对象类型</param>
        /// <param name="secretkey">智游宝秘钥</param>
        /// <returns></returns>
        public static string GetSign(object parameters, string secretkey)
        {
            var t = parameters.GetType();
            var dic = new Dictionary<string, string>();
            foreach (var item in t.GetProperties())
            {
                var value = Convert.ToString(item.GetValue(parameters, null));
                if (!string.IsNullOrEmpty(value))
                    dic.Add(item.Name, value);
            }
            return GetSign(dic, secretkey);
        }
        /// <summary>
        /// 转为md5
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        public static string GetMD5(string text)
        {
            MD5 md5Hash = MD5.Create();
            // 将输入字符串转换为字节数组并计算哈希数据
            byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(text));
            // 创建一个 Stringbuilder 来收集字节并创建字符串
            StringBuilder str = new StringBuilder();
            // 循环遍历哈希数据的每一个字节并格式化为十六进制字符串
            ; i < data.Length; i++)
            {
                str.Append(data[i].ToString("X2"));//加密结果"x2"结果为32位,"x3"结果为48位,"x4"结果为64位
            }
            // 返回十六进制字符串
            return str.ToString();
        }
    }
}

SignHelper

XML帮助类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Data;
using System.Xml;
using System.Xml.Serialization;
using System.Text.RegularExpressions;
using Log4NetManager;

namespace UnifiedPayment.Core
{
    /*
        实体对象转换到Xml
        Student stu1 = new Student() { Name = "okbase", Age = 10 };
        string xml = XmlUtil.Serializer(typeof(Student), stu1);

        Xml转换到实体对象
        Student stu2 = XmlUtil.Deserialize(typeof(Student), xml) as Student;

        可转换 list, DataTable
         */

    /// <summary>
    /// Xml序列化与反序列化
    /// </summary>
    public class XMLHelper
    {
        #region 反序列化
        /// <summary>
        /// 反序列化
        /// </summary>
        /// <param name="type">类型</param>
        /// <param name="xml">XML字符串</param>
        /// <returns></returns>
        public static object Deserialize(Type type, string xml)
        {
            try
            {
                using (StringReader sr = new StringReader(xml))
                {
                    XmlSerializer xmldes = new XmlSerializer(type);
                    return xmldes.Deserialize(sr);
                }
            }
            catch (Exception e)
            {

                return null;
            }
        }
        /// <summary>
        /// 反序列化
        /// </summary>
        /// <param name="type"></param>
        /// <param name="xml"></param>
        /// <returns></returns>
        public static object Deserialize(Type type, Stream stream)
        {
            XmlSerializer xmldes = new XmlSerializer(type);
            return xmldes.Deserialize(stream);
        }
        #endregion

        #region 序列化
        /// <summary>
        /// 序列化
        /// </summary>
        /// <param name="type">类型</param>
        /// <param name="obj">对象</param>
        /// <returns></returns>
        public static string Serializer(Type type, object obj)
        {
            MemoryStream Stream = new MemoryStream();
            XmlSerializer xml = new XmlSerializer(type);
            try
            {
                //序列化对象
                xml.Serialize(Stream, obj);
            }
            catch (InvalidOperationException)
            {
                throw;
            }
            Stream.Position = ;
            StreamReader sr = new StreamReader(Stream);
            string str = sr.ReadToEnd();

            sr.Dispose();
            Stream.Dispose();

            return str;
        }
        /// <summary>
        /// 序列化
        /// </summary>
        /// <param name="obj">参数</param>
        /// <returns></returns>
        public static string SerializerToWX(object obj)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><xml>");
            if (obj != null)
            {
                var pros = obj.GetType().GetProperties();
                foreach (var pro in pros)
                {
                    sb.AppendFormat("<{0}>{1}</{0}>",pro.Name,pro.GetValue(obj,null));
                }
            }
            sb.Append("</xml>");
            return sb.ToString();
        }
        /// <summary>
        /// 反序列化
        /// </summary>
        /// <param name="xml">xml内容</param>
        /// <returns></returns>
        public static T Deserialize<T>(string xml)
        {
            var type = typeof(T);
            var res = type.Assembly.CreateInstance(type.FullName);//创建实例
            var _t = res.GetType();
            var pros = type.GetProperties();
            LogHelper.Write($"原始xml为:{xml} 时间为:{DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss")}", LogLev.Info);
            foreach (var item in pros)
            {
                var matchStr = $@"<{item.Name}>(\S*)</{item.Name}>";
                var reg = new Regex(matchStr);
                var data= reg.Match(xml);
                if (data.Success)
                {
                    //转换为实体类
                    if (!_t.GetProperty(item.Name).PropertyType.IsGenericType)
                    {
                        //非泛型
                        _t.GetProperty(item.Name).SetValue(res, ].Value) ? ].Value, _t.GetProperty(item.Name).PropertyType), null);
                    }
                    else
                    {
                        //泛型Nullable<>
                        Type genericTypeDefinition = _t.GetProperty(item.Name).PropertyType.GetGenericTypeDefinition();
                        if (genericTypeDefinition == typeof(Nullable<>))
                        {
                            _t.GetProperty(item.Name).SetValue(res, ].Value) ? ].Value, Nullable.GetUnderlyingType(_t.GetProperty(item.Name).PropertyType)), null);
                        }
                    }
                }
            }
            return (T)res;
        }

        #endregion
    }
}

WinForm MessageBox更改位置为父窗口下居中

using System;
using System.Text;
using System.Drawing;
using System.Windows.Forms;
using System.Runtime.InteropServices;

class CenterWinDialog : IDisposable
{
    ;
    private Form mOwner;

    public CenterWinDialog(Form owner)
    {
        mOwner = owner;
        owner.BeginInvoke(new MethodInvoker(findDialog));
    }

    private void findDialog()
    {
        // Enumerate windows to find the message box
        ) return;
        EnumThreadWndProc callback = new EnumThreadWndProc(checkWindow);
        if (EnumThreadWindows(GetCurrentThreadId(), callback, IntPtr.Zero))
        {
            ) mOwner.BeginInvoke(new MethodInvoker(findDialog));
        }
    }
    private bool checkWindow(IntPtr hWnd, IntPtr lp)
    {
        // Checks if <hWnd> is a dialog
        StringBuilder sb = );
        GetClassName(hWnd, sb, sb.Capacity);
        if (sb.ToString() != "#32770") return true;
        // Got it
        Rectangle frmRect = new Rectangle(mOwner.Location, mOwner.Size);
        RECT dlgRect;
        GetWindowRect(hWnd, out dlgRect);
        MoveWindow(hWnd,
            frmRect.Left + (frmRect.Width - dlgRect.Right + dlgRect.Left) / ,
            frmRect.Top + (frmRect.Height - dlgRect.Bottom + dlgRect.Top) / ,
            dlgRect.Right - dlgRect.Left,
            dlgRect.Bottom - dlgRect.Top, true);
        return false;
    }
    public void Dispose()
    {
        mTries = -;
    }

    // P/Invoke declarations
    private delegate bool EnumThreadWndProc(IntPtr hWnd, IntPtr lp);
    [DllImport("user32.dll")]
    private static extern bool EnumThreadWindows(int tid, EnumThreadWndProc callback, IntPtr lp);
    [DllImport("kernel32.dll")]
    private static extern int GetCurrentThreadId();
    [DllImport("user32.dll")]
    private static extern int GetClassName(IntPtr hWnd, StringBuilder buffer, int buflen);
    [DllImport("user32.dll")]
    private static extern bool GetWindowRect(IntPtr hWnd, out RECT rc);
    [DllImport("user32.dll")]
    private static extern bool MoveWindow(IntPtr hWnd, int x, int y, int w, int h, bool repaint);
    private struct RECT { public int Left; public int Top; public int Right; public int Bottom; }
}

CenterWinDialog.cs

using System;
using System.Windows.Forms;
using System.Text;
using System.Drawing;
using System.Runtime.InteropServices;

public class MessageBoxEx
{
    public static DialogResult Show(Form owner, string text)
    {
        using (new CenterWinDialog(owner))
        {
            return MessageBox.Show(text);
        }
    }

}

MessageBoxEx 调用方式的封装

注: 出处为https://stackoverflow.com/questions/2576156/winforms-how-can-i-make-messagebox-appear-centered-on-mainform 的Hans Passant answer

WPF根据父控件获取子控件

 private List<ChildType> FindVisualChild<ChildType>(DependencyObject obj) where ChildType : DependencyObject
        {
            var res = new List<ChildType>();
            ; i < VisualTreeHelper.GetChildrenCount(obj); i++)
            {
                DependencyObject child = VisualTreeHelper.GetChild(obj, i);
                if (child != null && child is ChildType)
                {
                    res.Add( child as ChildType);
                }
                else
                {
                    List<ChildType> childOfChildren = FindVisualChild<ChildType>(child);
                    if (childOfChildren != null)
                    {
                        res.AddRange(childOfChildren);
                    }
                }
            }
            return res;

        }

寻找某个控件下的子控件

sqlSuger 简单封装

using log4net.Core;
using Microsoft.Extensions.Configuration;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Text;

namespace CommonHelper
{
    /// <summary>
    /// 使用文档:http://www.codeisbug.com/Doc/8/1122
    /// </summary>
    public class SqlSugerHelper
    {
        private string ConnectionString = string.Empty;
        private string SqlMapPath = string.Empty;
        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="conn">数据库连接串</param>
        /// <param name="jsonConfigFileName">配置文件名称</param>
        /// <param name="sqlMapPath">sqlmap地址</param>
        /// <param name="databaseType">数据库类型</param>
        /// <param name="isLogSql">是否记录日志</param>
        public SqlSugerHelper(string conn = "", string jsonConfigFileName = "appsettings.json", string sqlMapPath = "wwwroot/SQLMAP", DatabaseType databaseType = DatabaseType.Oracle, bool isLogSql = true)
        {
            var config = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile(jsonConfigFileName, optional: true)
.Build();
            if (string.IsNullOrEmpty(conn))
            {
                conn = config.GetSection("Connections:DefaultConnect").Value;
            }
            else if (conn.StartsWith("setting:"))
            {
                conn = config.GetSection(conn.Substring()).Value;
            }
            SqlMapPath = Common.GetPath(sqlMapPath);
            var sugerConfig = new ConnectionConfig()
            {
                ConnectionString = conn,
                DbType = SqlSugar.DbType.Oracle,
                IsAutoCloseConnection = true,
                IsShardSameThread = true //设为true相同线程是同一个SqlSugarClient
            };
            switch (databaseType)
            {
                case DatabaseType.SqlServer:
                    sugerConfig.DbType = SqlSugar.DbType.SqlServer;
                    break;
                case DatabaseType.MySql:
                    sugerConfig.DbType = SqlSugar.DbType.MySql;
                    break;
                case DatabaseType.Oracle:
                    sugerConfig.DbType = SqlSugar.DbType.Oracle;
                    break;
                case DatabaseType.Sqlite:
                    sugerConfig.DbType = SqlSugar.DbType.Sqlite;
                    break;
                default:
                    break;
            }
            SqlSugarClient db = new SqlSugarClient(sugerConfig);
            db.Ado.IsEnableLogEvent = true;
            db.Ado.LogEventStarting = (sql, pars) =>
            {
                //记录sql语句
                if (isLogSql)
                    LogHelper.Write(sql + "\r\n" + db.Utilities.SerializeObject(pars.ToDictionary(it => it.ParameterName, it => it.Value)), LogLev.Info);
                Console.WriteLine(sql + "\r\n" + db.Utilities.SerializeObject(pars.ToDictionary(it => it.ParameterName, it => it.Value)));
                Console.WriteLine();
            };
            Suger = db;
        }
        /// <summary>
        /// 返回操作对象
        /// </summary>
        public SqlSugarClient Suger { get; } = null;
        public void TranStart()
        {
            if (Suger.Ado.Transaction == null)
                Suger.Ado.BeginTran();
        }
        public void TranCommit()
        {
            if (Suger.Ado.Transaction != null)
                Suger.Ado.CommitTran();
        }
        public void TranRollback()
        {
            if (Suger.Ado.Transaction != null)
                Suger.Ado.RollbackTran();
        }
        /// <summary>
        /// 插入单条
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        /// <returns></returns>
        public bool Insert<T>(T obj) where T : class, new()
        {
            if (obj == null) { return false; }
            try
            {
                return Suger.Insertable(obj).ExecuteCommandIdentityIntoEntity();
            }
            catch (Exception ex)
            {
                LogHelper.Log(ex, $"出错表名:{typeof(T).Name}");
                return false;
            }
        }
        /// <summary>
        /// 插入多条
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        /// <returns></returns>
        public bool Insert<T>(List<T> obj) where T : class, new()
        {
            ) { return false; }
            try
            {
                return Suger.Insertable(obj.ToArray()).ExecuteCommandIdentityIntoEntity();
            }
            catch (Exception ex)
            {
                LogHelper.Log(ex, $"出错表名:{typeof(T).Name}");
                return false;
            }
        }
        /// <summary>
        /// 更新单条
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        /// <returns></returns>
        public int Update<T>(T obj, Expression<Func<T, object>> columns) where T : class, new()
        {
            ; }
            try
            {
                return Suger.Updateable(obj).WhereColumns(it => columns)
                .IgnoreColumns(it => it.ToUpper() == "CREATE_TIME" || it.ToUpper() == "CREATE_OPTORNAME" || it.ToUpper() == "CREATE_OPTORCODE")
                .ExecuteCommand();
            }
            catch (Exception ex)
            {
                LogHelper.Log(ex, $"出错表名:{typeof(T).Name}");
                ;
            }
        }
        /// <summary>
        /// 更新多条
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="objs"></param>
        /// <param name="columns"></param>
        /// <returns></returns>
        public int Update<T>(List<T> objs, Expression<Func<T, object>> columns) where T : class, new()
        {
            ) { ; }
            try
            {
                return Suger.Updateable(objs).WhereColumns(it => columns)
                .IgnoreColumns(it => it.ToUpper() == "CREATE_TIME" || it.ToUpper() == "CREATE_OPTORNAME" || it.ToUpper() == "CREATE_OPTORCODE").ExecuteCommand();
            }
            catch (Exception ex)
            {
                LogHelper.Log(ex, $"出错表名:{typeof(T).Name}");
                ;
            }
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="fid"></param>
        /// <returns></returns>
        public int Delete<T>(Expression<Func<T, bool>> expression) where T : class, new()
        {
            try
            {
                return Suger.Deleteable<T>().Where(expression).ExecuteCommand();
            }
            catch (Exception ex)
            {
                LogHelper.Log(ex, $"出错表名:{typeof(T).Name}");
                ;
            }
        }
        /// <summary>
        /// 执行存储过程
        /// </summary>
        /// <param name="produceFullName"> 如GTMP_PK_TBKTRADE.GTMP_TBK_GETSERIALNO</param>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public string ExcuteProduce(string produceFullName, params SugarParameter[] parameters)
        {
            try
            {
                return Suger.Ado.UseStoredProcedure().GetString(produceFullName, parameters);
            }
            catch (Exception ex)
            {
                LogHelper.Log(ex);
                return null;
            }
        }
        /// <summary>
        /// 执行无参数的sql语句 兼容sqlmap
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="sql"></param>
        /// <param name="mapname"></param>
        /// <returns></returns>
        public List<T> Query<T>(string sql, string mapname = "") where T : class, new()
        {
            try
            {
                if (!string.IsNullOrEmpty(mapname))
                {
                    var pd = SQLMapHelper.GetSqlMapInfo(SqlMapPath, mapname, sql);
                    return Suger.SqlQueryable<T>(pd.TransferedSQL).ToList();
                }
                return Suger.SqlQueryable<T>(sql).ToList();
            }
            catch (Exception ex)
            {
                LogHelper.Log(ex);
                return null;
            }
        }
        /// <summary>
        /// 返回延迟查询对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public ISugarQueryable<T> Queryable<T>() where T : class, new()
        {
            try
            {
                return Suger.Queryable<T>();
            }
            catch (Exception ex)
            {
                LogHelper.Log(ex, $"出错表名:{typeof(T).Name}");
                return null;
            }
        }
    }
}

SqlSugerHelper

注:sqlmap部分 没有需要的可以直接删掉

sqlSuger DataTable 转换为自定义 类型集合

注: 主要解决 直接使用sqlquery 出现返回数据首行出现无字段信息问题

public T ComplexSqlQueryable<T>(string sql) where T : class, new()
        {
            var dt = Queryable(sql);
            var tt = new System.Data.DataTable(typeof(T).Name);
            Type tp = typeof(T);
            //泛型Nullable判断,取其中的类型
            if (tp.IsGenericType)
            {
                tp = tp.GetGenericArguments()[];
            }
            foreach (DataColumn col in dt.Columns)
            {
                BindingFlags flag = BindingFlags.Public | BindingFlags.IgnoreCase | BindingFlags.Instance;
                var type = tp.GetProperty(col.ColumnName, flag);
                var typeres = type == null ? col.DataType : type.PropertyType;
                tt.Columns.Add(new System.Data.DataColumn(col.ColumnName, typeres));
            }
            ; i < dt.Rows.Count; i++)
            {
                System.Data.DataRow dr = tt.NewRow();
                foreach (DataColumn col in dt.Columns)
                {
                    var type = col.DataType;
                    var toType = tt.Columns[col.ColumnName].DataType;
                    if (type != toType)
                    {
                        //文本类型不转换
                        if (toType == typeof(string))
                        {
                            dr[col.ColumnName] = dt.Rows[i][col.ColumnName].ToString();
                            continue;
                        }
                        //空值 取字段默认实例
                        if (string.IsNullOrEmpty(dt.Rows[i][col.ColumnName].ToString()))
                        {
                            dr[col.ColumnName] = Activator.CreateInstance(toType);
                            continue;
                        }
                        var TryParse = toType.GetMethod("TryParse", BindingFlags.Public | BindingFlags.Static, Type.DefaultBinder,
                            new Type[] { typeof(string), toType.MakeByRefType() },
                            ) });
                        var parameters = new object[] { dt.Rows[i][col.ColumnName].ToString(), Activator.CreateInstance(toType) };
                        bool success = (bool)TryParse.Invoke(null, parameters);
                        if (success)
                        {
                            dr[col.ColumnName] = parameters[];
                        }
                    }
                    else
                        dr[col.ColumnName] = dt.Rows[i][col.ColumnName];
                }
                tt.Rows.Add(dr);
            }

            return tt.ToT<T>();
        }

转换方法

其中  获取datatable 方法代码为:

public DataTable Queryable(string sql)
        {
            return SugerClient.GetInstance().Ado.GetDataTable(sql);
        }

简单转换方法为:

public static class Extend
    {
        public static List<TT> ToT<TT>(this IEnumerable objs)
        {
            return JsonConvert.DeserializeObject<List<TT>>(JsonConvert.SerializeObject(objs));
        }
        public static TT ToT<TT>(this object obj)
        {
            return JsonConvert.DeserializeObject<TT>(JsonConvert.SerializeObject(obj));
        }
    }

类型转换扩展方法

另转载一个 泛型反射类型转换方法

public static T ConvertType<T>(object val)
        {
            if (val == null) return default(T);//返回类型的默认值
            Type tp = typeof(T);
            //泛型Nullable判断,取其中的类型
            if (tp.IsGenericType)
            {
                tp = tp.GetGenericArguments()[];
            }
            //string直接返回转换
            if (tp.Name.ToLower() == "string")
            {
                return (T)val;
            }
            //反射获取TryParse方法
            var TryParse = tp.GetMethod("TryParse", BindingFlags.Public | BindingFlags.Static, Type.DefaultBinder,
                new Type[] { typeof(string), tp.MakeByRefType() },
                ) });
            var parameters = new object[] { val, Activator.CreateInstance(tp) };
            bool success = (bool)TryParse.Invoke(null, parameters);
            //成功返回转换后的值,否则返回类型的默认值
            if (success)
            {
                ];
            }
            return default(T);
        }

泛型类型转换

C#工具帮助类的更多相关文章

  1. Unity编辑器 - 资源批处理工具基类

    Unity编辑器 - 资源批处理工具基类 经常要对资源进行批处理,很多时候都是一次性的需求,于是弄个通用脚本. 工具是个弹出面板,处理过程有进度条,如下: 如图,子类只需要重写几个方法: using ...

  2. Java开发微信公众号(三)---微信服务器请求消息,响应消息,事件消息以及工具处理类的封装

    在前面几篇文章我们讲了微信公众号环境的配置 和微信公众号服务的接入,接下来我们来说一下微信服务器请求消息,响应消息以及事件消息的相关内容,首先我们来分析一下消息类型和返回xml格式及实体类的封装. ( ...

  3. HBase编程 API入门系列之工具Bytes类(7)

    这是从程度开发层面来说,为了方便和提高开发人员. 这个工具Bytes类,有很多很多方法,帮助我们HBase编程开发人员,提高开发. 这里,我只赘述,很常用的! package zhouls.bigda ...

  4. 视图家族之mixins视图工具类与generics工具视图类

    视图家族之mixins视图工具类与generics工具视图类 一.mixins视图工具类 作用: 提供了几种后端视图(对数据资源进行曾删改查)处理流程的实现,如果需要编写的视图属于这五种,则视图可以通 ...

  5. Android圆角矩形创建工具RoundRect类

    用于把普通图片转换为圆角图像的工具类RoundRect类(复制即可使用): import android.content.Context; import android.graphics.Bitmap ...

  6. Java学习笔记 -- Java定时调度工具Timer类

    1 关于 (时间宝贵的小姐姐请跳过) 本教程是基于Java定时任务调度工具详解之Timer篇的学习笔记. 什么是定时任务调度 基于给定的时间点,给定的时间间隔或者给定的执行次数自动执行的任务. 在Ja ...

  7. SpringMVC Http请求工具代码类

    在SpringMVC的源代码中也提供了一个封装过的ThreadLocal,其中保存了每次请求的HttpServletRequest对象,(详细请看org.springframework.web.con ...

  8. 线程同步工具 Semaphore类使用案例

    参考博文 : 线程同步工具(一) 线程同步工具(二)控制并发访问多个资源 并发工具类(三)控制并发线程数的Semaphore 使用Semaphore模拟互斥锁 当一个线程想要访问某个共享资源,首先,它 ...

  9. 线程同步工具 Semaphore类的基础使用

    推荐好文: 线程同步工具(一) 线程同步工具(二)控制并发访问多个资源 并发工具类(三)控制并发线程数的Semaphore 简介 Semaphore是基于计数的信号量,可以用来控制同时访问特定资源的线 ...

  10. Android开发之强大的网络判断工具,判断是否联网,判断是wifi还是3g网络等java工具代码类

    作者:程序员小冰,CSDN博客:http://blog.csdn.net/qq_21376985, 转载请说明出处. 给大家分享一个Android开发者常用的工具类.主要针对网络判断的 功能强大.下面 ...

随机推荐

  1. 调试JDK源代码-一步一步看HashMap怎么Hash和扩容

    调试JDK源代码-一步一步看HashMap怎么Hash和扩容 调试JDK源代码-ConcurrentHashMap实现原理 调试JDK源代码-HashSet实现原理 调试JDK源代码-调试JDK源代码 ...

  2. 打造atom成为golang开发神器

    在我在Windows系统上开发的日子里.我使用IDE开发数年之久.比如Visual Basic IDE, Borland Delphi IDE, Visual C++ 和最后的Visual Studi ...

  3. [Apple开发者帐户帮助]七、注册设备(2)注册多个设备

    如果您有许多测试设备,则可以创建包含设备名称和设备ID的文件,并将整个文件上载到开发人员帐户.您的开发人员帐户支持以下两种文件格式:具有.deviceids文件扩展名和纯文本文件的属性列表文件.您选择 ...

  4. $CF1141C Polycarp Restores Permutation$

    \(problem\) 这题的大致意思就是已知数值差值 求1-n的排列 如果能构成排列 则输出这个排列.如果不能则输出-1 排列的值都是 大于1 而小于n的 而且没有相同的数字. 这题最关键的是 怎么 ...

  5. 【CodeForces727E/CF727E】Games on a CD (字符串哈希)

    题目: CodeForces727E 分析: 看到字符串比较,肯定想到哈希啊--现学的哈希,先丢两个重要的公式 (\(seed\)是大于字符集大小的质数,\(p\)是大质数) \[hash[i]=(h ...

  6. [转]Android | Simple SQLite Database Tutorial

    本文转自:http://hmkcode.com/android-simple-sqlite-database-tutorial/ Android SQLite database is an integ ...

  7. vue 中展示PDF内容

    vue 中展示PDF内容 不久前有个需要改的需求,以前是直接根据链接让用户下载对应pdf文件来查看,最主要是给用户查看,然而这种并不是很安全的,其他用户可以进行下载或者使用pdf链接分享给其他人,所以 ...

  8. ios的认识

    刚进了ios兴趣班,第一次使用苹果电脑,因为苹果电脑和windows电脑使用的区别很大.所以老师教我们苹果电脑的基本使用,以及关于苹果产品的一些认识.我听得热血沸腾,对苹果开发越来越感兴趣,相信下次上 ...

  9. P1538 迎春舞会之数字舞蹈

    题目背景 HNSDFZ的同学们为了庆祝春节,准备排练一场舞会. 题目描述 在越来越讲究合作的时代,人们注意的更多的不是个人物的舞姿,而是集体的排列. 为了配合每年的倒计时,同学们决定排出——“数字舞蹈 ...

  10. P1257 平面上的最接近点对

    题目描述 给定平面上n个点,找出其中的一对点的距离,使得在这n个点的所有点对中,该距离为所有点对中最小的 输入输出格式 输入格式: 第一行:n:2≤n≤200000 接下来n行:每行两个实数:x y, ...