HamBook – Blame information for rev 54

Subversion Repositories:
Rev:
Rev Author Line No. Line
1 office 1 using System;
13 office 2 using System.ComponentModel;
1 office 3 using System.Diagnostics;
4 using System.Drawing;
5 using System.IO;
13 office 6 using System.Linq;
1 office 7 using System.Reflection;
8 using System.Threading;
9 using System.Threading.Tasks;
10 using System.Windows.Forms;
11 using Microsoft.Win32;
12  
54 office 13 namespace HamBook.Utilities
14 {
1 office 15 public static class Miscellaneous
16 {
17 #region Public Methods
18  
19 public static bool LaunchOnBootSet(bool enable)
20 {
21 using (var key = Registry.CurrentUser.OpenSubKey
22 ("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true))
23 {
54 office 24 if (key == null) return false;
1 office 25  
26 switch (enable)
27 {
28 case true:
29 key.SetValue(Constants.AssemblyName, Assembly.GetEntryAssembly().Location);
30 break;
31 default:
32 key.DeleteValue(Constants.AssemblyName, false);
33 break;
34 }
35  
36 return true;
37 }
38 }
39  
40 public static bool LaunchOnBootGet()
41 {
42 using (var key = Registry.CurrentUser.OpenSubKey
43 ("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true))
44 {
45 return key?.GetValue(Constants.AssemblyName) != null;
46 }
47 }
48  
49 /// <summary>
50 /// Enable double buffering for an arbitrary control.
51 /// </summary>
52 /// <param name="control">the control to enable double buffering for</param>
53 /// <returns>true on success</returns>
54 /// <remarks>Do not enable double buffering on RDP: https://devblogs.microsoft.com/oldnewthing/20060103-12/?p=32793</remarks>
55 public static void SetDoubleBuffered(this Control control)
56 {
57 // Double buffering can make DGV slow in remote desktop
58 if (!SystemInformation.TerminalServerSession)
59 {
60 var dgvType = control.GetType();
61 var pi = dgvType.GetProperty("DoubleBuffered",
62 BindingFlags.Instance | BindingFlags.NonPublic);
63 pi.SetValue(control, true, null);
64 }
65 }
66  
67 public static async Task<Icon> CreateIconFromResource(string resource)
68 {
69 var iconBytes = await LoadResource(resource);
70 using (var iconMemoryStream = new MemoryStream(iconBytes))
71 {
72 var bitmap = (Bitmap)Image.FromStream(iconMemoryStream);
73 var bitmapIntPtr = bitmap.GetHicon();
74 var icon = Icon.FromHandle(bitmapIntPtr);
75 return icon;
76 }
77 }
78  
79 public static async Task<byte[]> LoadResource(string resource)
80 {
81 var assembly = Assembly.GetExecutingAssembly();
82  
83 using (var manifestResourceStream = assembly.GetManifestResourceStream(resource))
84 {
54 office 85 if (manifestResourceStream == null) return null;
1 office 86  
87 var memoryStream = new MemoryStream();
88  
89 await manifestResourceStream.CopyToAsync(memoryStream);
90  
91 memoryStream.Position = 0L;
92  
93 return memoryStream.ToArray();
94 }
95 }
96  
97 public static void InvokeIfRequired<T>(this T control, Action<T> action) where T : Control
98 {
99 if (control.InvokeRequired)
100 {
101 control.BeginInvoke((MethodInvoker)delegate { action(control); });
102 return;
103 }
104  
105 action(control);
106 }
107  
108 /// <summary>
109 /// Attempts to access a file within <see cref="timeout" /> milliseconds by retrying to access the file every
110 /// <see cref="retry" /> milliseconds.
111 /// </summary>
112 /// <param name="path">the path to the file</param>
113 /// <param name="mode">the file mode used to access the file</param>
114 /// <param name="access">the file access to use</param>
115 /// <param name="share">the file share to use</param>
116 /// <param name="cancellationToken">a cancellation token</param>
117 /// <param name="retry">the amount of milliseconds to retry between accesses to the file</param>
118 /// <param name="timeout">the amount of time in milliseconds to attempt and access the file</param>
119 /// <returns>a file stream if the file could be accessed within the allotted time</returns>
120 public static async Task<FileStream> GetFileStream(string path, FileMode mode, FileAccess access,
54 office 121 FileShare share, CancellationToken cancellationToken,
122 int retry = 1000, int timeout = 60000)
1 office 123 {
124 var time = Stopwatch.StartNew();
125  
126 while (time.ElapsedMilliseconds < timeout && !cancellationToken.IsCancellationRequested)
127 {
128 try
129 {
130 return new FileStream(path, mode, access, share);
131 }
132 catch (IOException e)
133 {
134 // access error
54 office 135 if (e.HResult != -2147024864) throw;
1 office 136 }
137  
138 await Task.Delay(retry, cancellationToken);
139 }
140  
141 throw new TimeoutException($"Failed to get a access to {path} within {timeout}ms.");
142 }
143  
13 office 144 ///////////////////////////////////////////////////////////////////////////
145 // Copyright (C) 2015 Wizardry and Steamworks - License: GNU GPLv3 //
146 ///////////////////////////////////////////////////////////////////////////
147 /// <summary>
148 /// Get the description from an enumeration value.
149 /// </summary>
150 /// <param name="value">an enumeration value</param>
151 /// <returns>the description or the empty string</returns>
152 public static string GetDescriptionFromEnumValue(Enum value)
153 {
154 var attribute = value.GetType()
54 office 155 .GetRuntimeField(value.ToString())
156 .GetCustomAttributes(typeof(DescriptionAttribute), false)
157 .SingleOrDefault() as DescriptionAttribute;
13 office 158  
159 return attribute?.Description;
160 }
161  
162 ///////////////////////////////////////////////////////////////////////////
163 // Copyright (C) 2015 Wizardry and Steamworks - License: GNU GPLv3 //
164 ///////////////////////////////////////////////////////////////////////////
165 /// <summary>
166 /// Get enumeration value from its name attribute.
167 /// </summary>
168 /// <typeparam name="T">the enumeration type</typeparam>
169 /// <param name="description">the description of a member</param>
170 /// <param name="comparison">the string comparison to use</param>
171 /// <returns>the value or the default of T if case no name attribute found</returns>
172 public static T GetEnumValueFromDescription<T>(string description,
54 office 173 StringComparison comparison = StringComparison.OrdinalIgnoreCase)
13 office 174 {
175 var field = typeof(T).GetRuntimeFields()
54 office 176 .SelectMany(f => f.GetCustomAttributes(
177 typeof(DescriptionAttribute),
178 false),
179 (
180 f,
181 a) => new { Field = f, Att = a })
182 .SingleOrDefault(a => string.Equals(((DescriptionAttribute)a.Att)
183 .Description,
184 description,
185 comparison));
13 office 186  
187 return (T)field?.Field.GetValue(Activator.CreateInstance<T>());
188 }
189  
1 office 190 #endregion
191 }
192 }