OSDN Git Service

string.Copy() など余分な処理を除去
[opentween/open-tween.git] / OpenTween / MyCommon.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      Egtra (@egtra) <http://dev.activebasic.com/egtra/>
8 //           (c) 2011      kim_upsilon (@kim_upsilon) <https://upsilo.net/~upsilon/>
9 // All rights reserved.
10 // 
11 // This file is part of OpenTween.
12 // 
13 // This program is free software; you can redistribute it and/or modify it
14 // under the terms of the GNU General public License as published by the Free
15 // Software Foundation; either version 3 of the License, or (at your option)
16 // any later version.
17 // 
18 // This program is distributed in the hope that it will be useful, but
19 // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
20 // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General public License
21 // for more details. 
22 // 
23 // You should have received a copy of the GNU General public License along
24 // with this program. if not, see <http://www.gnu.org/licenses/>, or write to
25 // the Free Software Foundation, Inc., 51 Franklin Street - Fifth Floor,
26 // Boston, MA 02110-1301, USA.
27
28 using System;
29 using System.Collections.Generic;
30 using System.Linq;
31 using System.Text;
32 using System.IO;
33 using System.Windows.Forms;
34 using System.Web;
35 using System.Globalization;
36 using System.Security.Cryptography;
37 using System.Drawing;
38 using System.Drawing.Imaging;
39 using System.Collections;
40 using System.Security.Principal;
41 using System.Runtime.Serialization.Json;
42 using System.Reflection;
43 using System.Diagnostics;
44 using System.Text.RegularExpressions;
45 using System.Net.NetworkInformation;
46 using System.Runtime.InteropServices;
47 using OpenTween.Api;
48
49 namespace OpenTween
50 {
51     public sealed class MyCommon
52     {
53         private static readonly object LockObj = new object();
54         public static bool _endingFlag;        //終了フラグ
55         public static string cultureStr = null;
56         public static string settingPath;
57
58         public enum IconSizes
59         {
60             IconNone = 0,
61             Icon16 = 1,
62             Icon24 = 2,
63             Icon48 = 3,
64             Icon48_2 = 4,
65         }
66
67         public enum NameBalloonEnum
68         {
69             None,
70             UserID,
71             NickName,
72         }
73
74         public enum DispTitleEnum
75         {
76             None,
77             Ver,
78             Post,
79             UnreadRepCount,
80             UnreadAllCount,
81             UnreadAllRepCount,
82             UnreadCountAllCount,
83             OwnStatus,
84         }
85
86         public enum LogUnitEnum
87         {
88             Minute,
89             Hour,
90             Day,
91         }
92
93         public enum UploadFileType
94         {
95             Invalid,
96             Picture,
97             MultiMedia,
98         }
99
100         public enum UrlConverter
101         {
102             TinyUrl,
103             Isgd,
104             Twurl,
105             Bitly,
106             Jmp,
107             Uxnu,
108             //特殊
109             Nicoms,
110             //廃止
111             Unu = -1,
112         }
113
114         public enum OutputzUrlmode
115         {
116             twittercom,
117             twittercomWithUsername,
118         }
119
120         public enum HITRESULT
121         {
122             None,
123             Copy,
124             CopyAndMark,
125             Move,
126             Exclude,
127         }
128
129         public enum HttpTimeOut
130         {
131             MinValue = 10,
132             MaxValue = 120,
133             DefaultValue = 20,
134         }
135
136         //Backgroundworkerへ処理種別を通知するための引数用enum
137         public enum WORKERTYPE
138         {
139             Timeline,                //タイムライン取得
140             Reply,                   //返信取得
141             DirectMessegeRcv,        //受信DM取得
142             DirectMessegeSnt,        //送信DM取得
143             PostMessage,             //発言POST
144             FavAdd,                  //Fav追加
145             FavRemove,               //Fav削除
146             Follower,                //Followerリスト取得
147             Favorites,               //Fav取得
148             Retweet,                 //Retweetする
149             PublicSearch,            //公式検索
150             List,                    //Lists
151             Related,                 //関連発言
152             UserStream,              //UserStream
153             UserTimeline,            //UserTimeline
154             BlockIds,                //Blocking/ids
155             Configuration,           //Twitter Configuration読み込み
156             //////
157             ErrorState,              //エラー表示のみで後処理終了(認証エラー時など)
158         }
159
160         public static class DEFAULTTAB
161         {
162             public const string RECENT = "Recent";
163             public const string REPLY = "Reply";
164             public const string DM = "Direct";
165             public const string FAV = "Favorites";
166
167             //private string dummy;
168
169             //private object ReferenceEquals()
170             //{
171             //    return new object();
172             //}
173             //private object Equals()
174             //{
175             //    return new object();
176             //}
177         }
178
179         public static readonly object Block = null;
180         public static bool TraceFlag = false;
181
182 #if DEBUG
183         public static bool DebugBuild = true;
184 #else
185         public static bool DebugBuild = false;
186 #endif
187
188         public enum ACCOUNT_STATE
189         {
190             Valid,
191             Invalid,
192         }
193
194         public enum REPLY_ICONSTATE
195         {
196             None,
197             StaticIcon,
198             BlinkIcon,
199         }
200
201         [FlagsAttribute()]
202         public enum EVENTTYPE
203         {
204             None = 0,
205             Favorite = 1,
206             Unfavorite = 2,
207             Follow = 4,
208             ListMemberAdded = 8,
209             ListMemberRemoved = 16,
210             Block = 32,
211             Unblock = 64,
212             UserUpdate = 128,
213             Deleted = 256,
214             ListCreated = 512,
215             ListUpdated = 1024,
216             Unfollow = 2048,
217
218             All = (None | Favorite | Unfavorite | Follow | ListMemberAdded | ListMemberRemoved |
219                    Block | Unblock | UserUpdate | Deleted | ListCreated | ListUpdated | Unfollow),
220         }
221
222         public static string GetErrorLogPath()
223         {
224             return Path.Combine(Path.GetDirectoryName(MyCommon.EntryAssembly.Location), "ErrorLogs");
225         }
226
227         public static void TraceOut(Exception ex, string Message)
228         {
229             var buf = ExceptionOutMessage(ex);
230             TraceOut(TraceFlag, Message + Environment.NewLine + buf);
231         }
232
233         public static void TraceOut(string Message)
234         {
235             TraceOut(TraceFlag, Message);
236         }
237
238         public static void TraceOut(bool OutputFlag, string Message)
239         {
240             lock (LockObj)
241             {
242                 if (!OutputFlag) return;
243
244                 var logPath = MyCommon.GetErrorLogPath();
245                 if (!Directory.Exists(logPath))
246                     Directory.CreateDirectory(logPath);
247
248                 var now = DateTime.Now;
249                 var fileName = string.Format("{0}Trace-{1:0000}{2:00}{3:00}-{4:00}{5:00}{6:00}.log", GetAssemblyName(), now.Year, now.Month, now.Day, now.Hour, now.Minute, now.Second);
250                 fileName = Path.Combine(logPath, fileName);
251
252                 using (var writer = new StreamWriter(fileName))
253                 {
254                     writer.WriteLine("**** TraceOut: {0} ****", DateTime.Now.ToString());
255                     writer.WriteLine(Properties.Resources.TraceOutText1, ApplicationSettings.FeedbackEmailAddress);
256                     writer.WriteLine(Properties.Resources.TraceOutText2, ApplicationSettings.FeedbackTwitterName);
257                     writer.WriteLine();
258                     writer.WriteLine(Properties.Resources.TraceOutText3);
259                     writer.WriteLine(Properties.Resources.TraceOutText4, Environment.OSVersion.VersionString);
260                     writer.WriteLine(Properties.Resources.TraceOutText5, Environment.Version.ToString());
261                     writer.WriteLine(Properties.Resources.TraceOutText6, MyCommon.GetAssemblyName(), fileVersion);
262                     writer.WriteLine(Message);
263                     writer.WriteLine();
264                 }
265             }
266         }
267
268         // エラー内容をバッファに書き出し
269         // 注意:最終的にファイル出力されるエラーログに記録されるため次の情報は書き出さない
270         // 文頭メッセージ、権限、動作環境
271         // Dataプロパティにある終了許可フラグのパースもここで行う
272
273         public static string ExceptionOutMessage(Exception ex)
274         {
275             bool IsTerminatePermission = true;
276             return ExceptionOutMessage(ex, ref IsTerminatePermission);
277         }
278
279         public static string ExceptionOutMessage(Exception ex, ref bool IsTerminatePermission)
280         {
281             if (ex == null) return "";
282
283             var buf = new StringBuilder();
284
285             buf.AppendFormat(Properties.Resources.UnhandledExceptionText8, ex.GetType().FullName, ex.Message);
286             buf.AppendLine();
287             if (ex.Data != null)
288             {
289                 var needHeader = true;
290                 foreach (DictionaryEntry dt in ex.Data)
291                 {
292                     if (needHeader)
293                     {
294                         buf.AppendLine();
295                         buf.AppendLine("-------Extra Information-------");
296                         needHeader = false;
297                     }
298                     buf.AppendFormat("{0}  :  {1}", dt.Key, dt.Value);
299                     buf.AppendLine();
300                     if (dt.Key.Equals("IsTerminatePermission"))
301                     {
302                         IsTerminatePermission = (bool)dt.Value;
303                     }
304                 }
305                 if (!needHeader)
306                 {
307                     buf.AppendLine("-----End Extra Information-----");
308                 }
309             }
310             buf.AppendLine(ex.StackTrace);
311             buf.AppendLine();
312
313             //InnerExceptionが存在する場合書き出す
314             var _ex = ex.InnerException;
315             var nesting = 0;
316             while (_ex != null)
317             {
318                 buf.AppendFormat("-----InnerException[{0}]-----\r\n", nesting);
319                 buf.AppendLine();
320                 buf.AppendFormat(Properties.Resources.UnhandledExceptionText8, _ex.GetType().FullName, _ex.Message);
321                 buf.AppendLine();
322                 if (_ex.Data != null)
323                 {
324                     var needHeader = true;
325
326                     foreach (DictionaryEntry dt in _ex.Data)
327                     {
328                         if (needHeader)
329                         {
330                             buf.AppendLine();
331                             buf.AppendLine("-------Extra Information-------");
332                             needHeader = false;
333                         }
334                         buf.AppendFormat("{0}  :  {1}", dt.Key, dt.Value);
335                         if (dt.Key.Equals("IsTerminatePermission"))
336                         {
337                             IsTerminatePermission = (bool)dt.Value;
338                         }
339                     }
340                     if (!needHeader)
341                     {
342                         buf.AppendLine("-----End Extra Information-----");
343                     }
344                 }
345                 buf.AppendLine(_ex.StackTrace);
346                 buf.AppendLine();
347                 nesting++;
348                 _ex = _ex.InnerException;
349             }
350             return buf.ToString();
351         }
352
353         public static bool ExceptionOut(Exception ex)
354         {
355             lock (LockObj)
356             {
357                 var IsTerminatePermission = true;
358
359                 var logPath = MyCommon.GetErrorLogPath();
360                 if (!Directory.Exists(logPath))
361                     Directory.CreateDirectory(logPath);
362
363                 var now = DateTime.Now;
364                 var fileName = string.Format("{0}-{1:0000}{2:00}{3:00}-{4:00}{5:00}{6:00}.log", GetAssemblyName(), now.Year, now.Month, now.Day, now.Hour, now.Minute, now.Second);
365                 fileName = Path.Combine(logPath, fileName);
366
367                 using (var writer = new StreamWriter(fileName))
368                 {
369                     var ident = WindowsIdentity.GetCurrent();
370                     var princ = new WindowsPrincipal(ident);
371
372                     writer.WriteLine(Properties.Resources.UnhandledExceptionText1, DateTime.Now.ToString());
373                     writer.WriteLine(Properties.Resources.UnhandledExceptionText2, ApplicationSettings.FeedbackEmailAddress);
374                     writer.WriteLine(Properties.Resources.UnhandledExceptionText3, ApplicationSettings.FeedbackTwitterName);
375                     // 権限書き出し
376                     writer.WriteLine(Properties.Resources.UnhandledExceptionText11 + princ.IsInRole(WindowsBuiltInRole.Administrator).ToString());
377                     writer.WriteLine(Properties.Resources.UnhandledExceptionText12 + princ.IsInRole(WindowsBuiltInRole.User).ToString());
378                     writer.WriteLine();
379                     // OSVersion,AppVersion書き出し
380                     writer.WriteLine(Properties.Resources.UnhandledExceptionText4);
381                     writer.WriteLine(Properties.Resources.UnhandledExceptionText5, Environment.OSVersion.VersionString);
382                     writer.WriteLine(Properties.Resources.UnhandledExceptionText6, Environment.Version.ToString());
383                     writer.WriteLine(Properties.Resources.UnhandledExceptionText7, MyCommon.GetAssemblyName(), fileVersion);
384
385                     writer.Write(ExceptionOutMessage(ex, ref IsTerminatePermission));
386                     writer.Flush();
387                 }
388
389                 switch (MessageBox.Show(MyCommon.ReplaceAppName(string.Format(Properties.Resources.UnhandledExceptionText9, fileName, ApplicationSettings.FeedbackEmailAddress, ApplicationSettings.FeedbackTwitterName, Environment.NewLine)),
390                                    Properties.Resources.UnhandledExceptionText10, MessageBoxButtons.YesNoCancel, MessageBoxIcon.Error))
391                 {
392                     case DialogResult.Yes:
393                         Process.Start(fileName);
394                         return false;
395                     case DialogResult.No:
396                         return false;
397                     case DialogResult.Cancel:
398                         return IsTerminatePermission;
399                     default:
400                         throw new Exception("");
401                 }
402             }
403         }
404
405         /// <summary>
406         /// URLに含まれているマルチバイト文字列を%xx形式でエンコードします。
407         /// <newpara>
408         /// マルチバイト文字のコードはUTF-8またはUnicodeで自動的に判断します。
409         /// </newpara>
410         /// </summary>
411         /// <param name="_input">エンコード対象のURL</param>
412         /// <returns>マルチバイト文字の部分をUTF-8/%xx形式でエンコードした文字列を返します。</returns>
413
414         public static string urlEncodeMultibyteChar(string _input)
415         {
416             Uri uri = null;
417             var sb = new StringBuilder(256);
418             var result = "";
419             var c_ = 'd';
420             foreach (var c in _input)
421             {
422                 c_ = c;
423                 if (Convert.ToInt32(c) > 127 || c == '%') break;
424             }
425             if (Convert.ToInt32(c_) <= 127 && c_ != '%') return _input;
426
427             var input = Uri.UnescapeDataString(_input);
428         retry:
429             foreach (char c in input)
430             {
431                 if (Convert.ToInt32(c) > 255)
432                 {
433                     // Unicodeの場合(1charが複数のバイトで構成されている)
434                     // Uriクラスをnewして再構成し、入力をPathAndQueryのみとしてやり直す
435                     foreach (var b in Encoding.UTF8.GetBytes(c.ToString()))
436                     {
437                         sb.AppendFormat("%{0:X2}", b);
438                     }
439                 }
440                 else if (Convert.ToInt32(c) > 127 || c == '%')
441                 {
442                     // UTF-8の場合
443                     // Uriクラスをnewして再構成し、入力をinputからAuthority部分を除去してやり直す
444                     if (uri == null)
445                     {
446                         uri = new Uri(input);
447                         input = input.Remove(0, uri.GetLeftPart(UriPartial.Authority).Length);
448                         sb.Length = 0;
449                         goto retry;
450                     }
451                     else
452                     {
453                         sb.Append("%" + Convert.ToInt16(c).ToString("X2").ToUpper());
454                     }
455                 }
456                 else
457                 {
458                     sb.Append(c);
459                 }
460             }
461
462             if (uri == null)
463             {
464                 result = sb.ToString();
465             }
466             else
467             {
468                 result = uri.GetLeftPart(UriPartial.Authority) + sb.ToString();
469             }
470
471             return result;
472         }
473
474         ////// <summary>
475         ////// URLのドメイン名をPunycode展開します。
476         ////// <para>
477         ////// ドメイン名がIDNでない場合はそのまま返します。
478         ////// ドメインラベルの区切り文字はFULLSTOP(.、U002E)に置き換えられます。
479         ////// </para>
480         ////// </summary>
481         ////// <param name="input">展開対象のURL</param>
482         ////// <returns>IDNが含まれていた場合はPunycodeに展開したURLをを返します。Punycode展開時にエラーが発生した場合はnullを返します。</returns>
483
484         public static string IDNDecode(string input)
485         {
486             var IDNConverter = new IdnMapping();
487
488             if (!input.Contains("://")) return null;
489
490             // ドメイン名をPunycode展開
491             string Domain;
492             string AsciiDomain;
493
494             try
495             {
496                 Domain = input.Split('/')[2];
497                 AsciiDomain = IDNConverter.GetAscii(Domain);
498             }
499             catch (Exception)
500             {
501                 return null;
502             }
503
504             return input.Replace("://" + Domain, "://" + AsciiDomain);
505         }
506
507         public static void MoveArrayItem(int[] values, int idx_fr, int idx_to)
508         {
509             var moved_value = values[idx_fr];
510             var num_moved = Math.Abs(idx_fr - idx_to);
511
512             if (idx_to < idx_fr)
513             {
514                 Array.Copy(values, idx_to, values,
515                     idx_to + 1, num_moved);
516             }
517             else
518             {
519                 Array.Copy(values, idx_fr + 1, values,
520                     idx_fr, num_moved);
521             }
522
523             values[idx_to] = moved_value;
524         }
525
526         public static string EncryptString(string str)
527         {
528             if (string.IsNullOrEmpty(str)) return "";
529
530             //文字列をバイト型配列にする
531             var bytesIn = Encoding.UTF8.GetBytes(str);
532
533             //DESCryptoServiceProviderオブジェクトの作成
534             using (var des = new DESCryptoServiceProvider())
535             {
536                 //共有キーと初期化ベクタを決定
537                 //パスワードをバイト配列にする
538                 var bytesKey = Encoding.UTF8.GetBytes("_tween_encrypt_key_");
539                 //共有キーと初期化ベクタを設定
540                 des.Key = ResizeBytesArray(bytesKey, des.Key.Length);
541                 des.IV = ResizeBytesArray(bytesKey, des.IV.Length);
542
543                 MemoryStream msOut = null;
544                 ICryptoTransform desdecrypt = null;
545
546                 try
547                 {
548                     //暗号化されたデータを書き出すためのMemoryStream
549                     msOut = new MemoryStream();
550
551                     //DES暗号化オブジェクトの作成
552                     desdecrypt = des.CreateEncryptor();
553
554                     //書き込むためのCryptoStreamの作成
555                     using (CryptoStream cryptStream = new CryptoStream(msOut, desdecrypt, CryptoStreamMode.Write))
556                     {
557                         //Disposeが重複して呼ばれないようにする
558                         MemoryStream msTmp = msOut;
559                         msOut = null;
560                         desdecrypt = null;
561
562                         //書き込む
563                         cryptStream.Write(bytesIn, 0, bytesIn.Length);
564                         cryptStream.FlushFinalBlock();
565                         //暗号化されたデータを取得
566                         var bytesOut = msTmp.ToArray();
567
568                         //Base64で文字列に変更して結果を返す
569                         return Convert.ToBase64String(bytesOut);
570                     }
571                 }
572                 finally
573                 {
574                     if (msOut != null) msOut.Dispose();
575                     if (desdecrypt != null) desdecrypt.Dispose();
576                 }
577             }
578         }
579
580         public static string DecryptString(string str)
581         {
582             if (string.IsNullOrEmpty(str)) return "";
583
584             //DESCryptoServiceProviderオブジェクトの作成
585             using (var des = new System.Security.Cryptography.DESCryptoServiceProvider())
586             {
587                 //共有キーと初期化ベクタを決定
588                 //パスワードをバイト配列にする
589                 var bytesKey = Encoding.UTF8.GetBytes("_tween_encrypt_key_");
590                 //共有キーと初期化ベクタを設定
591                 des.Key = ResizeBytesArray(bytesKey, des.Key.Length);
592                 des.IV = ResizeBytesArray(bytesKey, des.IV.Length);
593
594                 //Base64で文字列をバイト配列に戻す
595                 var bytesIn = Convert.FromBase64String(str);
596
597                 MemoryStream msIn = null;
598                 ICryptoTransform desdecrypt = null;
599                 CryptoStream cryptStreem = null;
600
601                 try
602                 {
603                     //暗号化されたデータを読み込むためのMemoryStream
604                     msIn = new MemoryStream(bytesIn);
605                     //DES復号化オブジェクトの作成
606                     desdecrypt = des.CreateDecryptor();
607                     //読み込むためのCryptoStreamの作成
608                     cryptStreem = new CryptoStream(msIn, desdecrypt, CryptoStreamMode.Read);
609
610                     //Disposeが重複して呼ばれないようにする
611                     msIn = null;
612                     desdecrypt = null;
613
614                     //復号化されたデータを取得するためのStreamReader
615                     using (StreamReader srOut = new StreamReader(cryptStreem, Encoding.UTF8))
616                     {
617                         //Disposeが重複して呼ばれないようにする
618                         cryptStreem = null;
619
620                         //復号化されたデータを取得する
621                         var result = srOut.ReadToEnd();
622
623                         return result;
624                     }
625                 }
626                 finally
627                 {
628                     if (msIn != null) msIn.Dispose();
629                     if (desdecrypt != null) desdecrypt.Dispose();
630                     if (cryptStreem != null) cryptStreem.Dispose();
631                 }
632             }
633         }
634
635         public static byte[] ResizeBytesArray(byte[] bytes,
636                                     int newSize)
637         {
638             var newBytes = new byte[newSize];
639             if (bytes.Length <= newSize)
640             {
641                 foreach (var i in Enumerable.Range(0, bytes.Length))
642                 {
643                     newBytes[i] = bytes[i];
644                 }
645             }
646             else
647             {
648                 var pos = 0;
649                 foreach (var i in Enumerable.Range(0, bytes.Length))
650                 {
651                     newBytes[pos] = unchecked((byte)(newBytes[pos] ^ bytes[i]));
652                     pos++;
653                     if (pos >= newBytes.Length)
654                     {
655                         pos = 0;
656                     }
657                 }
658             }
659             return newBytes;
660         }
661
662         public static bool IsNT6()
663         {
664             //NT6 kernelかどうか検査
665             return Environment.OSVersion.Platform == PlatformID.Win32NT && Environment.OSVersion.Version.Major == 6;
666         }
667
668         [FlagsAttribute()]
669         public enum TabUsageType
670         {
671             Undefined = 0,
672             Home = 1,      //Unique
673             Mentions = 2,     //Unique
674             DirectMessage = 4,   //Unique
675             Favorites = 8,       //Unique
676             UserDefined = 16,
677             LocalQuery = 32,      //Pin(no save/no save query/distribute/no update(normal update))
678             Profile = 64,         //Pin(save/no distribute/manual update)
679             PublicSearch = 128,    //Pin(save/no distribute/auto update)
680             Lists = 256,
681             Related = 512,
682             UserTimeline = 1024,
683             //RTMyTweet
684             //RTByOthers
685             //RTByMe
686         }
687
688         public static string fileVersion = "";
689
690         public static string GetUserAgentString()
691         {
692             if (string.IsNullOrEmpty(fileVersion))
693             {
694                 throw new Exception("fileversion is not Initialized.");
695             }
696             return GetAssemblyName() + "/" + fileVersion;
697         }
698
699         public static TwitterApiStatus TwitterApiInfo = new TwitterApiStatus();
700
701         public static bool IsAnimatedGif(string filename)
702         {
703             Image img = null;
704             try
705             {
706                 img = Image.FromFile(filename);
707                 if (img == null) return false;
708                 if (img.RawFormat.Guid == ImageFormat.Gif.Guid)
709                 {
710                     var fd = new FrameDimension(img.FrameDimensionsList[0]);
711                     var fd_count = img.GetFrameCount(fd);
712                     if (fd_count > 1)
713                     {
714                         return true;
715                     }
716                     else
717                     {
718                         return false;
719                     }
720                 }
721                 return false;
722             }
723             catch (Exception)
724             {
725                 return false;
726             }
727             finally
728             {
729                 if (img != null) img.Dispose();
730             }
731         }
732
733         public static DateTime DateTimeParse(string input)
734         {
735             DateTime rslt;
736             string[] format = {
737                 "ddd MMM dd HH:mm:ss zzzz yyyy",
738                 "ddd, d MMM yyyy HH:mm:ss zzzz",
739             };
740             foreach (var fmt in format)
741             {
742                 if (DateTime.TryParseExact(input,
743                                           fmt,
744                                           DateTimeFormatInfo.InvariantInfo,
745                                           DateTimeStyles.None,
746                                           out rslt))
747                 {
748                     return rslt;
749                 }
750                 else
751                 {
752                     continue;
753                 }
754             }
755             TraceOut("Parse Error(DateTimeFormat) : " + input);
756             return new DateTime();
757         }
758
759         public static T CreateDataFromJson<T>(string content)
760         {
761             T data;
762             var buf = Encoding.Unicode.GetBytes(content);
763             using (var stream = new MemoryStream(buf))
764             {
765                 data = (T)((new DataContractJsonSerializer(typeof(T))).ReadObject(stream));
766             }
767             return data;
768         }
769
770         public static bool IsNetworkAvailable()
771         {
772             try
773             {
774                 return NetworkInterface.GetIsNetworkAvailable();
775             }
776             catch(Exception)
777             {
778                 return false;
779             }
780         }
781
782         public static bool IsValidEmail(string strIn)
783         {
784             // Return true if strIn is in valid e-mail format.
785             return Regex.IsMatch(strIn,
786                    @"^(?("")("".+?""@)|(([0-9a-zA-Z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-zA-Z])@))" +
787                    @"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,6}))$");
788         }
789
790         /// <summary>
791         /// 指定された修飾キーが押されている状態かを取得します。
792         /// </summary>
793         /// <param name="keys">状態を調べるキー</param>
794         /// <returns><paramref name="keys"/> で指定された修飾キーがすべて押されている状態であれば true。それ以外であれば false。</returns>
795         public static bool IsKeyDown(params Keys[] keys)
796         {
797             return MyCommon._IsKeyDown(Control.ModifierKeys, keys);
798         }
799
800         internal static bool _IsKeyDown(Keys modifierKeys, Keys[] targetKeys)
801         {
802             foreach (Keys key in targetKeys)
803             {
804                 if ((modifierKeys & key) != key)
805                 {
806                     return false;
807                 }
808             }
809             return true;
810         }
811
812         /// <summary>
813         /// アプリケーションのアセンブリ名を取得します。
814         /// </summary>
815         /// <remarks>
816         /// VB.NETの<code>My.Application.Info.AssemblyName</code>と(ほぼ)同じ動作をします。
817         /// </remarks>
818         /// <returns>アプリケーションのアセンブリ名</returns>
819         public static string GetAssemblyName()
820         {
821             return MyCommon.EntryAssembly.GetName().Name;
822         }
823
824         internal static _Assembly EntryAssembly = Assembly.GetEntryAssembly();
825
826         /// <summary>
827         /// 文字列中に含まれる %AppName% をアプリケーション名に置換する
828         /// </summary>
829         /// <param name="orig">対象となる文字列</param>
830         /// <returns>置換後の文字列</returns>
831         public static string ReplaceAppName(string orig)
832         {
833             return MyCommon.ReplaceAppName(orig, Application.ProductName);
834         }
835
836         /// <summary>
837         /// 文字列中に含まれる %AppName% をアプリケーション名に置換する
838         /// </summary>
839         /// <param name="orig">対象となる文字列</param>
840         /// <param name="appname">アプリケーション名</param>
841         /// <returns>置換後の文字列</returns>
842         public static string ReplaceAppName(string orig, string appname)
843         {
844             return orig.Replace("%AppName%", appname);
845         }
846
847         /// <summary>
848         /// 表示用のバージョン番号の文字列を生成する
849         /// </summary>
850         /// <remarks>
851         /// バージョン1.0.0.1のように末尾が0でない(=開発版)の場合は「1.0.1-beta1」が出力される
852         /// </remarks>
853         /// <returns>
854         /// 生成されたバージョン番号の文字列
855         /// </returns>
856         public static string GetReadableVersion(string fileVersion = null)
857         {
858             if (fileVersion == null)
859             {
860                 fileVersion = MyCommon.fileVersion;
861             }
862
863             if (string.IsNullOrEmpty(fileVersion))
864             {
865                 return null;
866             }
867
868             int[] version = fileVersion.Split('.')
869                 .Select(x => int.Parse(x)).ToArray();
870
871             if (version[3] == 0)
872             {
873                 return string.Format("{0}.{1}.{2}", version[0], version[1], version[2]);
874             }
875             else
876             {
877                 version[2] = version[2] + 1;
878
879                 // 10を越えたら桁上げ
880                 if (version[2] >= 10)
881                 {
882                     version[1] += version[2] / 10;
883                     version[2] %= 10;
884
885                     if (version[1] >= 10)
886                     {
887                         version[0] += version[1] / 10;
888                         version[1] %= 10;
889                     }
890                 }
891
892                 return string.Format("{0}.{1}.{2}-beta{3}", version[0], version[1], version[2], version[3]);
893             }
894         }
895
896         public const string TwitterUrl = "https://twitter.com/";
897
898         public static string GetStatusUrl(PostClass post)
899         {
900             if (post.RetweetedId == 0)
901                 return GetStatusUrl(post.ScreenName, post.StatusId);
902             else
903                 return GetStatusUrl(post.ScreenName, post.RetweetedId);
904         }
905
906         public static string GetStatusUrl(string screenName, long statusId)
907         {
908             return TwitterUrl + screenName + "/status/" + statusId.ToString();
909         }
910     }
911 }