diff options
| author | LukePulverenti <luke.pulverenti@gmail.com> | 2013-02-20 20:33:05 -0500 |
|---|---|---|
| committer | LukePulverenti <luke.pulverenti@gmail.com> | 2013-02-20 20:33:05 -0500 |
| commit | 767cdc1f6f6a63ce997fc9476911e2c361f9d402 (patch) | |
| tree | 49add55976f895441167c66cfa95e5c7688d18ce /MediaBrowser.Common/Extensions | |
| parent | 845554722efaed872948a9e0f7202e3ef52f1b6e (diff) | |
Pushing missing changes
Diffstat (limited to 'MediaBrowser.Common/Extensions')
| -rw-r--r-- | MediaBrowser.Common/Extensions/BaseExtensions.cs | 233 | ||||
| -rw-r--r-- | MediaBrowser.Common/Extensions/NamedLock.cs | 97 | ||||
| -rw-r--r-- | MediaBrowser.Common/Extensions/ResourceNotFoundException.cs | 28 | ||||
| -rw-r--r-- | MediaBrowser.Common/Extensions/XmlExtensions.cs | 201 |
4 files changed, 496 insertions, 63 deletions
diff --git a/MediaBrowser.Common/Extensions/BaseExtensions.cs b/MediaBrowser.Common/Extensions/BaseExtensions.cs index 77eb9fbb4a..e6b9d8ee66 100644 --- a/MediaBrowser.Common/Extensions/BaseExtensions.cs +++ b/MediaBrowser.Common/Extensions/BaseExtensions.cs @@ -1,63 +1,170 @@ -using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
-using System.Security.Cryptography;
-
-namespace MediaBrowser.Common.Extensions
-{
- public static class BaseExtensions
- {
- static MD5CryptoServiceProvider md5Provider = new MD5CryptoServiceProvider();
-
- public static Guid GetMD5(this string str)
- {
- lock (md5Provider)
- {
- return new Guid(md5Provider.ComputeHash(Encoding.Unicode.GetBytes(str)));
- }
- }
-
- /// <summary>
- /// Examine a list of strings assumed to be file paths to see if it contains a parent of
- /// the provided path.
- /// </summary>
- /// <param name="lst"></param>
- /// <param name="path"></param>
- /// <returns></returns>
- public static bool ContainsParentFolder(this List<string> lst, string path)
- {
- path = path.TrimEnd('\\');
- foreach (var str in lst)
- {
- //this should be a little quicker than examining each actual parent folder...
- var compare = str.TrimEnd('\\');
- if (path.Equals(compare,StringComparison.OrdinalIgnoreCase)
- || (path.StartsWith(compare, StringComparison.OrdinalIgnoreCase) && path[compare.Length] == '\\')) return true;
- }
- return false;
- }
-
- /// <summary>
- /// Helper method for Dictionaries since they throw on not-found keys
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <typeparam name="U"></typeparam>
- /// <param name="dictionary"></param>
- /// <param name="key"></param>
- /// <param name="defaultValue"></param>
- /// <returns></returns>
- public static U GetValueOrDefault<T, U>(this Dictionary<T, U> dictionary, T key, U defaultValue)
- {
- U val;
- if (!dictionary.TryGetValue(key, out val))
- {
- val = defaultValue;
- }
- return val;
-
- }
-
- }
-}
+using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using System.Security.Cryptography; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Threading; + +namespace MediaBrowser.Common.Extensions +{ + /// <summary> + /// Class BaseExtensions + /// </summary> + public static class BaseExtensions + { + /// <summary> + /// Tries the add. + /// </summary> + /// <typeparam name="TKey">The type of the T key.</typeparam> + /// <typeparam name="TValue">The type of the T value.</typeparam> + /// <param name="dictionary">The dictionary.</param> + /// <param name="key">The key.</param> + /// <param name="value">The value.</param> + /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns> + public static bool TryAdd<TKey, TValue>(this Dictionary<TKey, TValue> dictionary, TKey key, TValue value) + { + if (dictionary.ContainsKey(key)) + { + return false; + } + + dictionary.Add(key, value); + return true; + } + + /// <summary> + /// Provides an additional overload for string.split + /// </summary> + /// <param name="val">The val.</param> + /// <param name="separator">The separator.</param> + /// <param name="options">The options.</param> + /// <returns>System.String[][].</returns> + public static string[] Split(this string val, char separator, StringSplitOptions options) + { + return val.Split(new[] { separator }, options); + } + + /// <summary> + /// Invokes an action after a specified delay + /// </summary> + /// <param name="dispatcher">The dispatcher.</param> + /// <param name="action">The action.</param> + /// <param name="delayMs">The delay ms.</param> + public static void InvokeWithDelay(this Dispatcher dispatcher, Action action, long delayMs) + { + var timer = new DispatcherTimer(DispatcherPriority.Normal, dispatcher); + timer.Interval = TimeSpan.FromMilliseconds(delayMs); + timer.Tick += (sender, args) => + { + timer.Stop(); + action(); + }; + timer.Start(); + } + + /// <summary> + /// Provides a non-blocking method to start a process and wait asynchronously for it to exit + /// </summary> + /// <param name="process">The process.</param> + /// <returns>Task{System.Boolean}.</returns> + public static Task<bool> RunAsync(this Process process) + { + var tcs = new TaskCompletionSource<bool>(); + + process.EnableRaisingEvents = true; + process.Exited += (sender, args) => tcs.SetResult(true); + + process.Start(); + + return tcs.Task; + } + + /// <summary> + /// Shuffles an IEnumerable + /// </summary> + /// <typeparam name="T"></typeparam> + /// <param name="list">The list.</param> + /// <returns>IEnumerable{``0}.</returns> + public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> list) + { + return list.OrderBy(x => Guid.NewGuid()); + } + + /// <summary> + /// Gets the M d5. + /// </summary> + /// <param name="str">The STR.</param> + /// <returns>Guid.</returns> + public static Guid GetMD5(this string str) + { + using (var provider = new MD5CryptoServiceProvider()) + { + return new Guid(provider.ComputeHash(Encoding.Unicode.GetBytes(str))); + } + } + + /// <summary> + /// Gets the MB id. + /// </summary> + /// <param name="str">The STR.</param> + /// <param name="aType">A type.</param> + /// <returns>Guid.</returns> + /// <exception cref="System.ArgumentNullException">aType</exception> + public static Guid GetMBId(this string str, Type aType) + { + if (aType == null) + { + throw new ArgumentNullException("aType"); + } + + return (aType.FullName + str.ToLower()).GetMD5(); + } + + /// <summary> + /// Helper method for Dictionaries since they throw on not-found keys + /// </summary> + /// <typeparam name="T"></typeparam> + /// <typeparam name="U"></typeparam> + /// <param name="dictionary">The dictionary.</param> + /// <param name="key">The key.</param> + /// <param name="defaultValue">The default value.</param> + /// <returns>``1.</returns> + public static U GetValueOrDefault<T, U>(this Dictionary<T, U> dictionary, T key, U defaultValue) + { + U val; + if (!dictionary.TryGetValue(key, out val)) + { + val = defaultValue; + } + return val; + + } + + /// <summary> + /// Gets the attribute value. + /// </summary> + /// <param name="str">The STR.</param> + /// <param name="attrib">The attrib.</param> + /// <returns>System.String.</returns> + /// <exception cref="System.ArgumentNullException">attrib</exception> + public static string GetAttributeValue(this string str, string attrib) + { + if (attrib == null) + { + throw new ArgumentNullException("attrib"); + } + + string srch = "[" + attrib + "="; + int start = str.IndexOf(srch, StringComparison.OrdinalIgnoreCase); + if (start > -1) + { + start += srch.Length; + int end = str.IndexOf(']', start); + return str.Substring(start, end - start); + } + return null; + } + } +} diff --git a/MediaBrowser.Common/Extensions/NamedLock.cs b/MediaBrowser.Common/Extensions/NamedLock.cs new file mode 100644 index 0000000000..d0164c70d0 --- /dev/null +++ b/MediaBrowser.Common/Extensions/NamedLock.cs @@ -0,0 +1,97 @@ +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; + +namespace MediaBrowser.Common.Extensions +{ + /// <summary> + /// Class NamedLock + /// </summary> + public class NamedLock : IDisposable + { + /// <summary> + /// The _locks + /// </summary> + private readonly Dictionary<string, SemaphoreSlim> _locks = new Dictionary<string, SemaphoreSlim>(); + + /// <summary> + /// Waits the async. + /// </summary> + /// <param name="name">The name.</param> + /// <returns>Task.</returns> + public Task WaitAsync(string name) + { + return GetLock(name).WaitAsync(); + } + + /// <summary> + /// Releases the specified name. + /// </summary> + /// <param name="name">The name.</param> + public void Release(string name) + { + SemaphoreSlim semaphore; + + if (_locks.TryGetValue(name, out semaphore)) + { + semaphore.Release(); + } + } + + /// <summary> + /// Gets the lock. + /// </summary> + /// <param name="filename">The filename.</param> + /// <returns>System.Object.</returns> + private SemaphoreSlim GetLock(string filename) + { + SemaphoreSlim fileLock; + lock (_locks) + { + if (!_locks.TryGetValue(filename, out fileLock)) + { + fileLock = new SemaphoreSlim(1,1); + _locks[filename] = fileLock; + } + } + return fileLock; + } + + /// <summary> + /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. + /// </summary> + public void Dispose() + { + Dispose(true); + } + + /// <summary> + /// Releases unmanaged and - optionally - managed resources. + /// </summary> + /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param> + protected virtual void Dispose(bool dispose) + { + if (dispose) + { + DisposeLocks(); + } + } + + /// <summary> + /// Disposes the locks. + /// </summary> + private void DisposeLocks() + { + lock (_locks) + { + foreach (var semaphore in _locks.Values) + { + semaphore.Dispose(); + } + + _locks.Clear(); + } + } + } +} diff --git a/MediaBrowser.Common/Extensions/ResourceNotFoundException.cs b/MediaBrowser.Common/Extensions/ResourceNotFoundException.cs new file mode 100644 index 0000000000..403236b3da --- /dev/null +++ b/MediaBrowser.Common/Extensions/ResourceNotFoundException.cs @@ -0,0 +1,28 @@ +using System; + +namespace MediaBrowser.Common.Extensions +{ + /// <summary> + /// Class ResourceNotFoundException + /// </summary> + public class ResourceNotFoundException : Exception + { + /// <summary> + /// Initializes a new instance of the <see cref="ResourceNotFoundException" /> class. + /// </summary> + public ResourceNotFoundException() + { + + } + + /// <summary> + /// Initializes a new instance of the <see cref="ResourceNotFoundException" /> class. + /// </summary> + /// <param name="message">The message.</param> + public ResourceNotFoundException(string message) + : base(message) + { + + } + } +} diff --git a/MediaBrowser.Common/Extensions/XmlExtensions.cs b/MediaBrowser.Common/Extensions/XmlExtensions.cs new file mode 100644 index 0000000000..6f626d3283 --- /dev/null +++ b/MediaBrowser.Common/Extensions/XmlExtensions.cs @@ -0,0 +1,201 @@ +using System; +using System.Globalization; +using System.Xml; + +namespace MediaBrowser.Common.Extensions +{ + /// <summary> + /// Class XmlExtensions + /// </summary> + public static class XmlExtensions + { + + /// <summary> + /// Safes the get int32. + /// </summary> + /// <param name="doc">The doc.</param> + /// <param name="path">The path.</param> + /// <returns>System.Int32.</returns> + public static int SafeGetInt32(this XmlDocument doc, string path) + { + return SafeGetInt32(doc, path, 0); + } + + /// <summary> + /// Safes the get int32. + /// </summary> + /// <param name="doc">The doc.</param> + /// <param name="path">The path.</param> + /// <param name="defaultInt">The default int.</param> + /// <returns>System.Int32.</returns> + public static int SafeGetInt32(this XmlDocument doc, string path, int defaultInt) + { + XmlNode rvalNode = doc.SelectSingleNode(path); + if (rvalNode != null && rvalNode.InnerText.Length > 0) + { + int rval; + if (Int32.TryParse(rvalNode.InnerText, out rval)) + { + return rval; + } + + } + return defaultInt; + } + + /// <summary> + /// The _us culture + /// </summary> + private static readonly CultureInfo _usCulture = new CultureInfo("en-US"); + + /// <summary> + /// Safes the get single. + /// </summary> + /// <param name="doc">The doc.</param> + /// <param name="path">The path.</param> + /// <param name="minValue">The min value.</param> + /// <param name="maxValue">The max value.</param> + /// <returns>System.Single.</returns> + public static float SafeGetSingle(this XmlDocument doc, string path, float minValue, float maxValue) + { + XmlNode rvalNode = doc.SelectSingleNode(path); + if (rvalNode != null && rvalNode.InnerText.Length > 0) + { + float rval; + // float.TryParse is local aware, so it can be probamatic, force us culture + if (float.TryParse(rvalNode.InnerText, NumberStyles.AllowDecimalPoint, _usCulture, out rval)) + { + if (rval >= minValue && rval <= maxValue) + { + return rval; + } + } + + } + return minValue; + } + + + /// <summary> + /// Safes the get string. + /// </summary> + /// <param name="doc">The doc.</param> + /// <param name="path">The path.</param> + /// <returns>System.String.</returns> + public static string SafeGetString(this XmlDocument doc, string path) + { + return SafeGetString(doc, path, null); + } + + /// <summary> + /// Safes the get string. + /// </summary> + /// <param name="doc">The doc.</param> + /// <param name="path">The path.</param> + /// <param name="defaultString">The default string.</param> + /// <returns>System.String.</returns> + public static string SafeGetString(this XmlDocument doc, string path, string defaultString) + { + XmlNode rvalNode = doc.SelectSingleNode(path); + if (rvalNode != null && rvalNode.InnerText.Trim().Length > 0) + { + return rvalNode.InnerText; + } + return defaultString; + } + + /// <summary> + /// Safes the get string. + /// </summary> + /// <param name="doc">The doc.</param> + /// <param name="path">The path.</param> + /// <returns>System.String.</returns> + public static string SafeGetString(this XmlNode doc, string path) + { + return SafeGetString(doc, path, null); + } + + /// <summary> + /// Safes the get string. + /// </summary> + /// <param name="doc">The doc.</param> + /// <param name="path">The path.</param> + /// <param name="defaultValue">The default value.</param> + /// <returns>System.String.</returns> + public static string SafeGetString(this XmlNode doc, string path, string defaultValue) + { + XmlNode rvalNode = doc.SelectSingleNode(path); + if (rvalNode != null && rvalNode.InnerText.Length > 0) + { + return rvalNode.InnerText; + } + return defaultValue; + } + + /// <summary> + /// Reads the string safe. + /// </summary> + /// <param name="reader">The reader.</param> + /// <returns>System.String.</returns> + public static string ReadStringSafe(this XmlReader reader) + { + var val = reader.ReadElementContentAsString(); + + return string.IsNullOrWhiteSpace(val) ? null : val; + } + + /// <summary> + /// Reads the value safe. + /// </summary> + /// <param name="reader">The reader.</param> + /// <returns>System.String.</returns> + public static string ReadValueSafe(this XmlReader reader) + { + reader.Read(); + + var val = reader.Value; + + return string.IsNullOrWhiteSpace(val) ? null : val; + } + + /// <summary> + /// Reads a float from the current element of an XmlReader + /// </summary> + /// <param name="reader">The reader.</param> + /// <returns>System.Single.</returns> + public static float ReadFloatSafe(this XmlReader reader) + { + string valueString = reader.ReadElementContentAsString(); + + float value = 0; + + if (!string.IsNullOrWhiteSpace(valueString)) + { + // float.TryParse is local aware, so it can be probamatic, force us culture + float.TryParse(valueString, NumberStyles.AllowDecimalPoint, _usCulture, out value); + } + + return value; + } + + /// <summary> + /// Reads an int from the current element of an XmlReader + /// </summary> + /// <param name="reader">The reader.</param> + /// <returns>System.Int32.</returns> + public static int ReadIntSafe(this XmlReader reader) + { + string valueString = reader.ReadElementContentAsString(); + + int value = 0; + + if (!string.IsNullOrWhiteSpace(valueString)) + { + + int.TryParse(valueString, out value); + } + + return value; + } + } +}
\ No newline at end of file |
