PageRenderTime 50ms CodeModel.GetById 18ms RepoModel.GetById 1ms app.codeStats 0ms

/HelpersLib/Helpers/Helpers.cs

https://github.com/llehouerou/ShareX
C# | 769 lines | 627 code | 120 blank | 22 comment | 87 complexity | 630687ad2b75be3044def21071b61a38 MD5 | raw file
Possible License(s): GPL-3.0
  1. #region License Information (GPL v3)
  2. /*
  3. ShareX - A program that allows you to take screenshots and share any file type
  4. Copyright (C) 2007-2014 ShareX Developers
  5. This program is free software; you can redistribute it and/or
  6. modify it under the terms of the GNU General Public License
  7. as published by the Free Software Foundation; either version 2
  8. of the License, or (at your option) any later version.
  9. This program is distributed in the hope that it will be useful,
  10. but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. GNU General Public License for more details.
  13. You should have received a copy of the GNU General Public License
  14. along with this program; if not, write to the Free Software
  15. Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  16. Optionally you can also view the license at <http://www.gnu.org/licenses/>.
  17. */
  18. #endregion License Information (GPL v3)
  19. using Microsoft.Win32;
  20. using System;
  21. using System.Diagnostics;
  22. using System.Drawing;
  23. using System.Globalization;
  24. using System.IO;
  25. using System.Linq;
  26. using System.Media;
  27. using System.Net.NetworkInformation;
  28. using System.Runtime.Serialization;
  29. using System.Runtime.Serialization.Formatters.Binary;
  30. using System.Text;
  31. using System.Text.RegularExpressions;
  32. using System.Threading;
  33. using System.Web;
  34. using System.Windows.Forms;
  35. namespace HelpersLib
  36. {
  37. public static class Helpers
  38. {
  39. public const string Numbers = "0123456789"; // 48 ... 57
  40. public const string AlphabetCapital = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; // 65 ... 90
  41. public const string Alphabet = "abcdefghijklmnopqrstuvwxyz"; // 97 ... 122
  42. public const string Alphanumeric = Numbers + AlphabetCapital + Alphabet;
  43. public const string URLCharacters = Alphanumeric + "-._~"; // 45 46 95 126
  44. public const string URLPathCharacters = URLCharacters + "/"; // 47
  45. public const string ValidURLCharacters = URLPathCharacters + ":?#[]@!$&'()*+,;= ";
  46. private static readonly object randomLock = new object();
  47. private static readonly Random random = new Random();
  48. public static readonly Version OSVersion = Environment.OSVersion.Version;
  49. public static int Random(int max)
  50. {
  51. lock (randomLock)
  52. {
  53. return random.Next(max + 1);
  54. }
  55. }
  56. public static int Random(int min, int max)
  57. {
  58. lock (randomLock)
  59. {
  60. return random.Next(min, max + 1);
  61. }
  62. }
  63. public static string GetFilenameExtension(string filePath)
  64. {
  65. if (!string.IsNullOrEmpty(filePath) && filePath.Contains('.'))
  66. {
  67. int pos = filePath.LastIndexOf('.');
  68. if (pos <= filePath.Length)
  69. {
  70. return filePath.Substring(pos + 1);
  71. }
  72. }
  73. return string.Empty;
  74. }
  75. private static bool IsValidFile(string filePath, Type enumType)
  76. {
  77. string ext = GetFilenameExtension(filePath);
  78. if (!string.IsNullOrEmpty(ext))
  79. {
  80. return Enum.GetNames(enumType).Any(x => ext.Equals(x, StringComparison.InvariantCultureIgnoreCase));
  81. }
  82. return false;
  83. }
  84. public static bool IsImageFile(string filePath)
  85. {
  86. return IsValidFile(filePath, typeof(ImageFileExtensions));
  87. }
  88. public static bool IsTextFile(string filePath)
  89. {
  90. return IsValidFile(filePath, typeof(TextFileExtensions));
  91. }
  92. public static EDataType FindDataType(string filePath)
  93. {
  94. if (IsImageFile(filePath))
  95. {
  96. return EDataType.Image;
  97. }
  98. if (IsTextFile(filePath))
  99. {
  100. return EDataType.Text;
  101. }
  102. return EDataType.File;
  103. }
  104. public static string AddZeroes(int number, int digits = 2)
  105. {
  106. return number.ToString().PadLeft(digits, '0');
  107. }
  108. public static string HourTo12(int hour)
  109. {
  110. if (hour == 0)
  111. {
  112. return 12.ToString();
  113. }
  114. if (hour > 12)
  115. {
  116. return AddZeroes(hour - 12);
  117. }
  118. return AddZeroes(hour);
  119. }
  120. public static char GetRandomChar(string chars)
  121. {
  122. return chars[Random(chars.Length - 1)];
  123. }
  124. public static string GetRandomString(string chars, int length)
  125. {
  126. StringBuilder sb = new StringBuilder();
  127. while (length-- > 0)
  128. {
  129. sb.Append(GetRandomChar(chars));
  130. }
  131. return sb.ToString();
  132. }
  133. public static string GetRandomNumber(int length)
  134. {
  135. return GetRandomString(Numbers, length);
  136. }
  137. public static string GetRandomAlphanumeric(int length)
  138. {
  139. return GetRandomString(Alphanumeric, length);
  140. }
  141. public static string GetRandomKey(int length = 5, int count = 3, char separator = '-')
  142. {
  143. return Enumerable.Range(1, (length + 1) * count - 1).Aggregate("", (x, index) => x += index % (length + 1) == 0 ? separator : GetRandomChar(Alphanumeric));
  144. }
  145. public static string GetAllCharacters()
  146. {
  147. return Encoding.UTF8.GetString(Enumerable.Range(1, 255).Select(i => (byte)i).ToArray());
  148. }
  149. public static string GetValidFileName(string fileName)
  150. {
  151. char[] invalidFileNameChars = Path.GetInvalidFileNameChars();
  152. return new string(fileName.Where(c => !invalidFileNameChars.Contains(c)).ToArray());
  153. }
  154. public static string GetValidFolderPath(string folderPath)
  155. {
  156. char[] invalidPathChars = Path.GetInvalidPathChars();
  157. return new string(folderPath.Where(c => !invalidPathChars.Contains(c)).ToArray());
  158. }
  159. public static string GetValidFilePath(string filePath)
  160. {
  161. string folderPath = Path.GetDirectoryName(filePath);
  162. string fileName = Path.GetFileName(filePath);
  163. return GetValidFolderPath(folderPath) + Path.DirectorySeparatorChar + GetValidFileName(fileName);
  164. }
  165. public static string GetValidURL(string url, bool replaceSpace = false)
  166. {
  167. if (replaceSpace) url = url.Replace(' ', '_');
  168. return new string(url.Where(c => ValidURLCharacters.Contains(c)).ToArray());
  169. }
  170. public static string GetXMLValue(string input, string tag)
  171. {
  172. return Regex.Match(input, String.Format("(?<={0}>).+?(?=</{0})", tag)).Value;
  173. }
  174. public static string GetMimeType(string fileName)
  175. {
  176. if (!string.IsNullOrEmpty(fileName))
  177. {
  178. string ext = Path.GetExtension(fileName).ToLower();
  179. if (!string.IsNullOrEmpty(ext))
  180. {
  181. string mimeType = MimeTypes.GetMimeType(ext);
  182. if (!string.IsNullOrEmpty(mimeType))
  183. {
  184. return mimeType;
  185. }
  186. using (RegistryKey regKey = Registry.ClassesRoot.OpenSubKey(ext))
  187. {
  188. if (regKey != null && regKey.GetValue("Content Type") != null)
  189. {
  190. mimeType = regKey.GetValue("Content Type").ToString();
  191. if (!string.IsNullOrEmpty(mimeType))
  192. {
  193. return mimeType;
  194. }
  195. }
  196. }
  197. }
  198. }
  199. return MimeTypes.DefaultMimeType;
  200. }
  201. public static string[] GetEnumDescriptions<T>()
  202. {
  203. return Enum.GetValues(typeof(T)).OfType<Enum>().Select(x => x.GetDescription()).ToArray();
  204. }
  205. public static int GetEnumLength<T>()
  206. {
  207. return Enum.GetValues(typeof(T)).Length;
  208. }
  209. public static T GetEnumFromIndex<T>(int i)
  210. {
  211. Array values = Enum.GetValues(typeof(T));
  212. return (T)values.GetValue(i);
  213. }
  214. public static string[] GetEnumNamesProper<T>()
  215. {
  216. string[] names = Enum.GetNames(typeof(T));
  217. string[] newNames = new string[names.Length];
  218. for (int i = 0; i < names.Length; i++)
  219. {
  220. newNames[i] = GetProperName(names[i]);
  221. }
  222. return newNames;
  223. }
  224. // Example: "TopLeft" becomes "Top left"
  225. public static string GetProperName(string name)
  226. {
  227. StringBuilder sb = new StringBuilder();
  228. for (int i = 0; i < name.Length; i++)
  229. {
  230. char c = name[i];
  231. if (i > 0 && char.IsUpper(c))
  232. {
  233. sb.Append(' ');
  234. sb.Append(char.ToLowerInvariant(c));
  235. }
  236. else
  237. {
  238. sb.Append(c);
  239. }
  240. }
  241. return sb.ToString();
  242. }
  243. public static string GetProperExtension(string filePath)
  244. {
  245. if (!string.IsNullOrEmpty(filePath))
  246. {
  247. int dot = filePath.LastIndexOf('.');
  248. if (dot >= 0)
  249. {
  250. string ext = filePath.Substring(dot + 1);
  251. return ext.ToLowerInvariant();
  252. }
  253. }
  254. return null;
  255. }
  256. public static void OpenFolder(string folderPath)
  257. {
  258. if (!string.IsNullOrEmpty(folderPath))
  259. {
  260. if (Directory.Exists(folderPath))
  261. {
  262. Process.Start("explorer.exe", folderPath);
  263. }
  264. else
  265. {
  266. MessageBox.Show("Folder not exist:\r\n" + folderPath, "ShareX", MessageBoxButtons.OK, MessageBoxIcon.Information);
  267. }
  268. }
  269. }
  270. public static void OpenFolderWithFile(string filePath)
  271. {
  272. if (!string.IsNullOrEmpty(filePath) && File.Exists(filePath))
  273. {
  274. Process.Start("explorer.exe", string.Format("/select,\"{0}\"", filePath));
  275. }
  276. }
  277. public static bool CheckVersion(Version currentVersion, Version latestVersion)
  278. {
  279. return NormalizeVersion(latestVersion).CompareTo(NormalizeVersion(currentVersion)) > 0;
  280. }
  281. private static Version NormalizeVersion(Version version)
  282. {
  283. return new Version(Math.Max(version.Major, 0), Math.Max(version.Minor, 0), Math.Max(version.Build, 0), Math.Max(version.Revision, 0));
  284. }
  285. public static bool IsWindowsXP()
  286. {
  287. return OSVersion.Major == 5 && OSVersion.Minor == 1;
  288. }
  289. public static bool IsWindowsXPOrGreater()
  290. {
  291. return (OSVersion.Major == 5 && OSVersion.Minor >= 1) || OSVersion.Major > 5;
  292. }
  293. public static bool IsWindowsVista()
  294. {
  295. return OSVersion.Major == 6;
  296. }
  297. public static bool IsWindowsVistaOrGreater()
  298. {
  299. return OSVersion.Major >= 6;
  300. }
  301. public static bool IsWindows7()
  302. {
  303. return OSVersion.Major == 6 && OSVersion.Minor == 1;
  304. }
  305. public static bool IsWindows7OrGreater()
  306. {
  307. return (OSVersion.Major == 6 && OSVersion.Minor >= 1) || OSVersion.Major > 6;
  308. }
  309. public static bool IsWindows8()
  310. {
  311. return OSVersion.Major == 6 && OSVersion.Minor == 2;
  312. }
  313. public static bool IsWindows8OrGreater()
  314. {
  315. return (OSVersion.Major == 6 && OSVersion.Minor >= 2) || OSVersion.Major > 6;
  316. }
  317. public static bool IsDefaultInstallDir()
  318. {
  319. string path = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles);
  320. return Application.ExecutablePath.StartsWith(path);
  321. }
  322. public static void OpenURL(string url)
  323. {
  324. if (!string.IsNullOrEmpty(url))
  325. {
  326. TaskEx.Run(() =>
  327. {
  328. try
  329. {
  330. Process.Start(url);
  331. }
  332. catch (Exception e)
  333. {
  334. DebugHelper.WriteException(e, string.Format("OpenURL({0}) failed", url));
  335. }
  336. });
  337. }
  338. }
  339. public static void OpenFile(string filepath)
  340. {
  341. if (!string.IsNullOrEmpty(filepath) && File.Exists(filepath))
  342. {
  343. TaskEx.Run(() =>
  344. {
  345. try
  346. {
  347. Process.Start(filepath);
  348. }
  349. catch (Exception e)
  350. {
  351. DebugHelper.WriteException(e, string.Format("OpenFile({0}) failed", filepath));
  352. }
  353. });
  354. }
  355. }
  356. public static bool IsValidIPAddress(string ip)
  357. {
  358. if (string.IsNullOrEmpty(ip)) return false;
  359. string pattern = @"(?<First>2[0-4]\d|25[0-5]|[01]?\d\d?)\.(?<Second>2[0-4]\d|25[0-5]|[01]?\d\d?)\.(?<Third>2[0-4]\d|25[0-5]|[01]?\d\d?)\.(?<Fourth>2[0-4]\d|25[0-5]|[01]?\d\d?)";
  360. return Regex.IsMatch(ip.Trim(), pattern);
  361. }
  362. public static string GetUniqueFilePath(string filepath)
  363. {
  364. if (File.Exists(filepath))
  365. {
  366. string folder = Path.GetDirectoryName(filepath);
  367. string filename = Path.GetFileNameWithoutExtension(filepath);
  368. string extension = Path.GetExtension(filepath);
  369. int number = 1;
  370. Match regex = Regex.Match(filepath, @"(.+) \((\d+)\)\.\w+");
  371. if (regex.Success)
  372. {
  373. filename = regex.Groups[1].Value;
  374. number = int.Parse(regex.Groups[2].Value);
  375. }
  376. do
  377. {
  378. number++;
  379. filepath = Path.Combine(folder, string.Format("{0} ({1}){2}", filename, number, extension));
  380. }
  381. while (File.Exists(filepath));
  382. }
  383. return filepath;
  384. }
  385. public static string ProperTimeSpan(TimeSpan ts)
  386. {
  387. string time = string.Format("{0:00}:{1:00}", ts.Minutes, ts.Seconds);
  388. int hours = (int)ts.TotalHours;
  389. if (hours > 0) time = hours + ":" + time;
  390. return time;
  391. }
  392. public static object Clone(object obj)
  393. {
  394. using (MemoryStream ms = new MemoryStream())
  395. {
  396. BinaryFormatter binaryFormatter = new BinaryFormatter(null, new StreamingContext(StreamingContextStates.Clone));
  397. binaryFormatter.Serialize(ms, obj);
  398. ms.Seek(0, SeekOrigin.Begin);
  399. return binaryFormatter.Deserialize(ms);
  400. }
  401. }
  402. public static void PlaySoundAsync(Stream stream)
  403. {
  404. TaskEx.Run(() =>
  405. {
  406. using (stream)
  407. using (SoundPlayer soundPlayer = new SoundPlayer(stream))
  408. {
  409. soundPlayer.PlaySync();
  410. }
  411. });
  412. }
  413. public static bool BrowseFile(string title, TextBox tb, string initialDirectory = "")
  414. {
  415. using (OpenFileDialog ofd = new OpenFileDialog())
  416. {
  417. ofd.Title = title;
  418. try
  419. {
  420. string path = tb.Text;
  421. if (!string.IsNullOrEmpty(path))
  422. {
  423. path = Path.GetDirectoryName(path);
  424. if (Directory.Exists(path))
  425. {
  426. ofd.InitialDirectory = path;
  427. }
  428. }
  429. }
  430. finally
  431. {
  432. if (string.IsNullOrEmpty(ofd.InitialDirectory) && !string.IsNullOrEmpty(initialDirectory))
  433. {
  434. ofd.InitialDirectory = initialDirectory;
  435. }
  436. }
  437. if (ofd.ShowDialog() == DialogResult.OK)
  438. {
  439. tb.Text = ofd.FileName;
  440. return true;
  441. }
  442. }
  443. return false;
  444. }
  445. public static bool BrowseFolder(string title, TextBox tb, string initialDirectory = "")
  446. {
  447. using (FolderSelectDialog fsd = new FolderSelectDialog())
  448. {
  449. fsd.Title = title;
  450. string path = tb.Text;
  451. if (!string.IsNullOrEmpty(path) && Directory.Exists(path))
  452. {
  453. fsd.InitialDirectory = path;
  454. }
  455. else if (!string.IsNullOrEmpty(initialDirectory))
  456. {
  457. fsd.InitialDirectory = initialDirectory;
  458. }
  459. if (fsd.ShowDialog())
  460. {
  461. tb.Text = fsd.FileName;
  462. return true;
  463. }
  464. }
  465. return false;
  466. }
  467. public static bool WaitWhile(Func<bool> check, int interval, int timeout = -1)
  468. {
  469. Stopwatch timer = Stopwatch.StartNew();
  470. while (check())
  471. {
  472. if (timeout >= 0 && timer.ElapsedMilliseconds >= timeout)
  473. {
  474. return false;
  475. }
  476. Thread.Sleep(interval);
  477. }
  478. return true;
  479. }
  480. public static void WaitWhileAsync(Func<bool> check, int interval, int timeout, Action onSuccess, int waitStart = 0)
  481. {
  482. bool result = false;
  483. TaskEx.Run(() =>
  484. {
  485. if (waitStart > 0)
  486. {
  487. Thread.Sleep(waitStart);
  488. }
  489. result = WaitWhile(check, interval, timeout);
  490. },
  491. () =>
  492. {
  493. if (result) onSuccess();
  494. }, false);
  495. }
  496. public static bool IsFileLocked(string path)
  497. {
  498. try
  499. {
  500. using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite))
  501. {
  502. }
  503. }
  504. catch (IOException)
  505. {
  506. return true;
  507. }
  508. return false;
  509. }
  510. public static void CreateDirectoryIfNotExist(string filePath)
  511. {
  512. if (!string.IsNullOrEmpty(filePath))
  513. {
  514. string directoryName = Path.GetDirectoryName(filePath);
  515. if (!string.IsNullOrEmpty(directoryName) && !Directory.Exists(directoryName))
  516. {
  517. Directory.CreateDirectory(directoryName);
  518. }
  519. }
  520. }
  521. public static void BackupFileMonthly(string filepath, string destinationFolder)
  522. {
  523. if (!string.IsNullOrEmpty(filepath) && File.Exists(filepath))
  524. {
  525. string filename = Path.GetFileNameWithoutExtension(filepath);
  526. string extension = Path.GetExtension(filepath);
  527. string newFilename = string.Format("{0}-{1:yyyy-MM}{2}", filename, DateTime.Now, extension);
  528. string newFilepath = Path.Combine(destinationFolder, newFilename);
  529. if (!File.Exists(newFilepath))
  530. {
  531. CreateDirectoryIfNotExist(newFilepath);
  532. File.Copy(filepath, newFilepath, false);
  533. }
  534. }
  535. }
  536. public static void BackupFileWeekly(string filepath, string destinationFolder)
  537. {
  538. if (!string.IsNullOrEmpty(filepath) && File.Exists(filepath))
  539. {
  540. string filename = Path.GetFileNameWithoutExtension(filepath);
  541. DateTime dateTime = DateTime.Now;
  542. string extension = Path.GetExtension(filepath);
  543. string newFilename = string.Format("{0}-{1:yyyy-MM}-W{2:00}{3}", filename, dateTime, dateTime.WeekOfYear(), extension);
  544. string newFilepath = Path.Combine(destinationFolder, newFilename);
  545. if (!File.Exists(newFilepath))
  546. {
  547. CreateDirectoryIfNotExist(newFilepath);
  548. File.Copy(filepath, newFilepath, false);
  549. }
  550. }
  551. }
  552. public static string GetUniqueID()
  553. {
  554. return Guid.NewGuid().ToString("N");
  555. }
  556. public static string HtmlEncode(string text)
  557. {
  558. char[] chars = HttpUtility.HtmlEncode(text).ToCharArray();
  559. StringBuilder result = new StringBuilder(chars.Length + (int)(chars.Length * 0.1));
  560. foreach (char c in chars)
  561. {
  562. int value = Convert.ToInt32(c);
  563. if (value > 127)
  564. {
  565. result.AppendFormat("&#{0};", value);
  566. }
  567. else
  568. {
  569. result.Append(c);
  570. }
  571. }
  572. return result.ToString();
  573. }
  574. public static Point GetPosition(ContentAlignment placement, Point offset, Size backgroundSize, Size objectSize)
  575. {
  576. int midX = backgroundSize.Width / 2 - objectSize.Width / 2;
  577. int midY = backgroundSize.Height / 2 - objectSize.Height / 2;
  578. int right = backgroundSize.Width - objectSize.Width;
  579. int bottom = backgroundSize.Height - objectSize.Height;
  580. switch (placement)
  581. {
  582. default:
  583. case ContentAlignment.TopLeft:
  584. return new Point(offset.X, offset.Y);
  585. case ContentAlignment.TopCenter:
  586. return new Point(midX, offset.Y);
  587. case ContentAlignment.TopRight:
  588. return new Point(right - offset.X, offset.Y);
  589. case ContentAlignment.MiddleLeft:
  590. return new Point(offset.X, midY);
  591. case ContentAlignment.MiddleCenter:
  592. return new Point(midX, midY);
  593. case ContentAlignment.MiddleRight:
  594. return new Point(right - offset.X, midY);
  595. case ContentAlignment.BottomLeft:
  596. return new Point(offset.X, bottom - offset.Y);
  597. case ContentAlignment.BottomCenter:
  598. return new Point(midX, bottom - offset.Y);
  599. case ContentAlignment.BottomRight:
  600. return new Point(right - offset.X, bottom - offset.Y);
  601. }
  602. }
  603. public static Size MeasureText(string text, Font font)
  604. {
  605. using (Graphics g = Graphics.FromHwnd(IntPtr.Zero))
  606. {
  607. return g.MeasureString(text, font).ToSize();
  608. }
  609. }
  610. public static Size MeasureText(string text, Font font, int width)
  611. {
  612. using (Graphics g = Graphics.FromHwnd(IntPtr.Zero))
  613. {
  614. return g.MeasureString(text, font, width).ToSize();
  615. }
  616. }
  617. public static string SendPing(string host)
  618. {
  619. return SendPing(host, 1);
  620. }
  621. public static string SendPing(string host, int count)
  622. {
  623. string[] status = new string[count];
  624. using (Ping ping = new Ping())
  625. {
  626. PingReply reply;
  627. //byte[] buffer = Encoding.ASCII.GetBytes(new string('a', 32));
  628. for (int i = 0; i < count; i++)
  629. {
  630. reply = ping.Send(host, 3000);
  631. if (reply.Status == IPStatus.Success)
  632. {
  633. status[i] = reply.RoundtripTime.ToString() + " ms";
  634. }
  635. else
  636. {
  637. status[i] = "Timeout";
  638. }
  639. Thread.Sleep(100);
  640. }
  641. }
  642. return string.Join(", ", status);
  643. }
  644. }
  645. }