文章出處

項目架構搭建之Infrastructure的搭建

Contents

 

系列一【架構概覽

0.項目簡介

1.項目解決方案分層方案 

2.所用到的技術

3.項目引用關系 

 

系列二【架構搭建初步

4.項目架構各部分解析

5.項目創建 

 

系列三 【Infrastructure搭建

6.項目架構搭建之Core搭建

7.項目架構搭建之Models搭建

 

系列四 【Repository和Service的搭建

8.項目架構搭建之IDAL搭建 
9.項目架構搭建之MSSQLDAL搭建
10.項目架構搭建之IBLL搭建
11.項目架構搭建之BLL搭建

 

 

系列五 【UI搭建

12.WebHelper搭建

13.Web搭建

14.AdminLogic搭建

 

系列六 【項目擴展

15.新增Model的處理

 

 

6.項目架構搭建之Core搭建

    添加對用到的類庫的引用,這里用到的包括:.NET自帶的兩個類庫System.Configuration 、 System.Web ,和兩個第三方類庫 log4net(日志框架) 和 Newtonsoft.Json (Json.Net)

 

  • ConfigurationHelper 【配置文件幫助類】

   

  1     /// <summary>
  2 
  3        /// 網站根路徑
  4 
  5        /// </summary>
  6 
  7        private static string siteroot = System.Web.Hosting.HostingEnvironment.MapPath("~/");
  8 
  9  
 10 
 11        /// <summary>
 12 
 13        /// 獲取配置文件中AppSetting節點的相對路徑對應的絕對路徑
 14 
 15        /// </summary>
 16 
 17        /// <param name="key">相對路徑設置的鍵值</param>
 18 
 19        /// <returns>絕對路徑</returns>
 20 
 21        public static string AppSettingMapPath(string key)
 22 
 23        {
 24 
 25            if (String.IsNullOrEmpty(siteroot))
 26 
 27            {
 28 
 29                siteroot = System.Web.Hosting.HostingEnvironment.MapPath("~/");
 30 
 31            }
 32 
 33            //拼接路徑
 34 
 35            string path = siteroot + System.Configuration.ConfigurationManager.AppSettings[key].ToString();
 36 
 37            return path;
 38 
 39        }
 40 
 41  
 42 
 43        /// <summary>
 44 
 45        /// 將虛擬路徑轉換為物理路徑
 46 
 47        /// </summary>
 48 
 49        /// <param name="virtualPath">虛擬路徑</param>
 50 
 51        /// <returns>虛擬路徑對應的物理路徑</returns>
 52 
 53        public static string MapPath(string virtualPath)
 54 
 55        {
 56 
 57            if (String.IsNullOrEmpty(siteroot))
 58 
 59            {
 60 
 61                siteroot = System.Web.Hosting.HostingEnvironment.MapPath("~/");
 62 
 63            }
 64 
 65            //拼接路徑
 66 
 67            string path = siteroot + virtualPath;
 68 
 69            return path;
 70 
 71        }
 72 
 73  
 74 
 75        /// <summary>
 76 
 77        /// 獲取配置文件中AppSetting節點的值
 78 
 79        /// </summary>
 80 
 81        /// <param name="key">設置的鍵值</param>
 82 
 83        /// <returns>鍵值對應的值</returns>
 84 
 85        public static string AppSetting(string key) => System.Configuration.ConfigurationManager.AppSettings[key].ToString();
 86 
 87  
 88 
 89        /// <summary>
 90 
 91        /// 獲取配置文件中ConnectionStrings節點的值
 92 
 93        /// </summary>
 94 
 95        /// <param name="key">鍵值</param>
 96 
 97        /// <returns>鍵值對應的連接字符串值</returns>
 98 
 99        public static string ConnectionString(string key) => System.Configuration.ConfigurationManager.ConnectionStrings[key].ConnectionString;
100 
101  
102 
103        public static bool UpdateAppSettings(string key, string value)
104 
105        {
106 
107            string filename = System.Web.Hosting.HostingEnvironment.MapPath("~/web.config");
108 
109            XmlDocument xmldoc = new XmlDocument();
110 
111            try
112 
113            {
114 
115                xmldoc.Load(filename);
116 
117            }
118 
119            catch (Exception)
120 
121            {
122 
123                return false;
124 
125            }
126 
127            XmlNodeList DocdNodeNameArr = xmldoc.DocumentElement.ChildNodes;//文檔節點名稱數組
128 
129            foreach (XmlElement element in DocdNodeNameArr)
130 
131            {
132 
133                if (element.Name == "appSettings")//找到名稱為 appSettings 的節點
134 
135                {
136 
137                    XmlNodeList KeyNameArr = element.ChildNodes;//子節點名稱數組
138 
139                    if (KeyNameArr.Count > 0)
140 
141                    {
142 
143                        foreach (XmlElement xmlElement in KeyNameArr)
144 
145                        {
146 
147                            //找到鍵值,修改為想要修改的值
148 
149                            if (xmlElement.Attributes["key"].InnerXml.Equals(key))
150 
151                            {
152 
153                                xmlElement.Attributes["value"].Value = value;
154 
155                                ConfigurationManager.RefreshSection("appSettings");
156 
157                                return true;
158 
159                            }
160 
161                        }
162 
163                        //沒有相應的節點
164 
165                        return false;
166 
167                    }
168 
169                    else
170 
171                    {
172 
173                        //不存在 AppSettings 節點
174 
175                        return false;
176 
177                    }
178 
179                }
180 
181            }
182 
183            return false;
184 
185        }
186 
187  

 

  • PathHelper 【路徑幫助類】

    通過 System.Web.Hosting.HostingEnvironment.MapPath() 方法將虛擬路徑轉換為物理路徑

 

1 /// <summary>
2 /// 將虛擬路徑轉換為物理路徑
3 /// </summary>
4 /// <param name="virtualPath">虛擬路徑</param>
5 /// <returns>虛擬路徑對應的物理路徑</returns>
6 public static string MapPath(string virtualPath) => System.Web.Hosting.HostingEnvironment.MapPath("~/") + virtualPath;

 

  • LogHelper    【日志幫助類】

    根據log4net中的ILog接口中的方法進行封裝,在構造函數中設置logger,在程序啟動時需要進行log4net的初始化,只初始化一次就可以了所以需要設置為static 靜態方法

 

/// <summary>
   /// 日志助手
   /// </summary>
   public class LogHelper
   {
       private readonly ILog logger = null;
 

       public LogHelper(Type t)
       {
           logger = LogManager.GetLogger(t);
       }
 

       public LogHelper(string name)
       {
           logger = LogManager.GetLogger(name);
       }
 

       public static void LogInit()
       {
           log4net.Config.XmlConfigurator.Configure();
       }
 

       public void Debug(string msg)
       {
           logger.Debug(msg);
       }
 

       public void Debug(string msg, Exception ex)
       {
           logger.Debug(msg, ex);
       }
 

       public void Error(string msg)
       {
           logger.Error(msg);
       }
 

       public void Error(string msg, Exception ex)
       {
           logger.Error(msg, ex);
       }
 

       public void Warn(string msg)
       {
           logger.Warn(msg);
       }
 

       public void Warn(string msg, Exception ex)
       {
           logger.Warn(msg, ex);
       }
 

       public void Debug(Exception ex)
       {
           logger.Debug(ex.Message, ex);
       }
 

       public void Error(Exception ex)
       {
           logger.Error(ex.Message, ex);
       }
   }

 

  • WebHelper 【Web幫助類】

    包括Web編碼解碼:html編碼解碼、url編碼解碼,Cookies管理,獲取客戶端信息(IP,瀏覽器類型、操作系統等信息)

     

     1 #region 編碼
     2 
     3         /// <summary>
     4         /// HTML解碼
     5         /// </summary>
     6         /// <returns></returns>
     7         public static string HtmlDecode(string s)
     8         {
     9             return HttpUtility.HtmlDecode(s);
    10         }
    11 
    12         /// <summary>
    13         /// HTML編碼
    14         /// </summary>
    15         /// <returns></returns>
    16         public static string HtmlEncode(string s)
    17         {
    18             return HttpUtility.HtmlEncode(s);
    19         }
    20 
    21         /// <summary>
    22         /// URL解碼
    23         /// </summary>
    24         /// <returns></returns>
    25         public static string UrlDecode(string s)
    26         {
    27             return HttpUtility.UrlDecode(s);
    28         }
    29 
    30         /// <summary>
    31         /// URL編碼
    32         /// </summary>
    33         /// <returns></returns>
    34         public static string UrlEncode(string s)
    35         {
    36             return HttpUtility.UrlEncode(s);
    37         }
    38 
    39         #endregion 編碼
      1 #region Cookie
      2 
      3         /// <summary>
      4         /// 刪除指定名稱的Cookie
      5         /// </summary>
      6         /// <param name="name">Cookie名稱</param>
      7         public static void DeleteCookie(string name)
      8         {
      9             HttpCookie cookie = new HttpCookie(name);
     10             cookie.Expires = DateTime.Now.AddYears(-1);
     11             HttpContext.Current.Response.AppendCookie(cookie);
     12         }
     13 
     14         /// <summary>
     15         /// 獲得指定名稱的Cookie值
     16         /// </summary>
     17         /// <param name="name">Cookie名稱</param>
     18         /// <returns></returns>
     19         public static string GetCookie(string name)
     20         {
     21             HttpCookie cookie = HttpContext.Current.Request.Cookies[name];
     22             if (cookie != null)
     23                 return cookie.Value;
     24 
     25             return string.Empty;
     26         }
     27 
     28         /// <summary>
     29         /// 獲得指定名稱的Cookie中特定鍵的值
     30         /// </summary>
     31         /// <param name="name">Cookie名稱</param>
     32         /// <param name="key"></param>
     33         /// <returns></returns>
     34         public static string GetCookie(string name, string key)
     35         {
     36             HttpCookie cookie = HttpContext.Current.Request.Cookies[name];
     37             if (cookie != null && cookie.HasKeys)
     38             {
     39                 string v = cookie[key];
     40                 if (v != null)
     41                     return v;
     42             }
     43 
     44             return string.Empty;
     45         }
     46 
     47         /// <summary>
     48         /// 設置指定名稱的Cookie的值
     49         /// </summary>
     50         /// <param name="name">Cookie名稱</param>
     51         /// <param name="value"></param>
     52         public static void SetCookie(string name, string value)
     53         {
     54             HttpCookie cookie = HttpContext.Current.Request.Cookies[name];
     55             if (cookie != null)
     56                 cookie.Value = value;
     57             else
     58                 cookie = new HttpCookie(name, value);
     59 
     60             HttpContext.Current.Response.AppendCookie(cookie);
     61         }
     62 
     63         /// <summary>
     64         /// 設置指定名稱的Cookie的值
     65         /// </summary>
     66         /// <param name="name">Cookie名稱</param>
     67         /// <param name="value"></param>
     68         /// <param name="expires">過期時間</param>
     69         public static void SetCookie(string name, string value, double expires)
     70         {
     71             HttpCookie cookie = HttpContext.Current.Request.Cookies[name];
     72             if (cookie == null)
     73                 cookie = new HttpCookie(name);
     74 
     75             cookie.Value = value;
     76             cookie.Expires = DateTime.Now.AddMinutes(expires);
     77             HttpContext.Current.Response.AppendCookie(cookie);
     78         }
     79 
     80         /// <summary>
     81         /// 設置指定名稱的Cookie特定鍵的值
     82         /// </summary>
     83         /// <param name="name">Cookie名稱</param>
     84         /// <param name="key"></param>
     85         /// <param name="value"></param>
     86         public static void SetCookie(string name, string key, string value)
     87         {
     88             HttpCookie cookie = HttpContext.Current.Request.Cookies[name];
     89             if (cookie == null)
     90                 cookie = new HttpCookie(name);
     91 
     92             cookie[key] = value;
     93             HttpContext.Current.Response.AppendCookie(cookie);
     94         }
     95 
     96         /// <summary>
     97         /// 設置指定名稱的Cookie特定鍵的值
     98         /// </summary>
     99         /// <param name="name">Cookie名稱</param>
    100         /// <param name="key"></param>
    101         /// <param name="value"></param>
    102         /// <param name="expires">過期時間</param>
    103         public static void SetCookie(string name, string key, string value, double expires)
    104         {
    105             HttpCookie cookie = HttpContext.Current.Request.Cookies[name];
    106             if (cookie == null)
    107                 cookie = new HttpCookie(name);
    108 
    109             cookie[key] = value;
    110             cookie.Expires = DateTime.Now.AddMinutes(expires);
    111             HttpContext.Current.Response.AppendCookie(cookie);
    112         }
    113 
    114         #endregion Cookie
      1         //瀏覽器列表
      2         private static string[] _browserlist = new string[] { "ie", "chrome", "mozilla", "netscape", "firefox", "opera", "konqueror" };
      3 
      4 #region 客戶端信息
      5 
      6         /// <summary>
      7         /// 是否是get請求
      8         /// </summary>
      9         /// <returns></returns>
     10         public static bool IsGet()
     11         {
     12             return HttpContext.Current.Request.HttpMethod == "GET";
     13         }
     14 
     15         /// <summary>
     16         /// 是否是post請求
     17         /// </summary>
     18         /// <returns></returns>
     19         public static bool IsPost()
     20         {
     21             return HttpContext.Current.Request.HttpMethod == "POST";
     22         }
     23 
     24         /// <summary>
     25         /// 是否是Ajax請求
     26         /// </summary>
     27         /// <returns></returns>
     28         public static bool IsAjax()
     29         {
     30             return HttpContext.Current.Request.Headers["X-Requested-With"] == "XMLHttpRequest";
     31         }
     32 
     33         /// <summary>
     34         /// 獲得查詢字符串中的值
     35         /// </summary>
     36         /// <param name="key"></param>
     37         /// <param name="defaultValue">默認值</param>
     38         /// <returns></returns>
     39         public static string GetQueryString(string key, string defaultValue)
     40         {
     41             string value = HttpContext.Current.Request.QueryString[key];
     42             if (!string.IsNullOrWhiteSpace(value))
     43                 return value;
     44             else
     45                 return defaultValue;
     46         }
     47 
     48         /// <summary>
     49         /// 獲得查詢字符串中的值
     50         /// </summary>
     51         /// <param name="key"></param>
     52         /// <returns></returns>
     53         public static string GetQueryString(string key)
     54         {
     55             return GetQueryString(key, "");
     56         }
     57 
     58         /// <summary>
     59         /// 獲得查詢字符串中的值
     60         /// </summary>
     61         /// <param name="key"></param>
     62         /// <param name="defaultValue">默認值</param>
     63         /// <returns></returns>
     64         public static int GetQueryInt(string key, int defaultValue)
     65         {
     66             return ConverterHelper.StringToInt(HttpContext.Current.Request.QueryString[key], defaultValue);
     67         }
     68 
     69         /// <summary>
     70         /// 獲得查詢字符串中的值
     71         /// </summary>
     72         /// <param name="key"></param>
     73         /// <returns></returns>
     74         public static int GetQueryInt(string key)
     75         {
     76             return GetQueryInt(key, 0);
     77         }
     78 
     79         /// <summary>
     80         /// 獲得表單中的值
     81         /// </summary>
     82         /// <param name="key"></param>
     83         /// <param name="defaultValue">默認值</param>
     84         /// <returns></returns>
     85         public static string GetFormString(string key, string defaultValue)
     86         {
     87             string value = HttpContext.Current.Request.Form[key];
     88             if (!string.IsNullOrWhiteSpace(value))
     89                 return value;
     90             else
     91                 return defaultValue;
     92         }
     93 
     94         /// <summary>
     95         /// 獲得表單中的值
     96         /// </summary>
     97         /// <param name="key"></param>
     98         /// <returns></returns>
     99         public static string GetFormString(string key)
    100         {
    101             return GetFormString(key, "");
    102         }
    103 
    104         /// <summary>
    105         /// 獲得表單中的值
    106         /// </summary>
    107         /// <param name="key"></param>
    108         /// <param name="defaultValue">默認值</param>
    109         /// <returns></returns>
    110         public static int GetFormInt(string key, int defaultValue)
    111         {
    112             return ConverterHelper.StringToInt(HttpContext.Current.Request.Form[key], defaultValue);
    113         }
    114 
    115         /// <summary>
    116         /// 獲得表單中的值
    117         /// </summary>
    118         /// <param name="key"></param>
    119         /// <returns></returns>
    120         public static int GetFormInt(string key)
    121         {
    122             return GetFormInt(key, 0);
    123         }
    124 
    125         /// <summary>
    126         /// 獲得請求中的值
    127         /// </summary>
    128         /// <param name="key"></param>
    129         /// <param name="defaultValue">默認值</param>
    130         /// <returns></returns>
    131         public static string GetRequestString(string key, string defaultValue)
    132         {
    133             if (HttpContext.Current.Request.Form[key] != null)
    134                 return GetFormString(key, defaultValue);
    135             else
    136                 return GetQueryString(key, defaultValue);
    137         }
    138 
    139         /// <summary>
    140         /// 獲得請求中的值
    141         /// </summary>
    142         /// <param name="key"></param>
    143         /// <returns></returns>
    144         public static string GetRequestString(string key)
    145         {
    146             if (HttpContext.Current.Request.Form[key] != null)
    147                 return GetFormString(key);
    148             else
    149                 return GetQueryString(key);
    150         }
    151 
    152         /// <summary>
    153         /// 獲得請求中的值
    154         /// </summary>
    155         /// <param name="key"></param>
    156         /// <param name="defaultValue">默認值</param>
    157         /// <returns></returns>
    158         public static int GetRequestInt(string key, int defaultValue)
    159         {
    160             if (HttpContext.Current.Request.Form[key] != null)
    161                 return GetFormInt(key, defaultValue);
    162             else
    163                 return GetQueryInt(key, defaultValue);
    164         }
    165 
    166         /// <summary>
    167         /// 獲得請求中的值
    168         /// </summary>
    169         /// <param name="key"></param>
    170         /// <returns></returns>
    171         public static int GetRequestInt(string key)
    172         {
    173             if (HttpContext.Current.Request.Form[key] != null)
    174                 return GetFormInt(key);
    175             else
    176                 return GetQueryInt(key);
    177         }
    178 
    179         /// <summary>
    180         /// 獲得上次請求的url
    181         /// </summary>
    182         /// <returns></returns>
    183         public static string GetUrlReferrer()
    184         {
    185             Uri uri = HttpContext.Current.Request.UrlReferrer;
    186             if (uri == null)
    187             {
    188                 return string.Empty;
    189             }
    190             return uri.ToString();
    191         }
    192 
    193         /// <summary>
    194         /// 獲得請求的主機部分
    195         /// </summary>
    196         /// <returns></returns>
    197         public static string GetHost()
    198         {
    199             return HttpContext.Current.Request.Url.Host;
    200         }
    201 
    202         /// <summary>
    203         /// 獲得請求的url
    204         /// </summary>
    205         /// <returns></returns>
    206         public static string GetUrl()
    207         {
    208             return HttpContext.Current.Request.Url.ToString();
    209         }
    210 
    211         /// <summary>
    212         /// 獲得請求的原始url
    213         /// </summary>
    214         /// <returns></returns>
    215         public static string GetRawUrl()
    216         {
    217             return HttpContext.Current.Request.RawUrl;
    218         }
    219 
    220         /// <summary>
    221         /// 獲得請求的ip
    222         /// </summary>
    223         /// <returns></returns>
    224         public static string GetIP()
    225         {
    226             string ip = string.Empty;
    227             if (HttpContext.Current.Request.ServerVariables["HTTP_VIA"] != null)
    228                 ip = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
    229             else
    230                 ip = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"].ToString();
    231 
    232             if (string.IsNullOrEmpty(ip) || !ValidateHelper.IsIP(ip))
    233                 ip = "127.0.0.1";
    234             return ip;
    235         }
    236 
    237         /// <summary>
    238         /// 獲得請求的瀏覽器類型
    239         /// </summary>
    240         /// <returns></returns>
    241         public static string GetBrowserType()
    242         {
    243             string type = HttpContext.Current.Request.Browser.Type;
    244             if (string.IsNullOrEmpty(type) || type == "unknown")
    245                 return "未知";
    246 
    247             return type.ToLower();
    248         }
    249 
    250         /// <summary>
    251         /// 獲得請求的瀏覽器名稱
    252         /// </summary>
    253         /// <returns></returns>
    254         public static string GetBrowserName()
    255         {
    256             string name = HttpContext.Current.Request.Browser.Browser;
    257             if (string.IsNullOrEmpty(name) || name == "unknown")
    258                 return "未知";
    259 
    260             return name.ToLower();
    261         }
    262 
    263         /// <summary>
    264         /// 獲得請求的瀏覽器版本
    265         /// </summary>
    266         /// <returns></returns>
    267         public static string GetBrowserVersion()
    268         {
    269             string version = HttpContext.Current.Request.Browser.Version;
    270             if (string.IsNullOrEmpty(version) || version == "unknown")
    271                 return "未知";
    272 
    273             return version;
    274         }
    275 
    276         /// <summary>
    277         /// 獲得請求客戶端的操作系統類型
    278         /// </summary>
    279         /// <returns></returns>
    280         public static string GetOSType()
    281         {
    282             string userAgent = HttpContext.Current.Request.UserAgent;
    283             if (userAgent == null)
    284                 return "未知";
    285 
    286             string type = null;
    287             if (userAgent.Contains("NT 6.1"))
    288                 type = "Windows 7";
    289             else if (userAgent.Contains("NT 5.1"))
    290                 type = "Windows XP";
    291             else if (userAgent.Contains("NT 6.2"))
    292                 type = "Windows 8";
    293             else if (userAgent.Contains("android"))
    294                 type = "Android";
    295             else if (userAgent.Contains("iphone"))
    296                 type = "IPhone";
    297             else if (userAgent.Contains("Mac"))
    298                 type = "Mac";
    299             else if (userAgent.Contains("NT 6.0"))
    300                 type = "Windows Vista";
    301             else if (userAgent.Contains("NT 5.2"))
    302                 type = "Windows 2003";
    303             else if (userAgent.Contains("NT 5.0"))
    304                 type = "Windows 2000";
    305             else if (userAgent.Contains("98"))
    306                 type = "Windows 98";
    307             else if (userAgent.Contains("95"))
    308                 type = "Windows 95";
    309             else if (userAgent.Contains("Me"))
    310                 type = "Windows Me";
    311             else if (userAgent.Contains("NT 4"))
    312                 type = "Windows NT4";
    313             else if (userAgent.Contains("Unix"))
    314                 type = "UNIX";
    315             else if (userAgent.Contains("Linux"))
    316                 type = "Linux";
    317             else if (userAgent.Contains("SunOS"))
    318                 type = "SunOS";
    319             else
    320                 type = "未知";
    321 
    322             return type;
    323         }
    324 
    325         /// <summary>
    326         /// 獲得請求客戶端的操作系統名稱
    327         /// </summary>
    328         /// <returns></returns>
    329         public static string GetOSName()
    330         {
    331             string name = HttpContext.Current.Request.Browser.Platform;
    332             if (string.IsNullOrEmpty(name))
    333                 return "未知";
    334 
    335             return name;
    336         }
    337 
    338         /// <summary>
    339         /// 判斷是否是瀏覽器請求
    340         /// </summary>
    341         /// <returns></returns>
    342         public static bool IsBrowser()
    343         {
    344             string name = GetBrowserName();
    345             foreach (string item in _browserlist)
    346             {
    347                 if (name.Contains(item))
    348                     return true;
    349             }
    350             return false;
    351         }
    352 
    353         /// <summary>
    354         /// 是否是移動設備請求
    355         /// </summary>
    356         /// <returns></returns>
    357         public static bool IsMobile()
    358         {
    359             if (HttpContext.Current.Request.Browser.IsMobileDevice)
    360                 return true;
    361 
    362             bool isTablet = false;
    363             if (bool.TryParse(HttpContext.Current.Request.Browser["IsTablet"], out isTablet) && isTablet)
    364                 return true;
    365 
    366             return false;
    367         }
    368 
    369         /// <summary>
    370         /// 判斷是否是搜索引擎爬蟲請求
    371         /// </summary>
    372         /// <returns></returns>
    373         public static bool IsCrawler()
    374         {
    375             bool result = HttpContext.Current.Request.Browser.Crawler;
    376             if (!result)
    377             {
    378                 string referrer = GetUrlReferrer();
    379                 if (referrer.Length > 0)
    380                 {
    381                     foreach (string item in _searchenginelist)
    382                     {
    383                         if (referrer.Contains(item))
    384                             return true;
    385                     }
    386                 }
    387             }
    388             return result;
    389         }
    390 
    391         #endregion 客戶端信息

     

  • ConverterHelper 【類型轉換幫助類】

    Json類型數據的轉換是通過開源類庫Json.Net來實現,利用反射將DataTable對象轉換為List對象,字符串轉換為其他常用類型

 

  1  /// <summary>
  2     /// 類型轉換助手
  3     /// </summary>
  4     public static class ConverterHelper
  5     {
  6         /// <summary>
  7         /// 利用反射和泛型
  8         /// </summary>
  9         /// <param name="dt">DataTable 對象</param>
 10         /// <returns></returns>
 11         public static List<T> DataTableToList<T>(DataTable dt) where T : class, new()
 12         {
 13             // 定義集合
 14             List<T> ts = new List<T>();
 15 
 16             // 獲得此模型的類型
 17             Type type = typeof(T);
 18             //定義一個臨時變量
 19             string tempName = string.Empty;
 20             //遍歷DataTable中所有的數據行
 21             foreach (DataRow dr in dt.Rows)
 22             {
 23                 T t = new T();
 24                 // 獲得此模型的公共屬性
 25                 PropertyInfo[] propertys = t.GetType().GetProperties();
 26                 //遍歷該對象的所有屬性
 27                 foreach (PropertyInfo pi in propertys)
 28                 {
 29                     tempName = pi.Name;//將屬性名稱賦值給臨時變量
 30                                        //檢查DataTable是否包含此列(列名==對象的屬性名)
 31                     if (dt.Columns.Contains(tempName))
 32                     {
 33                         //取值
 34                         object value = dr[tempName];
 35                         //如果非空,則賦給對象的屬性
 36                         if (value != DBNull.Value)
 37                             pi.SetValue(t, value, null);
 38                     }
 39                 }
 40                 //對象添加到泛型集合中
 41                 ts.Add(t);
 42             }
 43 
 44             return ts;
 45         }
 46 
 47         /// <summary>
 48         /// 將object對象轉換為Json數據
 49         /// </summary>
 50         /// <param name="obj">object對象</param>
 51         /// <returns>轉換后的json字符串</returns>
 52         public static string ObjectToJson(object obj)
 53         {
 54             return JsonConvert.SerializeObject(obj);
 55         }
 56 
 57         /// <summary>
 58         /// 將Json對象轉換為T對象
 59         /// </summary>
 60         /// <typeparam name="T">對象的類型</typeparam>
 61         /// <param name="jsonString">json對象字符串</param>
 62         /// <returns>由字符串轉換得到的T對象</returns>
 63         public static T JsonToObject<T>(string jsonString)
 64         {
 65             return JsonConvert.DeserializeObject<T>(jsonString);
 66         }
 67 
 68         /// <summary>
 69         /// 從字符串中獲取數據
 70         /// </summary>
 71         /// <param name="content">源字符串</param>
 72         /// <returns>字符串中的值</returns>
 73         public static string GetContent(string content)
 74         {
 75             return (String.IsNullOrEmpty(content) ? null : content);
 76         }
 77 
 78         /// <summary>
 79         /// 將int轉換為bool類型
 80         /// </summary>
 81         /// <param name="value"></param>
 82         /// <returns></returns>
 83         public static bool ConvertIntToBool(int value)
 84         {
 85             return (value > 0 ? true : false);
 86         }
 87 
 88         #region 轉Int
 89 
 90         /// <summary>
 91         /// 將string類型轉換成int類型
 92         /// </summary>
 93         /// <param name="s">目標字符串</param>
 94         /// <param name="defaultValue">默認值</param>
 95         /// <returns></returns>
 96         public static int StringToInt(string s, int defaultValue)
 97         {
 98             if (!string.IsNullOrWhiteSpace(s))
 99             {
100                 int result;
101                 if (int.TryParse(s, out result))
102                     return result;
103             }
104 
105             return defaultValue;
106         }
107 
108         /// <summary>
109         /// 將string類型轉換成int類型
110         /// </summary>
111         /// <param name="s">目標字符串</param>
112         /// <returns></returns>
113         public static int StringToInt(string s)
114         {
115             return StringToInt(s, 0);
116         }
117 
118         /// <summary>
119         /// 將object類型轉換成int類型
120         /// </summary>
121         /// <param name="s">目標對象</param>
122         /// <param name="defaultValue">默認值</param>
123         /// <returns></returns>
124         public static int ObjectToInt(object o, int defaultValue)
125         {
126             if (o != null)
127                 return StringToInt(o.ToString(), defaultValue);
128 
129             return defaultValue;
130         }
131 
132         /// <summary>
133         /// 將object類型轉換成int類型
134         /// </summary>
135         /// <param name="s">目標對象</param>
136         /// <returns></returns>
137         public static int ObjectToInt(object o)
138         {
139             return ObjectToInt(o, 0);
140         }
141 
142         #endregion 轉Int
143 
144         #region 轉Bool
145 
146         /// <summary>
147         /// 將string類型轉換成bool類型
148         /// </summary>
149         /// <param name="s">目標字符串</param>
150         /// <param name="defaultValue">默認值</param>
151         /// <returns></returns>
152         public static bool StringToBool(string s, bool defaultValue)
153         {
154             if (s.ToLower().Equals("false"))
155                 return false;
156             else if (s.ToLower().Equals("true"))
157                 return true;
158 
159             return defaultValue;
160         }
161 
162         /// <summary>
163         /// 將string類型轉換成bool類型
164         /// </summary>
165         /// <param name="s">目標字符串</param>
166         /// <returns></returns>
167         public static bool ToBool(string s)
168         {
169             return StringToBool(s, false);
170         }
171 
172         /// <summary>
173         /// 將object類型轉換成bool類型
174         /// </summary>
175         /// <param name="s">目標對象</param>
176         /// <param name="defaultValue">默認值</param>
177         /// <returns></returns>
178         public static bool ObjectToBool(object o, bool defaultValue)
179         {
180             if (o != null)
181                 return StringToBool(o.ToString(), defaultValue);
182 
183             return defaultValue;
184         }
185 
186         /// <summary>
187         /// 將object類型轉換成bool類型
188         /// </summary>
189         /// <param name="s">目標對象</param>
190         /// <returns></returns>
191         public static bool ObjectToBool(object o)
192         {
193             return ObjectToBool(o, false);
194         }
195 
196         #endregion 轉Bool
197 
198         #region 轉DateTime
199 
200         /// <summary>
201         /// 將string類型轉換成datetime類型
202         /// </summary>
203         /// <param name="s">目標字符串</param>
204         /// <param name="defaultValue">默認值</param>
205         /// <returns></returns>
206         public static DateTime StringToDateTime(string s, DateTime defaultValue)
207         {
208             if (!string.IsNullOrWhiteSpace(s))
209             {
210                 DateTime result;
211                 if (DateTime.TryParse(s, out result))
212                     return result;
213             }
214             return defaultValue;
215         }
216 
217         /// <summary>
218         /// 將string類型轉換成datetime類型
219         /// </summary>
220         /// <param name="s">目標字符串</param>
221         /// <returns></returns>
222         public static DateTime StringToDateTime(string s)
223         {
224             return StringToDateTime(s, DateTime.Now);
225         }
226 
227         /// <summary>
228         /// 將object類型轉換成datetime類型
229         /// </summary>
230         /// <param name="s">目標對象</param>
231         /// <param name="defaultValue">默認值</param>
232         /// <returns></returns>
233         public static DateTime ObjectToDateTime(object o, DateTime defaultValue)
234         {
235             if (o != null)
236                 return StringToDateTime(o.ToString(), defaultValue);
237 
238             return defaultValue;
239         }
240 
241         /// <summary>
242         /// 將object類型轉換成datetime類型
243         /// </summary>
244         /// <param name="s">目標對象</param>
245         /// <returns></returns>
246         public static DateTime ObjectToDateTime(object o)
247         {
248             return ObjectToDateTime(o, DateTime.Now);
249         }
250 
251         #endregion 轉DateTime
252 
253         #region 轉Decimal
254 
255         /// <summary>
256         /// 將string類型轉換成decimal類型
257         /// </summary>
258         /// <param name="s">目標字符串</param>
259         /// <param name="defaultValue">默認值</param>
260         /// <returns></returns>
261         public static decimal StringToDecimal(string s, decimal defaultValue)
262         {
263             if (!string.IsNullOrWhiteSpace(s))
264             {
265                 decimal result;
266                 if (decimal.TryParse(s, out result))
267                     return result;
268             }
269 
270             return defaultValue;
271         }
272 
273         /// <summary>
274         /// 將string類型轉換成decimal類型
275         /// </summary>
276         /// <param name="s">目標字符串</param>
277         /// <returns></returns>
278         public static decimal StringToDecimal(string s)
279         {
280             return StringToDecimal(s, 0m);
281         }
282 
283         /// <summary>
284         /// 將object類型轉換成decimal類型
285         /// </summary>
286         /// <param name="s">目標對象</param>
287         /// <param name="defaultValue">默認值</param>
288         /// <returns></returns>
289         public static decimal ObjectToDecimal(object o, decimal defaultValue)
290         {
291             if (o != null)
292                 return StringToDecimal(o.ToString(), defaultValue);
293 
294             return defaultValue;
295         }
296 
297         /// <summary>
298         /// 將object類型轉換成decimal類型
299         /// </summary>
300         /// <param name="s">目標對象</param>
301         /// <returns></returns>
302         public static decimal ObjectToDecimal(object o)
303         {
304             return ObjectToDecimal(o, 0m);
305         }
306 
307         #endregion 轉Decimal
308     }

 

7.項目架構搭建之Models搭建

    參考 這里 了解 EF CodeFirst,首先對EF類庫進行引用,由于我的應用的使用的是SQLServer數據庫,所以需要對EntityFramework.SqlServer進行引用,如果不引用子在進行數據庫相關操作時會出錯,錯誤如下:

The Entity Framework provider type 'System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer' registered in the application config file for the ADO.NET provider with invariant name 'System.Data.SqlClient' could not be loaded

 

  1. 添加類庫引用
  2. 創建Entity

    創建一個類,繼承DbContext類,并在他的構造函數中設置連接字符串或者構造函數中傳遞配置文件中ConnectionStrings的name

  3. 創建數據模型models

    創建Web應用中用到的Model對應數據庫中的表,ViewModel另外設置,這里的models對應數據庫的數據表,User示例:

  4. 啟用數據遷移 EnableMigration
    1. 打開 Package Manager Console
    2. 執行命令 "Enable-Migrations",如果這個項目中有兩個或兩個以上的繼承DbContext類的Entity,需要制定Context的名稱,不然會提示有多個Context。
    3. 執行命令之后會生成一個 Migrations文件夾,文件夾下有一個Configuration文件,打開文件修改構造函數,設置 AutomaticMigrationsEnabled = true;


文章列表

arrow
arrow
    全站熱搜
    創作者介紹
    創作者 大師兄 的頭像
    大師兄

    IT工程師數位筆記本

    大師兄 發表在 痞客邦 留言(0) 人氣()