MySqlHelper

来源:http://www.cnblogs.com/s0611163/archive/2016/04/25/5429656.html
-Advertisement-
Play Games

代碼: using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Da ...


MySqlHelper代碼:

using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using MySql.Data.MySqlClient;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Web;
using System.Xml.Linq;
using System.Data.Objects.DataClasses;
using Models;
using System.Text.RegularExpressions;

namespace DBHelper
{
    /// <summary>
    /// MySql操作類
    /// 2015年6月20日
    /// 寫程式之前,首先引用MySql.Data.MySqlClient
    /// </summary>
    public class MySqlHelper
    {
        #region 靜態變數
        /// <summary>
        /// 資料庫連接字元串
        /// </summary>
        private static string connectionString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ToString();
        #endregion

        #region MySqlConnection 獲取資料庫連接
        /// <summary>
        /// 獲取資料庫連接
        /// </summary>
        private static MySqlConnection GetConn()
        {
            MySqlConnection connection = null;

            string key = "Simpo2016_MySqlConnection";

            if (HttpContext.Current.Items[key] == null)
            {
                connection = new MySqlConnection(connectionString);
                connection.Open();
                HttpContext.Current.Items[key] = connection;
            }
            else
            {
                connection = (MySqlConnection)HttpContext.Current.Items[key];
            }

            return connection;
        }
        #endregion

        #region MySqlTransaction 獲取事務對象
        /// <summary>
        /// 獲取事務對象
        /// </summary>
        private static MySqlTransaction GetTran()
        {
            MySqlTransaction tran = null;

            string key = "Simpo2016_MySqlTransaction";

            if (HttpContext.Current.Items[key] == null)
            {
                tran = GetConn().BeginTransaction();
                HttpContext.Current.Items[key] = tran;
            }
            else
            {
                tran = (MySqlTransaction)HttpContext.Current.Items[key];
            }

            return tran;
        }
        #endregion

        #region 開起事務標誌
        /// <summary>
        /// 事務標誌
        /// </summary>
        private static string tranFlagKey = "Simpo2016_MySqlTransaction_Flag";
        /// <summary>
        /// 添加事務標誌
        /// </summary>
        public static void AddTranFlag()
        {
            HttpContext.Current.Items[tranFlagKey] = true;
        }
        /// <summary>
        /// 移除事務標誌
        /// </summary>
        public static void RemoveTranFlag()
        {
            HttpContext.Current.Items[tranFlagKey] = false;
        }
        /// <summary>
        /// 事務標誌
        /// </summary>
        public static bool TranFlag
        {
            get
            {
                bool tranFlag = false;

                if (HttpContext.Current.Items[tranFlagKey] != null)
                {
                    tranFlag = (bool)HttpContext.Current.Items[tranFlagKey];
                }

                return tranFlag;
            }
        }
        #endregion

        #region 用於查詢的資料庫連接
        /// <summary>
        /// 用於查詢的資料庫連接
        /// </summary>
        private MySqlConnection m_Conn;
        #endregion

        #region 構造函數
        public MySqlHelper()
        {
            m_Conn = new MySqlConnection(connectionString);
        }
        #endregion

        #region 基礎方法
        #region  執行簡單SQL語句
        #region Exists
        public bool Exists(string sqlString)
        {
            using (MySqlCommand cmd = new MySqlCommand(sqlString, m_Conn))
            {
                try
                {
                    m_Conn.Open();
                    object obj = cmd.ExecuteScalar();
                    if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
                    {
                        return false;
                    }
                    else
                    {
                        return true;
                    }
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                finally
                {
                    cmd.Dispose();
                    m_Conn.Close();
                }
            }
        }
        #endregion

        #region 執行SQL語句,返回影響的記錄數
        /// <summary>
        /// 執行SQL語句,返回影響的記錄數
        /// </summary>
        /// <param name="sqlString">SQL語句</param>
        /// <returns>影響的記錄數</returns>
        public int ExecuteSql(string sqlString)
        {
            MySqlConnection connection = GetConn();
            using (MySqlCommand cmd = new MySqlCommand(sqlString, connection))
            {
                try
                {
                    if (connection.State != ConnectionState.Open) connection.Open();
                    if (TranFlag) cmd.Transaction = GetTran();
                    int rows = cmd.ExecuteNonQuery();
                    return rows;
                }
                catch (Exception ex)
                {
                    throw new Exception(ex.Message);
                }
                finally
                {
                    cmd.Dispose();
                    if (!TranFlag) connection.Close();
                }
            }
        }
        #endregion

        #region 執行一條計算查詢結果語句,返回查詢結果
        /// <summary>
        /// 執行一條計算查詢結果語句,返回查詢結果(object)
        /// </summary>
        /// <param name="sqlString">計算查詢結果語句</param>
        /// <returns>查詢結果(object)</returns>
        public object GetSingle(string sqlString)
        {
            using (MySqlCommand cmd = new MySqlCommand(sqlString, m_Conn))
            {
                try
                {
                    m_Conn.Open();
                    object obj = cmd.ExecuteScalar();
                    if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
                    {
                        return null;
                    }
                    else
                    {
                        return obj;
                    }
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                finally
                {
                    cmd.Dispose();
                    m_Conn.Close();
                }
            }
        }
        #endregion

        #region 執行查詢語句,返回SQLiteDataReader
        /// <summary>
        /// 執行查詢語句,返回SQLiteDataReader ( 註意:調用該方法後,一定要對SqlDataReader進行Close )
        /// </summary>
        /// <param name="sqlString">查詢語句</param>
        /// <returns>SQLiteDataReader</returns>
        public MySqlDataReader ExecuteReader(string sqlString)
        {
            MySqlConnection connection = new MySqlConnection(connectionString);
            MySqlCommand cmd = new MySqlCommand(sqlString, connection);
            try
            {
                connection.Open();
                MySqlDataReader myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                return myReader;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 執行查詢語句,返回DataSet
        /// <summary>
        /// 執行查詢語句,返回DataSet
        /// </summary>
        /// <param name="sqlString">查詢語句</param>
        /// <returns>DataSet</returns>
        public DataSet Query(string sqlString)
        {
            using (MySqlConnection connection = new MySqlConnection(connectionString))
            {
                DataSet ds = new DataSet();
                try
                {
                    connection.Open();
                    MySqlDataAdapter command = new MySqlDataAdapter(sqlString, connection);
                    command.Fill(ds, "ds");
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                finally
                {
                    connection.Close();
                }
                return ds;
            }
        }
        #endregion
        #endregion

        #region 執行帶參數的SQL語句
        #region 執行SQL語句,返回影響的記錄數
        /// <summary>
        /// 執行SQL語句,返回影響的記錄數
        /// </summary>
        /// <param name="SQLString">SQL語句</param>
        /// <returns>影響的記錄數</returns>
        public int ExecuteSql(string SQLString, params MySqlParameter[] cmdParms)
        {
            MySqlConnection connection = GetConn();
            using (MySqlCommand cmd = new MySqlCommand())
            {
                try
                {
                    PrepareCommand(cmd, connection, null, SQLString, cmdParms);
                    if (TranFlag) cmd.Transaction = GetTran();
                    int rows = cmd.ExecuteNonQuery();
                    cmd.Parameters.Clear();
                    return rows;
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                finally
                {
                    cmd.Dispose();
                    if (!TranFlag) connection.Close();
                }
            }
        }
        #endregion

        #region 執行查詢語句,返回SQLiteDataReader
        /// <summary>
        /// 執行查詢語句,返回SQLiteDataReader ( 註意:調用該方法後,一定要對SqlDataReader進行Close )
        /// </summary>
        /// <param name="strSQL">查詢語句</param>
        /// <returns>SQLiteDataReader</returns>
        public MySqlDataReader ExecuteReader(string sqlString, params MySqlParameter[] cmdParms)
        {
            MySqlCommand cmd = new MySqlCommand();
            try
            {
                PrepareCommand(cmd, m_Conn, null, sqlString, cmdParms);
                MySqlDataReader myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                cmd.Parameters.Clear();
                return myReader;
            }
            catch (Exception ex)
            {
                throw ex;
            }

        }
        #endregion

        #region 執行查詢語句,返回DataSet
        /// <summary>
        /// 執行查詢語句,返回DataSet
        /// </summary>
        /// <param name="sqlString">查詢語句</param>
        /// <returns>DataSet</returns>
        public DataSet Query(string sqlString, params MySqlParameter[] cmdParms)
        {
            MySqlCommand cmd = new MySqlCommand();
            PrepareCommand(cmd, m_Conn, null, sqlString, cmdParms);
            using (MySqlDataAdapter da = new MySqlDataAdapter(cmd))
            {
                DataSet ds = new DataSet();
                try
                {
                    da.Fill(ds, "ds");
                    cmd.Parameters.Clear();
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                finally
                {
                    cmd.Dispose();
                    m_Conn.Close();
                }
                return ds;
            }
        }
        #endregion

        #region PrepareCommand
        private void PrepareCommand(MySqlCommand cmd, MySqlConnection conn, MySqlTransaction trans, string cmdText, MySqlParameter[] cmdParms)
        {
            if (conn.State != ConnectionState.Open) conn.Open();
            cmd.Connection = conn;
            cmd.CommandText = cmdText;
            if (trans != null) cmd.Transaction = trans;
            cmd.CommandType = CommandType.Text;
            if (cmdParms != null)
            {
                foreach (MySqlParameter parm in cmdParms)
                {
                    cmd.Parameters.Add(parm);
                }
            }
        }
        #endregion
        #endregion
        #endregion

        #region 增刪改查
        #region 獲取最大編號
        /// <summary>
        /// 獲取最大編號
        /// </summary>
        /// <typeparam name="T">實體Model</typeparam>
        /// <param name="key">主鍵</param>
        public int GetMaxID<T>(string key)
        {
            Type type = typeof(T);

            string sql = string.Format("SELECT Max({0}) FROM {1}", key, type.Name);
            using (MySqlCommand cmd = new MySqlCommand(sql, m_Conn))
            {
                try
                {
                    m_Conn.Open();
                    object obj = cmd.ExecuteScalar();
                    if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
                    {
                        return 1;
                    }
                    else
                    {
                        return int.Parse(obj.ToString()) + 1;
                    }
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                finally
                {
                    cmd.Dispose();
                    m_Conn.Close();
                }
            }
        }
        #endregion

        #region 添加
        /// <summary>
        /// 添加
        /// </summary>
        public void Insert(object obj)
        {
            StringBuilder strSql = new StringBuilder();
            Type type = obj.GetType();
            CacheHelper.Remove(type);//刪除緩存
            strSql.Append(string.Format("insert into {0}(", type.Name));

            PropertyInfo[] propertyInfoList = GetEntityProperties(type);
            List<string> propertyNameList = new List<string>();
            foreach (PropertyInfo propertyInfo in propertyInfoList)
            {
                propertyNameList.Add(propertyInfo.Name);
            }

            strSql.Append(string.Format("{0})", string.Join(",", propertyNameList.ToArray())));
            strSql.Append(string.Format(" values ({0})", string.Join(",", propertyNameList.ConvertAll<string>(a => "@" + a).ToArray())));
            MySqlParameter[] parameters = new MySqlParameter[propertyInfoList.Length];
            for (int i = 0; i < propertyInfoList.Length; i++)
            {
                PropertyInfo propertyInfo = propertyInfoList[i];
                object val = propertyInfo.GetValue(obj, null);
                MySqlParameter param = new MySqlParameter("@" + propertyInfo.Name, val == null ? DBNull.Value : val);
                parameters[i] = param;
            }

            ExecuteSql(strSql.ToString(), parameters);
        }
        #endregion

        #region 修改
        /// <summary>
        /// 修改
        /// </summary>
        public void Update(object obj)
        {
            object oldObj = Find(obj, false);
            if (oldObj == null) throw new Exception("無法獲取到舊數據");

            StringBuilder strSql = new StringBuilder();
            Type type = obj.GetType();
            CacheHelper.Remove(type);//刪除緩存
            strSql.Append(string.Format("update {0} ", type.Name));

            PropertyInfo[] propertyInfoList = GetEntityProperties(type);
            List<string> propertyNameList = new List<string>();
            int savedCount = 0;
            foreach (PropertyInfo propertyInfo in propertyInfoList)
            {
                object oldVal = propertyInfo.GetValue(oldObj, null);
                object val = propertyInfo.GetValue(obj, null);
                if (!object.Equals(oldVal, val))
                {
                    propertyNameList.Add(propertyInfo.Name);
                    savedCount++;
                }
            }

            strSql.Append(string.Format(" set "));
            MySqlParameter[] parameters = new MySqlParameter[savedCount];
            StringBuilder sbPros = new StringBuilder();
            int k = 0;
            for (int i = 0; i < propertyInfoList.Length; i++)
            {
                PropertyInfo propertyInfo = propertyInfoList[i];
                object oldVal = propertyInfo.GetValue(oldObj, null);
                object val = propertyInfo.GetValue(obj, null);
                if (!object.Equals(oldVal, val))
                {
                    sbPros.Append(string.Format(" {0}=@{0},", propertyInfo.Name));
                    MySqlParameter param = new MySqlParameter("@" + propertyInfo.Name, val == null ? DBNull.Value : val);
                    parameters[k++] = param;
                }
            }
            if (sbPros.Length > 0)
            {
                strSql.Append(sbPros.ToString(0, sbPros.Length - 1));
            }
            strSql.Append(string.Format(" where {0}='{1}'", GetIdName(obj.GetType()), GetIdVal(obj).ToString()));

            if (savedCount > 0)
            {
                ExecuteSql(strSql.ToString(), parameters);
            }
        }
        #endregion

        #region 刪除
        /// <summary>
        /// 根據Id刪除
        /// </summary>
        public void Delete<T>(int id)
        {
            Type type = typeof(T);
            CacheHelper.Remove(type);//刪除緩存
            StringBuilder sbSql = new StringBuilder();
            sbSql.Append(string.Format("delete from {0} where {2}='{1}'", type.Name, id, GetIdName(type)));

            ExecuteSql(sbSql.ToString());
        }
        /// <summary>
        /// 根據Id集合刪除
        /// </summary>
        public void BatchDelete<T>(string ids)
        {
            if (string.IsNullOrWhiteSpace(ids)) return;

            Type type = typeof(T);
            CacheHelper.Remove(type);//刪除緩存
            StringBuilder sbSql = new StringBuilder();
            sbSql.Append(string.Format("delete from {0} where {2} in ({1})", type.Name, ids, GetIdName(type)));

            ExecuteSql(sbSql.ToString());
        }
        /// <summary>
        /// 根據條件刪除
        /// </summary>
        public void Delete<T>(string conditions)
        {
            if (string.IsNullOrWhiteSpace(conditions)) return;

            Type type = typeof(T);
            CacheHelper.Remove(type);//刪除緩存
            StringBuilder sbSql = new StringBuilder();
            sbSql.Append(string.Format("delete from {0} where {1}", type.Name, conditions));

            ExecuteSql(sbSql.ToString());
        }
        #endregion

        #region 獲取實體
        #region 根據實體獲取實體
        /// <summary>
        /// 根據實體獲取實體
        /// </summary>
        private object Find(object obj, bool readCache = true)
        {
            Type type = obj.GetType();

            object result = Activator.CreateInstance(type);
            bool hasValue = false;
            IDataReader rd = null;

            string sql = string.Format("select * from {0} where {2}='{1}'", type.Name, GetIdVal(obj), GetIdName(obj.GetType()));
            //獲取緩存
            if (readCache && CacheHelper.Exists(type, sql))
            {
                return CacheHelper.Get(type, sql);
            }

            try
            {
                rd = ExecuteReader(sql);

                PropertyInfo[] propertyInfoList = GetEntityProperties(type);

                int fcnt = rd.FieldCount;
                List<string> fileds = new List<string>();
                for (int i = 0; i < fcnt; i++)
                {
                    fileds.Add(rd.GetName(i).ToUpper());
                }

                while (rd.Read())
                {
                    hasValue = true;
                    IDataRecord record = rd;

                    foreach (PropertyInfo pro in propertyInfoList)
                    {
                        if (!fileds.Contains(pro.Name.ToUpper()) || record[pro.Name] == DBNull.Value)
                        {
                            continue;
                        }

                        pro.SetValue(result, record[pro.Name] == DBNull.Value ? null : getReaderValue(record[pro.Name], pro.PropertyType), null);
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (rd != null && !rd.IsClosed)
                {
                    rd.Close();
                    rd.Dispose();
                }
            }

            if (hasValue)
            {
                CacheHelper.Add(type, sql, result);//添加緩存
                return result;
            }
            else
            {
                return null;
            }
        }
        #endregion

        #region 根據Id獲取實體
        /// <summary>
        /// 根據Id獲取實體
        /// </summary>
        private object FindById(Type type, int id)
        {
            object result = Activator.CreateInstance(type);
            IDataReader rd = null;
            bool hasValue = false;

            string sql = string.Format("select * from {0} where {2}='{1}'", type.Name, id, GetIdName(type));
            //獲取緩存
            if (CacheHelper.Exists(type, sql))
            {
                return CacheHelper.Get(type, sql);
            }

            try
            {
                rd = ExecuteReader(sql);

                PropertyInfo[] propertyInfoList = GetEntityProperties(type);

                int fcnt = rd.FieldCount;
                List<string> fileds = new List<string>();
                for (int i = 0; i < fcnt; i++)
                {
                    fileds.Add(rd.GetName(i).ToUpper());
                }

                while (rd.Read())
                {
                    hasValue = true;
                    IDataRecord record = rd;

                    foreach (PropertyInfo pro in propertyInfoList)
                    {
                        if (!fileds.Contains(pro.Name.ToUpper()) || record[pro.Name] == DBNull.Value)
                        {
                            continue;
                        }

                        pro.SetValue(result, record[pro.Name] == DBNull.Value ? null : getReaderValue(record[pro.Name], pro.PropertyType), null);
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (rd != null && !rd.IsClosed)
                {
                    rd.Close();
                    rd.Dispose();
                }
            }

            if (hasValue)
            {
                CacheHelper.Add(type, sql, result);//添加緩存
                return result;
            }
            else
            {
                return null;
            }
        }
        #endregion

        #region 根據Id獲取實體
        /// <summary>
        /// 根據Id獲取實體
        /// </summary>
        public T FindById<T>(string id) where T : new()
        {
            Type type = typeof(T);
            T result = (T)Activator.CreateInstance(type);
            IDataReader rd = null;
            bool hasValue = false;

            string sql = string.Format("select * from {0} where {2}='{1}'", type.Name, id, GetIdName(type));
            //獲取緩存
            if (CacheHelper.Exists(type, sql))
            {
                return (T)CacheHelper.Get(type, sql);
            }

            try
            {
                rd = ExecuteReader(sql);

                PropertyInfo[] propertyInfoList = GetEntityProperties(type);

                int fcnt = rd.FieldCount;
                List<string> fileds = new List<string>();
                for (int i = 0; i < fcnt; i++)
                {
                    fileds.Add(rd.GetName(i).ToUpper());
                }

                while (rd.Read())
                {
                    hasValue = true;
                    IDataRecord record = rd;

                    foreach (PropertyInfo pro in propertyInfoList)
                    {
                        if (!fileds.Contains(pro.Name.ToUpper()) || record[pro.Name] == DBNull.Value)
                        {
                            continue;
                        }

                        pro.SetVal

您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 我在上篇隨筆《C#開發微信門戶及應用(32)--微信支付接入和API封裝使用》介紹為微信支付的API封裝及使用,其中介紹瞭如何配置好支付環境,並對掃碼支付的兩種方式如何在C#開發中使用進行了介紹,本隨筆繼續介紹微信支付的相關內容,介紹其中的微信現金紅包和裂變紅包的封裝和使用。 在上篇隨筆後,經過對整 ...
  • 1.C#中的類型一共分兩類,一類是值類型,一類是引用類型。2.結構類型變數本身就相當於一個實例。3.調用結構上的方法前,需要對其所有的欄位進行賦值。4.所有元素使用前都必須初始化。5.(結構類型)new操作符不會分配記憶體,僅僅調用此結構的預設構造函數去初始化其所有欄位。 6.(引用類型)變數保存了位 ...
  • 實現的原理比較直接,定義一個MessageHandler記錄WebAPI的請求記錄,然後將這些請求日誌推送到客戶端,客戶端就是一個查看日誌的頁面,實時將請求日誌展示在頁面中。 這個例子的目的是演示如何在PersistentConnection類外部給Clients推送消息 實現過程 一、服務端 服務 ...
  • ASP.NET vNext總結:EntityFramework7 源碼分享:http://www.jinhusns.com/Products/Download/?type=xcj 1.概述 關於EF7之前的版本如何?這裡就不再扯了。更不會和別人爭論EF的性能如何?好比一把寶刀,在善於用它的高手和不善 ...
  • 當你的資料庫為SQLEXPRESS時,在程式的資料庫連接字元串的服務Server使用127.0.0.1\SQLEXPRESS時,如下:它會顯示一異常: Server Error in '/' Application. A network-related or instance-specific er ...
  • 系列教程:MVC5 + EF6 + Bootstrap3 上一節:MVC5 + EF6 + Bootstrap3 (10) 數據查詢頁面 源碼下載:點我下載 我工作的源碼:http://www.jinhusns.com/Products/Download/?type=xcj 目錄 前言 排序 搜索 ...
  • 傳入一個cid,返回一個數組類型數據,在傳入數組中的cid,返回子類別數組數據,直到沒有子類別 例子: 將: [ { "cid","123", name:"標題1" }, { "cid","1234", name:"標題1" }, { "cid","1234", name:"標題1" }, { "c ...
  • [源碼下載] 背水一戰 Windows 10 (9) - 資源: 資源限定符概述, 資源限定符示例 作者:webabcd介紹背水一戰 Windows 10 之 資源 資源限定符概述 資源限定符示例 示例1、資源限定符概述Resource/Qualifiers/Summary.xaml Resourc ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...