構建一個.net的乾貨類庫,以便於快速的開發 - 工具類

来源:http://www.cnblogs.com/starmile/archive/2016/08/05/5740122.html
-Advertisement-
Play Games

相信每一個開發的框架都會有一個工具類,工具類的作用有很多,通常我會將最常用的方法放在工具類里 當然每個開發框架的工具類都會不同,這裡我只收錄了這些方法,希望有更多需求的小伙伴也可以收錄進工具類里 1.取得用戶IP 做Web開發的一定會遇到獲取用戶IP的需求的,無論是用來記錄登錄時間,還是日誌的記錄, ...


  相信每一個開發的框架都會有一個工具類,工具類的作用有很多,通常我會將最常用的方法放在工具類里

  1. 取得用戶IP
  2. 取得網站根目錄的物理路徑
  3. 枚舉相關
  4. 非法關鍵字檢查
  5. 絕對路徑改為相對路徑
  6. 獲取小數位(四捨五入 ,保留小數)
  7. 生成縮略圖

  當然每個開發框架的工具類都會不同,這裡我只收錄了這些方法,希望有更多需求的小伙伴也可以收錄進工具類里

 

  

  1.取得用戶IP

  做Web開發的一定會遇到獲取用戶IP的需求的,無論是用來記錄登錄時間,還是日誌的記錄,都要用到IP這個東西,而IP的記錄一直是程式員開發的難題,因為這個IP是可以改的,也可以代理,所以在一定程度上會有偏差(IP這東西沒用百分百的正確,如果有心不想讓你知道的話總有辦法不讓你知道),所以這個方法只是說比較精確的一個獲取IP的方法。

 1  /// <summary>
 2         /// 取得用戶IP
 3         /// </summary>
 4         /// <returns></returns>
 5         public static string GetAddressIP()
 6         {
 7             ///獲取本地的IP地址
 8             string AddressIP = string.Empty;
 9             if (System.Web.HttpContext.Current.Request.ServerVariables["HTTP_VIA"] != null) 
10             {
11                 AddressIP = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString(); 
12             }
13             else 
14             {
15                 AddressIP = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"].ToString();  
16             }
17             return AddressIP;
18         }
View Code

  

  2.取得網站根目錄的物理路徑

  

 1 /// <summary>
 2         /// 取得網站根目錄的物理路徑
 3         /// </summary>
 4         /// <returns></returns>
 5         public static string GetRootPath()
 6         {
 7             string AppPath = "";
 8             HttpContext HttpCurrent = HttpContext.Current;
 9             if (HttpCurrent != null)
10             {
11                 AppPath = HttpCurrent.Server.MapPath("~");
12             }
13             else
14             {
15                 AppPath = AppDomain.CurrentDomain.BaseDirectory;
16                 if (Regex.Match(AppPath, @"\\$", RegexOptions.Compiled).Success)
17                     AppPath = AppPath.Substring(0, AppPath.Length - 1);
18             }
19             return AppPath;
20         }
View Code

  

  3.枚舉相關

  枚舉在開發中的使用也是非常頻繁的,畢竟枚舉能夠使代碼更加清晰,也提高了代碼的維護性,所以枚舉相關的方法就顯得很是實用。

  1 /// <summary>
  2         /// 獲取枚舉列表
  3         /// </summary>
  4         /// <param name="enumType">枚舉的類型</param>
  5         /// <returns>枚舉列表</returns>
  6         public static Dictionary<int, string> GetEnumList(Type enumType)
  7         {
  8             Dictionary<int, string> dic = new Dictionary<int, string>();
  9             FieldInfo[] fd = enumType.GetFields();
 10             for (int index = 1; index < fd.Length; ++index)
 11             {
 12                 FieldInfo info = fd[index];
 13                 object fieldValue = Enum.Parse(enumType, fd[index].Name);
 14                 object[] attrs = info.GetCustomAttributes(typeof(EnumTextAttribute), false);
 15                 foreach (EnumTextAttribute attr in attrs)
 16                 {
 17                     int key = (int)fieldValue;
 18                     if (key != -100)//-100為NULL項
 19                     {
 20                         string value = attr.Text;
 21                         dic.Add(key, value);
 22                     }
 23                 }
 24             }
 25             return dic;
 26         }
 27 
 28         /// <summary>
 29         /// 獲取枚舉名稱
 30         /// </summary>
 31         /// <param name="enumType">枚舉的類型</param>
 32         /// <param name="id">枚舉值</param>
 33         /// <returns>如果枚舉值存在,返回對應的枚舉名稱,否則,返回空字元</returns>
 34         public static string GetEnumTextById(Type enumType, int id)
 35         {
 36             string ret = "";
 37             Dictionary<int, string> dic = GetEnumList(enumType);
 38             foreach (var item in dic)
 39             {
 40                 if (item.Key == id)
 41                 {
 42                     ret = item.Value;
 43                     break;
 44                 }
 45             }
 46 
 47             return ret;
 48         }
 49 
 50         /// <summary>
 51         /// 根據枚舉值獲取對應中文描述
 52         /// </summary>
 53         /// <param name="enumValue">枚舉值</param>
 54         /// <returns>枚舉值中文描述</returns>
 55         public static string GetEnumTextByEnum(object enumValue)
 56         {
 57             string ret = "";
 58             if ((int)enumValue != -1)
 59             {
 60                 Dictionary<int, string> dic = GetEnumList(enumValue.GetType());
 61                 foreach (var item in dic)
 62                 {
 63                     if (item.Key == (int)enumValue)
 64                     {
 65                         ret = item.Value;
 66                         break;
 67                     }
 68                 }
 69             }
 70 
 71             return ret;
 72         }
 73 
 74 
 75 
 76         /// <summary>
 77         /// 獲取枚舉名稱
 78         /// </summary>
 79         /// <param name="enumType">枚舉的類型</param>
 80         /// <param name="index">枚舉值的位置編號</param>
 81         /// <returns>如果枚舉值存在,返回對應的枚舉名稱,否則,返回空字元</returns>
 82         public static string GetEnumTextByIndex(Type enumType, int index)
 83         {
 84             string ret = "";
 85 
 86             Dictionary<int, string> dic = GetEnumList(enumType);
 87 
 88             if (index < 0 ||
 89                 index > dic.Count)
 90                 return ret;
 91 
 92             int i = 0;
 93             foreach (var item in dic)
 94             {
 95                 if (i == index)
 96                 {
 97                     ret = item.Value;
 98                     break;
 99                 }
100                 i++;
101             }
102 
103             return ret;
104         }
105 
106         /// <summary>
107         /// 獲取枚舉值
108         /// </summary>
109         /// <param name="enumType">枚舉的類型</param>
110         /// <param name="name">枚舉名稱</param>
111         /// <returns>如果枚舉名稱存在,返回對應的枚舉值,否則,返回-1</returns>
112         public static int GetEnumIdByName(Type enumType, string name)
113         {
114             int ret = -1;
115 
116             if (string.IsNullOrEmpty(name))
117                 return ret;
118 
119             Dictionary<int, string> dic = GetEnumList(enumType);
120             foreach (var item in dic)
121             {
122                 if (item.Value.CompareTo(name) == 0)
123                 {
124                     ret = item.Key;
125                     break;
126                 }
127             }
128 
129             return ret;
130         }
131 
132         /// <summary>
133         /// 獲取名字對應枚舉值
134         /// </summary>
135         /// <typeparam name="T">枚舉類型</typeparam>
136         /// <param name="name">枚舉名稱</param>
137         /// <returns></returns>
138         public static T GetEnumIdByName<T>(string name) where T : new()
139         {
140             Type type = typeof(T);
141             T enumItem = new T();
142             enumItem = (T)TypeDescriptor.GetConverter(type).ConvertFrom("-1");
143             if (string.IsNullOrEmpty(name))
144                 return enumItem;
145             FieldInfo[] fd = typeof(T).GetFields();
146             for (int index = 1; index < fd.Length; ++index)
147             {
148                 FieldInfo info = fd[index];
149                 object fieldValue = Enum.Parse(type, fd[index].Name);
150                 object[] attrs = info.GetCustomAttributes(typeof(EnumTextAttribute), false);
151                 if (attrs.Length == 1)
152                 {
153                     EnumTextAttribute attr = (EnumTextAttribute)attrs[0];
154                     if (name.Equals(attr.Text))
155                     {
156                         enumItem = (T)fieldValue;
157                         break;
158                     }
159                 }
160             }
161             return enumItem;
162         }
163 
164 
165         /// <summary>
166         /// 獲取枚舉值所在的位置編號
167         /// </summary>
168         /// <param name="enumType">枚舉的類型</param>
169         /// <param name="name">枚舉名稱</param>
170         /// <returns>如果枚舉名稱存在,返回對應的枚舉值的位置編號,否則,返回-1</returns>
171         public static int GetEnumIndexByName(Type enumType, string name)
172         {
173             int ret = -1;
174 
175             if (string.IsNullOrEmpty(name))
176                 return ret;
177 
178             Dictionary<int, string> dic = GetEnumList(enumType);
179             int i = 0;
180             foreach (var item in dic)
181             {
182                 if (item.Value.CompareTo(name) == 0)
183                 {
184                     ret = i;
185                     break;
186                 }
187                 i++;
188             }
189 
190             return ret;
191         }
View Code

 

  4.非法關鍵字檢查

  非法關鍵字檢查在很多網站上也有用到,這裡我收錄的方法並不是最好的,但也能滿足一般的需求,我覺得最好是用一個文件來保存字型檔去維護是最好的,有需求的小伙伴可以去搜索一下。

  

 1 /// <summary>
 2         /// 非法關鍵字檢查
 3         /// </summary>
 4         /// <param name="Emtxt">要檢查的字元串</param>
 5         /// <returns>如果字元串里沒有非法關鍵字,返回true,否則,返回false</returns>
 6         public static bool CheckWord(string Emtxt)
 7         {
 8             string keyword = @"";//因為論壇也有關鍵字檢查所以這裡的字型檔就小伙伴們自己去找^_^
 9             Regex regex = new Regex(keyword, RegexOptions.IgnoreCase);
10             if (regex.IsMatch(Emtxt))
11             {
12                 return false;
13             }
14             return true;
15         }
16 
17         /// <summary>
18         /// SQL註入關鍵字過濾
19         /// </summary>
20         private const string StrKeyWord = @"^\s*select | select |^\s*insert | insert |^\s*delete | delete |^\s*from | from |^\s*declare | declare |^\s*exec | exec | count\(|drop table|^\s*update | update |^\s*truncate | truncate |asc\(|mid\(|char\(|xp_cmdshell|^\s*master| master |exec master|netlocalgroup administrators|net user|""|^\s*or | or |^\s*and | and |^\s*null | null ";
21 
22         /// <summary>
23         /// 關鍵字過濾
24         /// </summary>
25         /// <param name="_sWord"></param>
26         /// <returns></returns>
27         public static string ResplaceSql(string _sWord)
28         {
29             if (!string.IsNullOrEmpty(_sWord))
30             {
31                 Regex regex = new Regex(StrKeyWord, RegexOptions.IgnoreCase);
32                 _sWord = regex.Replace(_sWord, "");
33                 _sWord = _sWord.Replace("'", "''");
34                 return _sWord;
35             }
36             else
37             {
38                 return "";
39             }
40         }
View Code

 

  5.絕對路徑改為相對路徑

  這個方法相對於前面的使用率並不是很高,在特定的情況下這個方法還是很有用的

 1 /// <summary>
 2         /// 絕對路徑改為相對路徑
 3         /// </summary>
 4         /// <param name="relativeTo"></param>
 5         /// <returns></returns>
 6         public static string RelativePath(string relativeTo)
 7         {
 8             string absolutePath = GetRootPath();
 9             string[] absoluteDirectories = absolutePath.Split('\\');
10             string[] relativeDirectories = relativeTo.Split('\\');
11 
12             //獲得這兩條路徑中最短的
13             int length = absoluteDirectories.Length < relativeDirectories.Length ? absoluteDirectories.Length : relativeDirectories.Length;
14 
15             //用於確定退出的迴圈中的地方
16             int lastCommonRoot = -1;
17             int index;
18 
19             //找到共同的根目錄
20             for (index = 0; index < length; index++)
21                 if (absoluteDirectories[index] == relativeDirectories[index])
22                     lastCommonRoot = index;
23                 else
24                     break;
25 
26             //如果我們沒有找到一個共同的首碼,然後拋出
27             if (lastCommonRoot == -1)
28                 throw new ArgumentException("Paths do not have a common base");
29 
30             //建立相對路徑
31             StringBuilder relativePath = new StringBuilder();
32 
33             //加上 ..
34             for (index = lastCommonRoot + 1; index < absoluteDirectories.Length; index++)
35                 if (absoluteDirectories[index].Length > 0)
36                     relativePath.Append("..\\");
37 
38             //添加文件夾
39             for (index = lastCommonRoot + 1; index < relativeDirectories.Length - 1; index++)
40                 relativePath.Append(relativeDirectories[index] + "\\");
41             relativePath.Append(relativeDirectories[relativeDirectories.Length - 1]);
42 
43             return relativePath.ToString();
44         }
View Code

 

  6.獲取小數位(四捨五入 ,保留小數)

  在日常處理數字相關的時候經常會用到的方法

 1        /// <summary>
 2         /// 四捨五入,保留2位小數
 3         /// </summary>
 4         /// <param name="obj"></param>
 5         /// <returns></returns>
 6         public static decimal Rounding(decimal obj)
 7         {
 8             return Rounding(obj, 2);
 9         }
10         /// <summary>
11         /// 四捨五入,保留n位小數
12         /// </summary>
13         /// <param name="obj"></param>
14         /// <param name="len">保留幾位小數</param>
15         /// <returns></returns>
16         public static decimal Rounding(decimal obj, int len)
17         {
18             return Math.Round(obj, len, MidpointRounding.AwayFromZero);
19         }
20 
21         /// <summary>
22         /// 只舍不入,保留2位小數
23         /// </summary>
24         /// <param name="obj"></param>
25         /// <returns></returns>
26         public static decimal RoundingMin(decimal obj)
27         {
28             return RoundingMin(obj, 2);
29         }
30 
31         /// <summary>
32         /// 只舍不入,保留n位小數
33         /// </summary>
34         /// <param name="obj"></param>
35         /// <param name="len"></param>
36         /// <returns></returns>
37         public static decimal RoundingMin(decimal obj, int len)
38         {
39             var str = "0." + "".PadLeft(len, '0') + "5";
40             decimal dec = Convert.ToDecimal(str);
41             return Rounding(obj - dec, len);
42         }
43 
44 
45         /// <summary>
46         /// 只舍不入,保留2位小數
47         /// </summary>
48         /// <param name="obj"></param>
49         /// <returns></returns>
50         public static decimal RoundingMax(decimal obj)
51         {
52             return RoundingMax(obj, 2);
53         }
54 
55         /// <summary>
56         /// 只舍不入,保留n位小數
57         /// </summary>
58         /// <param name="obj"></param>
59         /// <param name="len"></param>
60         /// <returns></returns>
61         public static decimal RoundingMax(decimal obj, int len)
62         {
63             var str = "0." + "".PadLeft(len, '0') + "4";
64             decimal dec = Convert.ToDecimal(str);
65             return Rounding(obj + dec, len);

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

-Advertisement-
Play Games
更多相關文章
  • VS2013自帶IIS Express,無法發佈JSON文件,需添加MIME映射。 沒有圖形界面,只能命令行。 進入C:\Program Files(x86)\IIS Express文件夾,輸入:appcmd set config /section:staticContent /+[fileExte... ...
  • 可能對於初入此行業人來說有些困惑,實現起來有一絲複雜。 比如說時間是:2016-08-05 14:46:30,中間過了56秒鐘。要求得出56秒之後的時間格式是:年月日時分秒 下麵介紹最簡單的辦法, 也就是直接用 2016-08-05 14:46:30.AddSeconds(56)即可。 其中的Add ...
  • 這次主要實現管理後臺界面用戶資料的修改和刪除,修改用戶資料和角色是經常用到的功能,但刪除用戶的情況比較少,為了功能的完整性還是坐上了。主要用到兩個action “Modify”和“Delete”。 目錄 MVC5網站開發之一 總體概述 MVC5 網站開發之二 創建項目 MVC5 網站開發之三 數據存 ...
  • 對Web API新手來說,不要忽略了ApiController 在web API中,方法的返回值如果是實體的話實際上是自動返回JSON數據的例如: 他的返回值就是這樣的: 這是定義的Response類 在web API還有一個問題,可能是我自己太大意了,新建的控制器如果沒有仔細看就會預設選擇了MVC ...
  • 一、什麼是VSTO? VSTO = Visual Studo Tools for Office,是.net平臺下的Office開發技術。相對於傳統的VBA(Visual Basic Application)開發,VSTO為中高級開發人員提供了更加強大的開發平臺和語言,並部分解決了傳統Office開發 ...
  • 為什麼要創造Taurus.MVC:記得被上一家公司忽悠去負責公司電商平臺的時候,情況是這樣的:項目原版是外包給第三方的,使用:WebForm+NHibernate,代碼不堪入目,Bug無限,經常點著點著就掛了。一開始招了幾個實習的大學生在那玩,搞不定了,終於忽悠的我了,哈哈。。。當時進去的第一感覺是... ...
  • public static void InsertWithLob(OracleConnection conn) { if (conn!= null && conn.State == ConnectionState.Open) { try { string sqlText = "insert into ...
  • Insert測試,只測試1000條的情況,多了在實際的項目中應該就要另行處理了。 using System; using System.Collections.Generic; using System.Configuration; using System.Data.Entity; using S ...
一周排行
    -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.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...