Implement site configuration files and XML serialization using xml serialization and Asp. Net Web Cache

Source: Internet
Author: User

Implement site configuration files and XML serialization using xml serialization and Asp. Net Web Cache

We often encounter such scenarios:
We have a business today. We need to add a field, but there may be changes in the future. We need to configure it as "active.
In general, the initial method is to add a configuration to the AppSettings of the Web. Config file. However, there is a problem, that is, to change the configuration node, the AppDomain needs to be restarted, which is very uncomfortable.
With a little flexibility, an xml file will be created and serialized for dynamic reading. But, brother! Do I not think it is too IO-intensive to read files every time? Especially when the usage frequency is high?

The code below is a lazy nonsense, and the key points are all commented out, which is not a profound technology:


First, configure the file (note that the Config path must be self-built and the code is not processed) and the corresponding configuration file code:

<? Xml version = "1.0" encoding = "UTF-8"?> <SimpleBizConfig xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance" xmlns: xsd = "http://www.w3.org/2001/XMLSchema"> <ID> 12 </ID> <Key> MyKey </Key> <ListSimple> <string> simple </string> <string> list </string> <string> set </string> </ListSimple> </SimpleBizConfig>

 

Using System. text; using gluton. web. configuration; using System. collections. generic; using System. linq; using System. web; namespace WebTest. models {public class SimpleBizConfig: ISimpleConfig {// <summary> // default configuration file path /// </summary> public string GetPath () {return "~ /Config/SimpleBizConfig. cfg ";} public string GetCacheKey () {return "~ /MyConfig_SimpleBizConfig ";} public SimpleBizConfig () {this. ID = 1; this. key = "MyKey"; this. listSimple = new List <string> ();} public int ID {get; set;} public string Key {get; set;} public List <string> ListSimple {get; set;} internal string Desc () {StringBuilder sb = new StringBuilder (); sb. append ("type: SimpleBizConfig "). append ("<br/>"); sb. append ("ID =" + this. ID. toString ()). append ("<br/>"); sb. append ("Key =" + this. key ). append ("<br/>"); sb. append ("list "). append ("<br/>"); for (int I = 0; I <this. listSimple. count; I ++) {sb. append ("index:" + I. toString () + ", value:" + ListSimple [I]). append ("<br/>");} return sb. toString ();}}}

 


Manage the configuration file class again:

 

Using System; using System. collections. generic; using System. IO; using System. linq; using System. runtime. interopServices; using System. text; using System. threading. tasks; using System. web; using System. web. caching; using System. xml. serialization; namespace gluton. web. configuration {public interface ISimpleConfig {string GetPath (); string GetCacheKey ();} public class ConfigManager {public static T GetConf Ig <T> () where T: class, ISimpleConfig, new () {T tmpT = new T (); string cacheKey = tmpT. getCacheKey (); // first try to get data from the cache T = GetFromCache <t> (cacheKey); // very depressing, no static generic interface if (T! = Null) {return t;} // No data in the cache. Read the configuration file XmlSerializer xmlSerializer = new XmlSerializer (typeof (T) directly. string configFilePath = HttpContext. current. server. mapPath (tmpT. getPath (); if (! File. exists (configFilePath) {// the file does not exist. initialize the file. You need to configure the file class to implement the default initialization action using (TextWriter writer = new StreamWriter (configFilePath )) {t = new T (); xmlSerializer. serialize (writer, t) ;}} else {using (FileStream fs = new FileStream (configFilePath, FileMode. open) {t = xmlSerializer. deserialize (fs) as T ;}// save it to the cache. Depending on the web cache file dependency function, you can modify the monitoring configuration file SetToCache <T> (cacheKey, configFilePath, t ); return t;} private static void SetToCache <T> (string cacheKey, string configFilePath, T t) where T: class, new () {HttpRuntime. cache. insert (cacheKey, t, new CacheDependency (configFilePath), // The file depends on the expired Cache. noAbsoluteExpiration, Cache. noSlidingExpiration, CacheItemPriority. notRemovable, null);} private static T GetFromCache <T> (string cacheKey) where T: class, new () {return HttpRuntime. cache [cacheKey] as T ;}}}

 

Look at the call method. A test method is added to HomeController:

 

using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Mvc;using Glutton.Web.Configuration;using WebTest.Models;namespace WebTest.Controllers{    public class HomeController : Controller    {        public ActionResult Index()        {            return View();        }        public ActionResult About()        {            ViewBag.Message = "Your application description page.";            return View();        }        public ActionResult Contact()        {            ViewBag.Message = "Your contact page.";            return View();        }        public string TestCfg()        {            return ConfigManager.GetConfig<SimpleBizConfig>().Desc();        }    }}

 

Look at the effect:-D:

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.