OSDN Git Service

アセンブリ名を表す ApplicationSettings.AssemblyName を追加
[opentween/open-tween.git] / OpenTween / Setting / SettingBase.cs
1 // OpenTween - Client of Twitter
2 // Copyright (c) 2007-2011 kiri_feather (@kiri_feather) <kiri.feather@gmail.com>
3 //           (c) 2008-2011 Moz (@syo68k)
4 //           (c) 2008-2011 takeshik (@takeshik) <http://www.takeshik.org/>
5 //           (c) 2010-2011 anis774 (@anis774) <http://d.hatena.ne.jp/anis774/>
6 //           (c) 2010-2011 fantasticswallow (@f_swallow) <http://twitter.com/f_swallow>
7 //           (c) 2011      kim_upsilon (@kim_upsilon) <https://upsilo.net/~upsilon/>
8 // All rights reserved.
9 // 
10 // This file is part of OpenTween.
11 // 
12 // This program is free software; you can redistribute it and/or modify it
13 // under the terms of the GNU General Public License as published by the Free
14 // Software Foundation; either version 3 of the License, or (at your option)
15 // any later version.
16 // 
17 // This program is distributed in the hope that it will be useful, but
18 // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
19 // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
20 // for more details. 
21 // 
22 // You should have received a copy of the GNU General Public License along
23 // with this program. If not, see <http://www.gnu.org/licenses/>, or write to
24 // the Free Software Foundation, Inc., 51 Franklin Street - Fifth Floor,
25 // Boston, MA 02110-1301, USA.
26
27 using System;
28 using System.Collections.Generic;
29 using System.Linq;
30 using System.Text;
31 using System.IO;
32 using System.Xml;
33 using System.Xml.Serialization;
34 using System.Windows.Forms;
35 using System.Threading;
36
37 namespace OpenTween
38 {
39     abstract public class SettingBase<T> where T : class, new()
40     {
41         /// <summary>
42         /// XML に含まれる追加データを保持するフィールド
43         /// </summary>
44         /// <remarks>
45         /// 他バージョンから設定をコピーした場合など、クラスに存在しないフィールドが
46         /// XML に含まれていた場合に破棄せず保持するため必要となる。
47         /// </remarks>
48         [XmlAnyElement]
49         public XmlElement[] ExtraElements;
50
51         private static object lockObj = new object();
52
53         protected static T LoadSettings(string FileId)
54         {
55             try
56             {
57                 var settingFilePath = GetSettingFilePath(FileId);
58                 if (!File.Exists(settingFilePath))
59                 {
60                     return new T();
61                 }
62
63                 lock (lockObj)
64                 {
65                     using (FileStream fs = new FileStream(settingFilePath, FileMode.Open, FileAccess.Read))
66                     {
67                         fs.Position = 0;
68                         XmlSerializer xs = new XmlSerializer(typeof(T));
69                         T instance = (T)xs.Deserialize(fs);
70                         return instance;
71                     }
72                 }
73             }
74             catch (FileNotFoundException)
75             {
76                 return new T();
77             }
78             catch (Exception)
79             {
80                 string backupFile = Path.Combine(
81                         Path.Combine(
82                             Application.StartupPath,
83                             ApplicationSettings.AssemblyName + "Backup1st"),
84                         typeof(T).Name + FileId + ".xml");
85                 if (File.Exists(backupFile))
86                 {
87                     try
88                     {
89                         lock (lockObj)
90                         {
91                             using (FileStream fs = new FileStream(backupFile, FileMode.Open, FileAccess.Read))
92                             {
93                                 fs.Position = 0;
94                                 XmlSerializer xs = new XmlSerializer(typeof(T));
95                                 T instance = (T)xs.Deserialize(fs);
96                                 MessageBox.Show("File: " + GetSettingFilePath(FileId) + Environment.NewLine + "Use old setting file, because application can't read this setting file.");
97                                 return instance;
98                             }
99                         }
100                     }
101                     catch (Exception)
102                     {
103                     }
104                 }
105                 MessageBox.Show("File: " + GetSettingFilePath(FileId) + Environment.NewLine + "Use default setting, because application can't read this setting file.");
106                 return new T();
107                 //ex.Data.Add("FilePath", GetSettingFilePath(FileId));
108                 //FileInfo fi = new IO.FileInfo(GetSettingFilePath(FileId));
109                 //ex.Data.Add("FileSize", fi.Length.ToString());
110                 //ex.Data.Add("FileData", File.ReadAllText(GetSettingFilePath(FileId)));
111                 //throw;
112             }
113         }
114
115         protected static T LoadSettings()
116         {
117             return LoadSettings("");
118         }
119
120         protected static void SaveSettings(T instance, string fileId)
121         {
122             const int SaveRetryMax = 3;
123
124             if (instance == null)
125                 return;
126
127             var retryCount = 0;
128             Exception lastException = null;
129
130             var filePath = GetSettingFilePath(fileId);
131             do
132             {
133                 var tmpfilePath = GetSettingFilePath("_" + Path.GetRandomFileName());
134                 try
135                 {
136                     lock (lockObj)
137                     {
138                         using (var stream = new FileStream(tmpfilePath, FileMode.Create, FileAccess.Write))
139                         {
140                             var serializer = new XmlSerializer(typeof(T));
141                             serializer.Serialize(stream, instance);
142                             stream.Flush();
143                         }
144
145                         var fileInfo = new FileInfo(tmpfilePath);
146                         if (fileInfo.Length != 0)
147                         {
148                             // 成功
149                             File.Copy(tmpfilePath, filePath, true);
150                             return;
151                         }
152                     }
153                 }
154                 catch (Exception e)
155                 {
156                     lastException = e;
157                 }
158                 finally
159                 {
160                     try
161                     {
162                         if (File.Exists(tmpfilePath))
163                             File.Delete(tmpfilePath);
164                     }
165                     catch (Exception) { }
166                 }
167
168                 // リトライ
169                 retryCount++;
170                 Thread.Sleep(1000);
171
172             } while (retryCount <= SaveRetryMax);
173
174             // リトライオーバー
175             if (lastException != null)
176                 MyCommon.ExceptionOut(lastException);
177
178             MessageBox.Show("Can't write setting XML.(" + filePath + ")", "Save Settings", MessageBoxButtons.OK);
179         }
180
181         protected static void SaveSettings(T Instance)
182         {
183             SaveSettings(Instance, "");
184         }
185
186         public static string GetSettingFilePath(string FileId)
187         {
188             return Path.Combine(MyCommon.settingPath, typeof(T).Name + FileId + ".xml");
189         }
190     }
191 }