azure-accelerators-project /Accelerator/AcceleratorExtensions.cs

Language C# Lines 517
MD5 Hash 0db8932bc3bc8c37519c54afbf7e79d1 Estimated Cost $6,753 (why?)
Repository https://bitbucket.org/zgramana/azure-accelerators-project View Raw File View Project SPDX
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
using System;
using System.Collections.Generic;
using System.IO;
using System.Security.AccessControl;
using System.Xml;
using System.Xml.Linq;
using System.Text;
using System.Data.Linq;
using System.Linq;
using System.Xml.Serialization;
using System.Xml.Xsl;

namespace Microsoft.WindowsAzure.Accelerator
{
    /// <summary>
    /// Extension methods for the Accelerators project.  (rdm)
    /// </summary>
    public static class AcceleratorExtensions
    {
#region | BASE EXTENSIONS

        /// <summary>
        /// Returns an element attribute matching the specified name and converted into the expected data type.  Handles null values gracefully.
        /// </summary>
        /// <param name="element">Element whose attributes we are matching by name.</param>
        /// <param name="attributeName">Name of the attribute to return the value of the specified type.</param>
        /// <returns>Attribute value converted to the specifed type</returns>
        public static String GetAttribute(this XElement element, XName attributeName)
        {
            return element.GetAttribute(attributeName, null);
        }

        /// <summary>
        /// Returns an element attribute matching the specified name and converted into the expected data type.  Handles null values gracefully.
        /// </summary>
        /// <param name="element">Element whose attributes we are matching by name.</param>
        /// <param name="attributeName">Name of the attribute to return the value of the specified type.</param>
        /// <param name="onEmptyString">The on empty string.</param>
        /// <returns>Attribute value converted to the specifed type.</returns>
        public static String GetAttribute(this XElement element, XName attributeName, String onEmptyString)
        {
            return element.OnValid(e => e.Attribute(attributeName).OnValid(a => a.Value)) ?? onEmptyString;
        }

        /// <summary>
        /// Performs the specified action on each element in the sequence handling null gracefully.
        /// </summary>
        /// <typeparam name="T">The item type.</typeparam>
        /// <param name="sequence">Sequence of items.</param>
        /// <param name="action">The action to perform.</param>
        public static void ForEach<T>(this IEnumerable<T> sequence, Action<T> action)
        {
            if ( sequence != null )
                foreach ( T item in sequence )
                    action(item);
        }

        /// <summary>
        /// Evaluates the function only when the current object is not null. Provides in-line null value check and continue on valid.
        /// </summary>
        /// <typeparam name="T">Context value type.</typeparam>
        /// <typeparam name="U">Return value type.</typeparam>
        /// <param name="value">Context value.</param>
        /// <param name="func">Function to perform on non-null context value.</param>
        /// <returns>Results of function evaluation.</returns>
        public static U OnValid<T,U>(this T value, Func<T, U> func) where T : class
        {
            return value != null ? func(value) : default(U);
        }

        /// <summary>
        /// Evaluates the action only when the current object is not null. Provides in-line null value check and continue on valid.
        /// </summary>
        /// <typeparam name="T">Context value type.</typeparam>
        /// <param name="value">Context value.</param>
        /// <param name="action">Action to perform on non-null context value.</param>
        public static void OnValid<T>(this T value, Action<T> action) where T : class
        {
            if ( value != null ) action(value);
        }

        /// <summary>
        /// Evaluates the function only when value is not null; and then inside a try/catch block.  Use OnValid if you wish to handle exceptions.
        /// </summary>
        /// <typeparam name="T">Context value type.</typeparam>
        /// <typeparam name="U">Return value type.</typeparam>
        /// <param name="value">Context value.</param>
        /// <param name="func">Function to perform on non-null context value.</param>
        /// <returns>Results of function evaluation.</returns>
        public static void Protect<T>(this T value, Action<T> func) where T : class
        {
            if ( value != null )
                try { func(value); }
                catch {}
        }

        /// <summary>
        /// Evaluates the function only when value is not null; and then inside a try/catch block.  Use OnValid if you wish to handle exceptions.
        /// </summary>
        /// <typeparam name="T">Context value type.</typeparam>
        /// <typeparam name="U">Return value type.</typeparam>
        /// <param name="value">Context value.</param>
        /// <param name="func">Function to perform on non-null context value.</param>
        /// <returns>Results of function evaluation.</returns>
        public static U Protect<T, U>(this T value, Func<T, U> func) where T : class
        {
            if ( value != null )
                try { return func(value); }
                catch { }
            return default(U);
        }
        /// <summary>
        /// Performs type conversion of the value to the specified type handling nulls with default.
        /// </summary>
        /// <typeparam name="T">The return type.</typeparam>
        /// <param name="value">The object.</param>
        /// <returns>Value converted to type T.</returns>
        public static T As<T>(this Object value) where T : IConvertible 
        {
            return value == null ? default(T) : (T)Convert.ChangeType(value, typeof(T));
        }
        /// <summary>
        /// Tests if the string is a valid value of the enum type.
        /// </summary>
        /// <typeparam name="T">The target enum type.</typeparam>
        /// <param name="value">The string value to test.</param>
        /// <returns>True if the value is a valid member of the enum.</returns>
        public static Boolean IsEnum<T>(this String value)
        {
            return Enum.IsDefined(typeof (T), value);
        }

        /// <summary>
        /// Returns the nullable enum value of the string for the provided enum type; otherwise null.
        /// </summary>
        /// <typeparam name="T">The target enum type.</typeparam>
        /// <param name="value">The string value for conversion.</param>
        /// <returns>Nullable of the enum type.</returns>
        public static T? ToEnum<T>(this String value) where T : struct
        {
            return (IsEnum<T>(value) ? (T?) Enum.Parse(typeof (T), value) : null);
        }

        /// <summary>
        /// Selects a descendant heirarchy into a flattened list.
        /// </summary>
        /// <typeparam name="T">The type.</typeparam>
        /// <param name="source">The source.</param>
        /// <param name="selector">The selector.</param>
        /// <returns>An enumerator.</returns>
        public static IEnumerable<T> SelectDeep<T>(this IEnumerable<T> source, Func<T, IEnumerable<T>> selector)
        {
            foreach (T item in source)
            {
                yield return item;
                foreach (T subItem in SelectDeep(selector(item), selector))
                {
                    yield return subItem;
                }
            }
        }

        /// <summary>
        /// Splits as string and returns a list of the specified type.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="value">The string to split.</param>
        /// <param name="settingSeparator">The separator.</param>
        /// <returns>List of type T.</returns>
        public static List<T> SplitToList<T>(this String value, Char[] settingSeparator) where T : IConvertible
        {
            return value.Split(settingSeparator, StringSplitOptions.RemoveEmptyEntries).Cast<T>().ToList();
        }

        /// <summary>
        /// Splits a string into pairs, then into keys and values, returning a dictionary.
        /// </summary>
        /// <typeparam name="TKey">The dictionary key type.</typeparam>
        /// <typeparam name="TValue">The dictionary value type.</typeparam>
        /// <param name="value">The string to splid.</param>
        /// <param name="pairsSeparator">The paired items separator.</param>
        /// <param name="valuesSeparator">The key value separator for each pair.</param>
        /// <returns>Dictionary</returns>
        public static Dictionary<TKey, TValue> SplitToDictionary<TKey,TValue>(this String value, Char[] pairsSeparator, Char[] valuesSeparator) where TKey : IConvertible where TValue : IConvertible
        {
            return value.SplitToList<String>(pairsSeparator).Select(pairs 
                => pairs.Split(valuesSeparator, StringSplitOptions.RemoveEmptyEntries)).ToDictionary(kvp 
                    => kvp[0].As<TKey>(), kvp => kvp[1].As<TValue>());
        }

        /// <summary>
        /// Creates a string based respresentation of a dictionary.
        /// </summary>
        /// <typeparam name="TKey">The type of the key.</typeparam>
        /// <typeparam name="TValue">The type of the value.</typeparam>
        /// <param name="dictionary">The dictionary values.</param>
        /// <param name="keyFormat">The key format.</param>
        /// <param name="valueFormat">The value format.</param>
        /// <returns>
        /// String representation of the key value pairs.
        /// </returns>
        public static String ToString<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, String keyFormat, String valueFormat)
        {
            if ( dictionary == null )
                return null;
            return String.Concat(dictionary.Select(x => String.Format("{0}{1}", String.Format(keyFormat, x.Key.ToString()), String.Format(valueFormat, x.Value.ToString()))).ToArray());
        }

        /// <summary>
        /// Creates a string based respresentation of a dictionary.
        /// </summary>
        /// <param name="dictionary">The dictionary values.</param>
        /// <param name="keyFormat">The key format.</param>
        /// <param name="valueFormat">The value format.</param>
        /// <returns>
        /// String representation of the key value pairs.
        /// </returns>
        public static String ToString(this System.Collections.IDictionary dictionary, String keyFormat, String valueFormat)
        {
            return dictionary.ToString(keyFormat, valueFormat);
        }

        /// <summary>
        /// Returns a <see cref="System.String"/> that representation of the FileSecurity attributes. 
        /// </summary>
        /// <param name="security">The security.</param>
        /// <param name="format">The format - must contain: {0}, {1}, {2} identifiers.</param>
        /// <param name="includeExplicit">if set to <c>true</c> [include explicit].</param>
        /// <param name="includeInherited">if set to <c>true</c> [include inherited].</param>
        /// <returns>
        /// A <see cref="System.String"/> that represents this instance.
        /// </returns>
        public static String ToString(this FileSecurity security, String format, Boolean includeExplicit, Boolean includeInherited)
        {
            var sb  = new StringBuilder();

            var accessRules = security.GetAccessRules(includeExplicit, includeInherited, typeof (System.Security.Principal.SecurityIdentifier)).OfType<FileSystemAccessRule>().ToList();
            
            foreach (FileSystemAccessRule rule in accessRules)
            {
                sb.AppendFormat(format, 
                                String.Format("{{[\"{0}\"], '{1}'}}", 
                                              rule.IdentityReference.Value, 
                                              rule.AccessControlType),
                                String.Format("\r\n\t{{\r\n{0}\r\n\t}}\r\n\t{{\r\n{1}\r\n\t}}\r\n",
                                              rule.FileSystemRights.ToString("\t\t{{[\"{0}\"], '{1}'}},\r\n", true),
                                              rule.PropagationFlags.ToString("\t\t{{[\"{0}\"], '{1}'}},\r\n", true)));
            }
            return sb.ToString();
        }

        /// <summary>
        /// Returns a <see cref="System.String"/> that represents this instance of propagation flags.
        /// </summary>
        /// <param name="flags">The flags.</param>
        /// <param name="kvpFormat">The KVP format.</param>
        /// <param name="includeImplicit">if set to <c>true</c> [include implicit].</param>
        /// <returns>
        /// A <see cref="System.String"/> that represents this instance.
        /// </returns>
        public static String ToString(this PropagationFlags flags, String kvpFormat, Boolean includeImplicit)
        {
            var sb = new StringBuilder();
            foreach ( PropagationFlags f in Enum.GetValues(typeof(PropagationFlags)) )
            {
                if ( includeImplicit || ( ( flags & f ) == f ) )
                    sb.AppendFormat(kvpFormat, f, ( flags & f ) == f);
            }
            return sb.ToString();
        }

        /// <summary>
        /// Returns a <see cref="System.String"/> that represents this instance of file system rights.
        /// </summary>
        /// <param name="rights">The rights.</param>
        /// <param name="kvpFormat">The KVP format.</param>
        /// <param name="includeImplicit">if set to <c>true</c> [include implicit].</param>
        /// <returns>
        /// A <see cref="System.String"/> that represents this instance.
        /// </returns>
        public static String ToString(this FileSystemRights rights, String kvpFormat, Boolean includeImplicit)
        {
            var sb = new StringBuilder();
            foreach ( FileSystemRights r in Enum.GetValues(typeof(FileSystemRights)) )
            {
                if (includeImplicit || ((rights & r) == r))
                    sb.AppendFormat(kvpFormat, r, ( rights & r ) == r);
            }
            return sb.ToString();
        }

        /// <summary>
        /// Returns a <see cref="System.String"/> that represents this instance of file attributes.
        /// </summary>
        /// <param name="attributes">The attributes.</param>
        /// <param name="kvpFormat">The KVP format.</param>
        /// <param name="includeImplicit">if set to <c>true</c> [include implicit].</param>
        /// <returns>
        /// A <see cref="System.String"/> that represents this instance.
        /// </returns>
        public static String ToString(this FileAttributes attributes, String kvpFormat, Boolean includeImplicit)
        {
            var sb = new StringBuilder();
            foreach(FileAttributes a in Enum.GetValues(typeof(FileAttributes)))
            {
                if (includeImplicit || ((attributes & a) == a))
                    sb.AppendFormat(kvpFormat, a, (attributes & a) == a);
            }
            return sb.ToString();
        }

        /// <summary>
        /// Replaces the path char with the separator provided.
        /// </summary>
        /// <param name="path">The path.</param>
        /// <param name="replacePathChar">The replacement char.</param>
        /// <remarks>If the supplied path char is a backslash, the assumption is that the path char to be replaced is the forward slash.  In all other instances the path char to be replaced is the backslash.</remarks>
        /// <returns></returns>
        public static String SetPathChar(this String path, Char replacePathChar)
        {
            if ( String.IsNullOrEmpty(path) )
                return path;
            return replacePathChar == '\\' ? path.Replace('/', '\\') : path.Replace('\\', replacePathChar);
        }

        /// <summary>
        /// Ensures that this string start with the string provided; otherwise it prepends the string.
        /// </summary>
        /// <param name="value">This string.</param>
        /// <param name="startWith">The start with string.</param>
        /// <returns></returns>
        public static String EnsureStartsWith(this String value, String startWith)
        {
            return value != null && value.StartsWith(startWith) ? value : startWith + (value ?? String.Empty);
        }

        /// <summary>
        /// Ensures that the supplied string ends with the specified characters. The characters are appended if not already existing.
        /// </summary>
        /// <param name="value">The value.</param>
        /// <param name="endWith">The end of the string..</param>
        /// <returns></returns>
        public static String EnsureEndsWith(this String value, String endWith)
        {
            return value != null && value.EndsWith(endWith) ? value : (value ?? String.Empty) + endWith;
        }
        
#endregion      
#region | BINARY

        /// <summary>
        /// Write the binary field to a target file.
        /// </summary>
        public static void ToFile(this Binary binary, String targetFile)
        {
            if ( binary != null )
                File.WriteAllBytes(targetFile, binary.ToArray());
        }

        /// <summary>
        /// Write the binary field to a text string.
        /// </summary>
        public static String ToText(this Binary binary)
        {
            using ( var ms = new MemoryStream(binary.ToArray()) )
            using ( var sr = new StreamReader(ms) )
                return sr.ReadToEnd();
        }

        /// <summary>
        /// Write the binary field to an XDocument.
        /// </summary>
        public static XDocument ToXDocument(this Binary binary)
        {
            using ( var ms = new MemoryStream(binary.ToArray()) )
            using ( var sr = new XmlTextReader(ms) )
                return XDocument.Load(sr, LoadOptions.None);
        }

#endregion  
#region | SERIALIZATION

        /// <summary>
        /// Serialize the entity as XML to the provided file.
        /// </summary>
        /// <typeparam name="T">The object type.</typeparam>
        public static void SerializeToXml<T>(T entity, String fileName)
        {
            using (var fileStream = new FileStream(fileName, FileMode.Create))
            {
                var ser = new XmlSerializer(typeof(T));
                ser.Serialize(fileStream, entity);
            }
        }

        /// <summary>
        /// Deserialize the entity from XML file.
        /// </summary>
        /// <typeparam name="T">The object type.</typeparam>
        public static T DeserializeFromXml<T>(String xml)
        {
            T result;
            var ser = new XmlSerializer(typeof(T));
            using (var tr = new StringReader(xml))
            {
                result = (T)ser.Deserialize(tr);
            }
            return result;
        }

        /// <summary>
        /// Serlizes the object to XML, using an empty namespace.
        /// </summary>
        /// <typeparam name="T">The object type.</typeparam>
        public static XDocument Serialize<T>(this T entity) { return Serialize(entity, ""); }


        /// <summary>
        /// Serlizes the object to XML, using the provided namespace.
        /// </summary>
        public static XDocument Serialize<T>(this T entity, String nameSpace)
        {
            var result = new XDocument();
            using (var resultWriter = result.CreateWriter())
            {
                var xmls = new XmlSerializer(typeof(T), nameSpace);
                xmls.Serialize(resultWriter, entity);
            }
            return result;
        }

#endregion
#region | XSLT

        /// <summary>
        /// Transform the XML represented in the XmlReader.
        /// </summary>
        /// <returns>An Xml reader.</returns>
        public static XmlReader Transform(this XslCompiledTransform xslt, XmlReader xml)
        {
            var result = new XDocument();
            using (var resultWriter = result.CreateWriter())
                xslt.Transform(xml, resultWriter);
            return result.CreateReader();
        }

        /// <summary>
        /// Renders the serialized XML of the entity to an XmlDocument.
        /// </summary>
        /// <typeparam name="T">The entity type.</typeparam>
        public static XmlDocument Render<T>(this XslCompiledTransform xslt, T entity)
        {
            var xmlDoc = new XmlDocument();
            xmlDoc.Load(Transform(xslt, Serialize(entity).CreateReader()));
            return xmlDoc;
        }

#endregion

       

    }

#region | PATH

    //b|
    //b| Scrap: Remove as time permits.
    //b|
    public class Path
    {
        private String _path = String.Empty;
        public Path(String path) { _path = path.TrimEnd('\\'); }
        public static implicit operator Path(String value) { return new Path(value); }
        public static implicit operator String(Path path) { return path.ToString(); }
        public override String ToString() { return _path; }
        public static Path GetFullPath(String path) { return System.IO.Path.GetFullPath(path); }
        public static Path GetFileName(String path) { return System.IO.Path.GetFileName(path); }
        public static Path Combine(String path, String path2) { return System.IO.Path.Combine(path, path2); }
        public static Boolean FileExists(Path path) { return System.IO.File.Exists(path); }
        public static Boolean FolderExists(Path path) { return System.IO.Directory.Exists(path); }
    }

    public static class PathExtensions
    {
        public static Path Combine(this Path path, String path2) { return System.IO.Path.Combine(path, path2); }
        public static Path GetFolder(this Path path) { return System.IO.Path.GetDirectoryName(path); }
        public static Boolean IsRootPath(this Path path)
        {
            try
            {
                GetFolder(GetFolder(path));
                return false;
            }
            catch
            {
                return true;
            }
        }
        public static Path GetParentFolder(this Path path) { return GetFolder(GetFolder(path)); }
        public static Path GetFullPath(this Path path) { return System.IO.Path.GetFullPath(path); }
        public static Path GetFileName(this Path path) { return System.IO.Path.GetFileName(path); }
        public static Path GetExtension(this Path path) { return System.IO.Path.GetExtension(path); }
        public static String EnQuote(this Path path) { return String.Format(@"""{0}""", path); }

        public static void CopyPath(this Path source, Path target)
        {
            if (String.IsNullOrEmpty(source))
                throw new ArgumentNullException("source", "The source path cannot be null.");
            if (String.IsNullOrEmpty(target))
                throw new ArgumentNullException("target", "The target path cannot be null.");
            ConsoleProcess.CopyFolder(source, target);
        }
    }

#endregion
}
Back to Top