DBを使用しないデータの永続化
HttpApplicationとHttpModuleの勉強がてら作ってみました。
こういうのは手段としてはありなんでしょうか?
下記の動作を行います。
- http://localhost/Hogege/Group.add でグループ情報を追加、http://localhost/Hogege/Group.xml でグループ情報を表示します。
- アプリケーションがDiposeされるときにローカルのxmlファイルにグループ情報を書き込みます。
- また、ログイン後最初のリクエストでxmlファイルからグループ情報を読み込みします。
//HtmlApplication public class MvcApplication : System.Web.HttpApplication { public Dictionary<string, List<Group>> Groups = new Dictionary<string,List<Group>>(); public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( "Hogege" , "Hogege/{action}.{extention}" , new { controller = "Hogege", extention = "html" } ); routes.MapRoute( "Default", // Route name "{controller}/{action}/{id}", // URL with parameters new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults ); } protected void Application_Start() { AreaRegistration.RegisterAllAreas(); RegisterRoutes(RouteTable.Routes); } }
//データのロード、セーブを行うHttpModule public class MyHttpModule : IHttpModule { public MyHttpModule() { } public void Init(HttpApplication context) { context.Disposed += new EventHandler(context_Disposed); context.PostAuthorizeRequest += new EventHandler(context_PostAuthorizeRequest); } void context_PostAuthorizeRequest(object sender, EventArgs e) { var app = (MvcApplication)sender; if (!app.Request.IsAuthenticated) return; //ログインユーザーのデータをロード if (!app.Groups.ContainsKey(app.User.Identity.Name)) { var Groups = new List<Group>(); var grpEles = Read(app.User.Identity.Name, "Groups"); if(grpEles != null) { foreach (var grpEle in grpEles.Elements()) Groups.Add(Group.CreateInstance(grpEle)); app.Groups.Add(app.User.Identity.Name, Groups); } } } void context_Disposed(object sender, EventArgs e) { var app = (MvcApplication)sender; try { foreach (var usr in app.Groups.Keys) Write(usr, "Groups", app.Groups[usr].Serialize()); } catch (Exception exc) { exc.ToString(); } } private XElement Read(string usr, string type) { StreamReader sr = null; XElement result = null; try { var path = string.Format(@"c:\work\{0}_{1}.xml", usr, type); if(File.Exist(path) { sr = new StreamReader(new FileStream(path , FileMode.Open , FileAccess.Read , FileShare.Read) , Encoding.UTF8); var xdoc = XDocument.Load(sr); result = xdoc.Root; } } finally { if (sr != null) sr.Close(); } return result; } private void Write(string usr,string type, XElement data) { StreamWriter sw = null; try { var path = string.Format(@"c:\work\{0}_{1}.xml", usr, type); sw = new StreamWriter(new FileStream(path , FileMode.OpenOrCreate , FileAccess.Write , FileShare.Read) , Encoding.UTF8); var xdoc = new XDocument(data); xdoc.Declaration = new XDeclaration("1.0", "utf-8", "yes"); xdoc.Save(sw); } finally { if(sw != null) sw.Close(); } } }
//使用するデータクラス public class Group { public string UserId {get;set;} public string GroupId {get;set;} public string GroupName {get;set;} public XElement Serialize() { XDocument xdoc = new XDocument(new XElement("Group" , new XElement("UserId", new XAttribute("value", UserId)) , new XElement("GroupId", new XAttribute("value", GroupId)) , new XElement("GroupName", new XAttribute("value", GroupName)) )); return xdoc.Root; } static public Group CreateInstance(XElement element) { var obj = new Group(); obj.UserId = element.Element("UserId").Attribute("value").Value; obj.GroupId = element.Element("GroupId").Attribute("value").Value; obj.GroupName = element.Element("GroupName").Attribute("value").Value; return obj; } } //拡張メソッド static public class GroupExtentions { static public XElement Serialize(this IEnumerable<Group> grps) { var ele = new XElement("Groups"); foreach (var grp in grps) ele.Add(grp.Serialize()); return ele; } }
//コントローラー public class HogegeController : Controller { public ActionResult Index() { return new EmptyResult(); } [HttpGet] public ActionResult Group(string extention) { if (Request.IsAuthenticated) { var groups = ((MvcApplication)HttpContext.ApplicationInstance).Groups; if (extention == "xml") { return new ContentResult() { ContentType = "Application/xml" , Content = groups[User.Identity.Name].Serialize().ToString() }; } else if (extention == "add") { if(!groups.ContainsKey(User.Identity.Name)) groups.Add(User.Identity.Name, new List<Group>()); var newGrp = new Group(){GroupId = DateTime.Now.Ticks.ToString() ,GroupName = "グループ_" + DateTime.Now.Ticks.ToString() ,UserId = User.Identity.Name }; groups[User.Identity.Name].Add(newGrp); return new ContentResult() { Content = "Add ok" }; } } return new EmptyResult(); } }