Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Newer
Older
100644 295 lines (263 sloc) 12.687 kb
0092c332 »
2011-09-21 Update.
1 using System;
2 using System.Collections.Generic;
3 using System.Diagnostics.Contracts;
4 using System.Globalization;
5 using System.IO;
6 using System.Linq;
7 using System.Security.Cryptography;
8 using System.Text;
9 using System.Threading;
10 using System.Windows.Threading;
11
12 namespace SharpBag
13 {
14 /// <summary>
15 /// A static class containing generic extension methods.
16 /// </summary>
17 public static class GenericExtensions
18 {
19 /// <summary>
20 /// Invokes the specified action if the current object is not null.
21 /// </summary>
22 /// <typeparam name="T">The type of the object.</typeparam>
23 /// <param name="obj">The object.</param>
24 /// <param name="action">The action.</param>
25 public static void IfNotNull<T>(this T obj, Action<T> action) where T : class
26 {
27 Contract.Requires(action != null);
28
29 if (obj != null) action(obj);
30 }
31
32 /// <summary>
33 /// Invokes the specified action if the current object is not null.
34 /// </summary>
35 /// <typeparam name="T">The type of the object.</typeparam>
36 /// <param name="obj">The object.</param>
37 /// <param name="action">The action.</param>
38 public static void IfNotNull<T>(this T obj, Action action) where T : class
39 {
40 Contract.Requires(action != null);
41
42 if (obj != null) action();
43 }
44
45 #region InvokeIfRequired overloads
46
47 /// <summary>
48 /// Simple helper extension method to marshall to correct thread if its required.
49 /// </summary>
50 /// <param name="control">The source control.</param>
51 /// <param name="methodcall">The method to call.</param>
52 public static void InvokeIfRequired(this DispatcherObject control, Action methodcall)
53 {
54 Contract.Requires(control != null);
55 Contract.Requires(methodcall != null);
56
57 control.InvokeIfRequired(methodcall, DispatcherPriority.Normal);
58 }
59
60 /// <summary>
61 /// Simple helper extension method to marshall to correct thread if its required.
62 /// </summary>
63 /// <param name="control">The source control.</param>
64 /// <param name="methodcall">The method to call.</param>
65 /// <param name="priorityForCall">The thread priority.</param>
66 public static void InvokeIfRequired(this DispatcherObject control, Action methodcall, DispatcherPriority priorityForCall)
67 {
68 Contract.Requires(control != null);
69 Contract.Requires(methodcall != null);
70
71 if (control.Dispatcher.Thread != Thread.CurrentThread) control.Dispatcher.Invoke(priorityForCall, methodcall);
72 else methodcall();
73 }
74
75 #endregion InvokeIfRequired overloads
76
77 /// <summary>
78 /// Whether the current instance is null or empty.
79 /// </summary>
80 /// <typeparam name="T">The type of items in the current instance.</typeparam>
81 /// <param name="collection">The current instance.</param>
82 /// <returns>Whether the current instance is null or empty.</returns>
83 public static bool IsNullOrEmpty<T>(this IEnumerable<T> collection)
84 {
85 return collection == null || !collection.Any();
86 }
87
88 /// <summary>
89 /// Converts the current instance to the specified type.
90 /// </summary>
91 /// <typeparam name="TOut">Type the current instance will be converted to.</typeparam>
92 /// <param name="original">The current instance.</param>
93 /// <param name="defaultValue">The default value to use in case the current instance can't be converted.</param>
94 /// <returns>The converted value.</returns>
95 public static TOut As<TOut>(this object original, TOut defaultValue = default(TOut))
96 {
97 return original.As(CultureInfo.CurrentCulture, defaultValue);
98 }
99
100 /// <summary>
101 /// Converts the current instance to the specified type.
102 /// </summary>
103 /// <typeparam name="TOut">Type the current instance will be converted to.</typeparam>
104 /// <param name="original">The current instance.</param>
105 /// <param name="provider">An IFormatProvider.</param>
106 /// <param name="defaultValue">The default value to use in case the current instance can't be converted.</param>
107 /// <returns>The converted value.</returns>
108 public static TOut As<TOut>(this object original, IFormatProvider provider, TOut defaultValue = default(TOut))
109 {
110 Contract.Requires(provider != null);
111
112 Type type = typeof(TOut);
113 if (type.IsNullableType()) type = Nullable.GetUnderlyingType(type);
114
115 try
116 {
117 return type.IsEnum && (original is string) ? (TOut)Enum.Parse(type, original as string, true) : (TOut)Convert.ChangeType(original, type, provider);
118 }
119 catch { return defaultValue; }
120 }
121
122 /// <summary>
123 /// Returns whether or not the specified type is Nullable{T}
124 /// </summary>
125 /// <param name="type">A Type.</param>
126 /// <returns>True if the specified type is Nullable{T}; otherwise, false.</returns>
127 /// <remarks>Use <see cref="Nullable.GetUnderlyingType"/> to access the underlying type.</remarks>
128 public static bool IsNullableType(this Type type)
129 {
130 Contract.Requires(type != null);
131
132 return type.IsGenericType && type.GetGenericTypeDefinition().Equals(typeof(Nullable<>));
133 }
134
135 /// <summary>
136 /// Writes the current instance to the console.
137 /// </summary>
138 /// <param name="o">The specified object.</param>
139 /// <returns>A console helper.</returns>
140 public static ConsoleHelper Write<T>(this T o)
141 {
142 return ConsoleHelper.GetInstance().Write<T>(o);
143 }
144
145 /// <summary>
146 /// Writes the current instance to the console.
147 /// </summary>
148 /// <param name="o">The specified object.</param>
149 /// <param name="format">The format string.</param>
150 /// <param name="objects">The objects.</param>
151 /// <returns>A console helper.</returns>
152 public static ConsoleHelper Write<T>(this T o, string format, params object[] objects)
153 {
154 return ConsoleHelper.GetInstance().Write(format, new object[] { o }.Concat(objects).ToArray());
155 }
156
157 /// <summary>
158 /// Writes the current instance to the console, and then puts the cursor on a new line.
159 /// </summary>
160 /// <param name="o">The specified object.</param>
161 /// <returns>A console helper.</returns>
162 public static ConsoleHelper WriteLine<T>(this T o)
163 {
164 return ConsoleHelper.GetInstance().WriteLine<T>(o);
165 }
166
167 /// <summary>
168 /// Writes the current instance to the console, and then puts the cursor on a new line.
169 /// </summary>
170 /// <param name="o">The specified object.</param>
171 /// <param name="format">The format string.</param>
172 /// <param name="objects">The objects.</param>
173 /// <returns>A console helper.</returns>
174 public static ConsoleHelper WriteLine<T>(this T o, string format, params object[] objects)
175 {
176 return ConsoleHelper.GetInstance().WriteLine(format, new object[] { o }.Concat(objects).ToArray());
177 }
178
179 /// <summary>
180 /// Gets the current instance's hash.
181 /// </summary>
182 /// <param name="s">The current instance.</param>
183 /// <param name="hasher">The hash function.</param>
184 /// <returns>The hash.</returns>
185 public static byte[] GetHash(this Stream s, HashAlgorithm hasher = null)
186 {
187 if (hasher == null) hasher = SHA1.Create();
188 return hasher.ComputeHash(s);
189 }
190
191 /// <summary>
192 /// Gets the current instance's hash.
193 /// </summary>
194 /// <param name="s">The current instance.</param>
195 /// <param name="hasher">The hash function.</param>
196 /// <returns>The hash.</returns>
197 public static string GetHashString(this Stream s, HashAlgorithm hasher = null)
198 {
199 return String.Join("", s.GetHash(hasher).Select(f =>
200 {
201 string st = Convert.ToString(f, 16);
202 if (st.Length == 1) return "0" + st;
203 else return st;
204 }).ToArray());
205 }
206
207 /// <summary>
208 /// Gets the current instance's hash.
209 /// </summary>
210 /// <param name="s">The current instance.</param>
211 /// <param name="hasher">The hash function.</param>
212 /// <returns>The hash.</returns>
213 public static byte[] GetHash(this string s, HashAlgorithm hasher = null)
214 {
215 MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(s));
216 return ms.GetHash(hasher);
217 }
218
219 /// <summary>
220 /// Gets the current instance's hash.
221 /// </summary>
222 /// <param name="s">The current instance.</param>
223 /// <param name="hasher">The hash function.</param>
224 /// <returns>The hash.</returns>
225 public static string GetHashString(this string s, HashAlgorithm hasher = null)
226 {
227 MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(s));
228 return ms.GetHashString(hasher);
229 }
230
231 /// <summary>
232 /// Executes the specified action and returns the current instance.
233 /// </summary>
234 /// <typeparam name="T">The type of the current instance.</typeparam>
235 /// <param name="variable">The current instance.</param>
236 /// <param name="action">The action to execute.</param>
237 /// <returns>The current instance.</returns>
238 public static T Do<T>(this T variable, Action<T> action)
239 {
240 action(variable);
241 return variable;
242 }
243
244 /// <summary>
245 /// Executes the specified function and returns the result.
246 /// </summary>
247 /// <typeparam name="TIn">The type of the current instance.</typeparam>
248 /// <typeparam name="TOut">The type of the result.</typeparam>
249 /// <param name="variable">The current instance.</param>
250 /// <param name="func">The function to execute.</param>
251 /// <returns>The function result.</returns>
252 public static TOut Do<TIn, TOut>(this TIn variable, Func<TIn, TOut> func)
253 {
254 return func(variable);
255 }
256
257 #region ExecutionTime
258
259 /// <summary>
260 /// Calculates the execution time of the specified action.
261 /// </summary>
262 /// <param name="a">The action.</param>
263 /// <param name="handleGc">Whether to handle the garbage collector. If true, the GC will be forced to clean up before taking the time.</param>
264 /// <returns>The execution time in milliseconds.</returns>
265 public static TimeSpan ExecutionTime(this Action a, bool handleGc = true)
266 {
267 return Utils.ExecutionTime(a, handleGc);
268 }
269
270 /// <summary>
271 /// Calculates the execution time of the specified function.
272 /// </summary>
273 /// <param name="f">The function.</param>
274 /// <param name="handleGc">Whether to handle the garbage collector. If true, the GC will be forced to clean up before taking the time.</param>
275 /// <returns>The execution time in milliseconds, and the result of the function.</returns>
276 public static Tuple<TimeSpan, T> ExecutionTime<T>(this Func<T> f, bool handleGc = true)
277 {
278 T result = default(T);
279 return Tuple.Create(Utils.ExecutionTime(() => result = f(), handleGc), result);
280 }
281
282 /// <summary>
283 /// Calculates the execution time of the specified query.
284 /// </summary>
285 /// <param name="collection">The query.</param>
286 /// <param name="handleGc">Whether to handle the garbage collector. If true, the GC will be forced to clean up before taking the time.</param>
287 /// <returns>The execution time in milliseconds.</returns>
288 public static TimeSpan ExecutionTime<T>(this IEnumerable<T> collection, bool handleGc = true)
289 {
290 return Utils.ExecutionTime(() => collection.Execute(), handleGc);
291 }
292
293 #endregion ExecutionTime
294 }
1da62167 »
2011-03-21 Collection extension methods update.
295 }
Something went wrong with that request. Please try again.