/// <summary>
        /// Progressive retry for a function call.
        /// </summary>
        /// <param name="operation">The operation to perform.</param>
        /// <param name="retryCount">The retry count (default 3).</param>
        /// <param name="retryWaitMilliseconds">The retry wait milliseconds (default 100).</param>
        /// <returns>System.Int32.</returns>
        public static int ProgressiveRetry(Action operation, byte retryCount = 3, int retryWaitMilliseconds = 100)
        {
            Encapsulation.TryValidateParam <ArgumentNullException>(operation != null);
            Encapsulation.TryValidateParam <ArgumentOutOfRangeException>(retryCount > 0);
            Encapsulation.TryValidateParam <ArgumentOutOfRangeException>(retryWaitMilliseconds > 0);

            var attempts = 0;

            do
            {
                try
                {
                    attempts++;

#pragma warning disable CS8602 // Dereference of a possibly null reference.
                    operation();
#pragma warning restore CS8602 // Dereference of a possibly null reference.

                    return(attempts);
                }
                catch (Exception ex)
                {
                    // Using Exception since the actual exception is unknown beforehand.
                    if (attempts == retryCount)
                    {
                        throw;
                    }

                    Debug.WriteLine(ex.GetAllMessages());

                    Task.Delay(retryWaitMilliseconds * attempts).Wait();
                }
            } while (true);
        }
示例#2
0
        public static RegistryKey?GetRegistryKey(string keyName, RegistryHive registryKeyType)
        {
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) == false)
            {
                throw new PlatformNotSupportedException();
            }

            Encapsulation.TryValidateParam(keyName, nameof(keyName));

            switch (registryKeyType)
            {
            case RegistryHive.ClassesRoot:
                return(Registry.ClassesRoot.OpenSubKey(keyName));

            case RegistryHive.CurrentConfig:
                return(Registry.CurrentConfig.OpenSubKey(keyName));

            case RegistryHive.CurrentUser:
                return(Registry.CurrentUser.OpenSubKey(keyName));

            case RegistryHive.LocalMachine:
                return(Registry.LocalMachine.OpenSubKey(keyName));

            case RegistryHive.PerformanceData:
                return(Registry.PerformanceData.OpenSubKey(keyName));

            case RegistryHive.Users:
                return(Registry.CurrentUser.OpenSubKey(keyName));
            }

            return(null);
        }
        /// <summary>
        /// Moves the file.
        /// </summary>
        /// <param name="sourceFileName">Name of the source file.</param>
        /// <param name="destinationFileName">Name of the destination file.</param>
        public static void MoveFile(string sourceFileName, string destinationFileName)
        {
            Encapsulation.TryValidateParam(sourceFileName, nameof(sourceFileName));
            Encapsulation.TryValidateParam(destinationFileName, nameof(destinationFileName));
            Encapsulation.TryValidateParam <ArgumentInvalidException>(File.Exists(sourceFileName),
                                                                      nameof(sourceFileName),
                                                                      $"File {sourceFileName} does not exist.");

            for (var retryCount = 0; retryCount < Retries; retryCount++)
            {
                try
                {
                    File.Move(sourceFileName, destinationFileName);
                    return;
                }
                catch (IOException) when(retryCount < Retries - 1)
                {
                }
                catch (UnauthorizedAccessException) when(retryCount < Retries - 1)
                {
                }

                // If something has a transient lock on the file waiting may resolve the issue
                Thread.Sleep((retryCount + 1) * 10);
            }
        }
示例#4
0
        /// <summary>
        /// Moves the directory with retry.
        /// </summary>
        /// <param name="sourceDirectoryName">Name of the source dir.</param>
        /// <param name="destinationDirectoryName">Name of the destination dir.</param>
        /// <param name="retries">Number of retries.</param>
        /// <remarks>Checks for the <see cref="IOException" /> and <see cref="UnauthorizedAccessException" />.</remarks>
        public static void MoveDirectory(string sourceDirectoryName, string destinationDirectoryName, int retries = 10)
        {
            Encapsulation.TryValidateParam(sourceDirectoryName, nameof(sourceDirectoryName));
            Encapsulation.TryValidateParam(destinationDirectoryName, nameof(destinationDirectoryName));
            Encapsulation.TryValidateParam <ArgumentInvalidException>(Directory.Exists(sourceDirectoryName));

            retries = Math.Max(1, retries);
            var tries = 0;

            do
            {
                tries++;

                if (tries > 1)
                {
                    // If something has a transient lock on the file waiting may resolve the issue
                    Thread.Sleep((retries + 1) * 10);
                }

                try
                {
                    Directory.Move(sourceDirectoryName, destinationDirectoryName);
                    return;
                }
                catch (IOException) when(tries >= retries)
                {
                    throw;
                }
                catch (UnauthorizedAccessException) when(tries >= retries)
                {
                    throw;
                }
            }while (tries < retries);
        }
示例#5
0
        /// <summary>
        /// Load files as an asynchronous operation.
        /// </summary>
        /// <param name="directories">The directories.</param>
        /// <param name="searchPattern">The search pattern.</param>
        /// <param name="searchOption">The search option.</param>
        /// <returns>IAsyncEnumerable&lt;IEnumerable&lt;FileInfo&gt;&gt;.</returns>
        public static async IAsyncEnumerable <IEnumerable <FileInfo> > LoadFilesAsync(IEnumerable <DirectoryInfo> directories, string searchPattern, SearchOption searchOption)
        {
            Encapsulation.TryValidateParam(directories, nameof(directories));
            Encapsulation.TryValidateParam(searchPattern, nameof(searchPattern));
            Encapsulation.TryValidateParam(searchOption, nameof(searchOption));

            var options = new EnumerationOptions()
            {
                IgnoreInaccessible = true
            };

            if (searchOption == SearchOption.AllDirectories)
            {
                options.RecurseSubdirectories = true;
            }

            var validDirectories = directories.Where(directory => directory.Exists).Select(directory => directory).ToList();

            foreach (var directory in validDirectories)
            {
                var files = await Task.Run(() => directory.EnumerateFiles(searchPattern, options)).ConfigureAwait(false);

                yield return(files);
            }
        }
        public static string GetDriveSerialNumber(string drive)
        {
            Encapsulation.TryValidateParam(drive, nameof(drive));

            var driveSerial = string.Empty;

            // No matter what is sent in, get just the drive letter
            var driveFixed = System.IO.Path.GetPathRoot(drive);

            driveFixed = driveFixed.Replace(@"\", string.Empty);

            // Perform Query
            using (ManagementObjectSearcher querySearch = new ManagementObjectSearcher(string.Format("SELECT VolumeSerialNumber FROM Win32_LogicalDisk Where Name = '{0}'", driveFixed)))
            {
                using (ManagementObjectCollection queryCollection = querySearch.Get())
                {
                    foreach (var moItem in queryCollection)
                    {
                        driveSerial = System.Convert.ToString(moItem.GetPropertyValue("VolumeSerialNumber"));
                        break;
                    }
                }
            }

            return(driveSerial);
        }
示例#7
0
        /// <summary>
        /// Loads the files.
        /// </summary>
        /// <param name="directories">The directories.</param>
        /// <param name="searchPattern">The search pattern.</param>
        /// <param name="searchOption">The search option.</param>
        /// <returns>IEnumerable(Of FileInfo).</returns>
        public static IEnumerable <FileInfo> LoadFiles(IEnumerable <DirectoryInfo> directories, string searchPattern, SearchOption searchOption)
        {
            Encapsulation.TryValidateParam(directories, nameof(directories));
            Encapsulation.TryValidateParam(searchPattern, nameof(searchPattern));
            Encapsulation.TryValidateParam(searchOption, nameof(searchOption));

            var files = new List <FileInfo>();

            var validDirectories = directories.Where(directory => directory.Exists).Select(directory => directory).ToList();

            validDirectories.ForEach(directory =>
            {
                try
                {
                    var directoryFiles = directory.EnumerateFiles(searchPattern, searchOption).ToArray();

                    if (directoryFiles.HasItems())
                    {
                        files.AddIfNotExists(directoryFiles);
                    }
                }
                catch (Exception ex) when(ex is DirectoryNotFoundException || ex is SecurityException)
                {
                    System.Diagnostics.Trace.WriteLine(ex.Message);
                }
            });

            return(files.AsEnumerable());
        }
示例#8
0
        public static IEnumerable <DirectoryInfo> SafeDirectorySearch(DirectoryInfo rootDirectory, string searchPattern = "*.*", SearchOption searchOption = SearchOption.TopDirectoryOnly)
        {
            Encapsulation.TryValidateParam(rootDirectory, nameof(rootDirectory));
            Encapsulation.TryValidateParam(searchPattern, nameof(searchPattern));

            var folders = new List <DirectoryInfo>
            {
                rootDirectory,
            };

            for (var directoryCount = 0; directoryCount < rootDirectory.GetDirectories(searchPattern, searchOption).Length; directoryCount++)
            {
                try
                {
                    var searchResult = SafeDirectorySearch(rootDirectory.GetDirectories(searchPattern, searchOption)[directoryCount], searchPattern);

                    if (searchResult.HasItems())
                    {
                        _ = folders.AddRange(searchResult, insureUnique: true);
                    }
                }
                catch (Exception ex) when(ex is ArgumentException || ex is ArgumentNullException || ex is ArgumentOutOfRangeException || ex is System.IO.DirectoryNotFoundException || ex is UnauthorizedAccessException)
                {
                    Trace.WriteLine(ex.Message);
                }
            }

            return(folders);
        }
示例#9
0
        public static IEnumerable <FileInfo> SafeFileSearch(IEnumerable <DirectoryInfo> directories, string searchPattern, SearchOption searchOption)
        {
            Encapsulation.TryValidateParam(directories, nameof(directories));
            Encapsulation.TryValidateParam(searchPattern, nameof(searchPattern));
            Encapsulation.TryValidateParam(searchOption, nameof(searchOption));

            var files = new List <FileInfo>();

            directories.ToList().ForEach(directory =>
            {
                try
                {
                    if (directory.Exists)
                    {
                        var directoryFiles = directory.EnumerateFiles(searchPattern, searchOption).ToArray();

                        if (directoryFiles.HasItems())
                        {
                            _ = files.AddIfNotExists(directoryFiles);
                        }
                    }
                }
                catch (Exception ex) when(ex is System.IO.DirectoryNotFoundException || ex is SecurityException || ex is UnauthorizedAccessException)
                {
                    Trace.WriteLine(ex.Message);
                }
            });

            return(files.AsEnumerable());
        }
        public static DirectoryInfo CombinePaths(bool createIfNotExists, string path1, string path2)
        {
            Encapsulation.TryValidateParam(path1, nameof(path1));
            Encapsulation.TryValidateParam(path2, nameof(path2));

            return(CombinePaths(createIfNotExists, path1, path2));
        }
        /// <summary>
        /// Groups the elements of a sequence according to a specified firstKey selector function and
        /// rotates the unique values from the secondKey selector function into multiple values in
        /// the output, and performs aggregations.
        /// </summary>
        /// <typeparam name="TSource">The type of the t source.</typeparam>
        /// <typeparam name="TFirstKey">The type of the t first key.</typeparam>
        /// <typeparam name="TSecondKey">The type of the t second key.</typeparam>
        /// <typeparam name="TValue">The type of the t value.</typeparam>
        /// <param name="source">The source.</param>
        /// <param name="firstKeySelector">The first key selector.</param>
        /// <param name="secondKeySelector">The second key selector.</param>
        /// <param name="aggregate">The aggregate.</param>
        /// <returns>Dictionary&lt;TFirstKey, Dictionary&lt;TSecondKey, TValue&gt;&gt;.</returns>
        /// <remarks>Original code by: Fons Sonnemans</remarks>
        public static Dictionary <TFirstKey, Dictionary <TSecondKey, TValue> > Pivot <TSource, TFirstKey, TSecondKey, TValue>(this IEnumerable <TSource> source, Func <TSource, TFirstKey> firstKeySelector, Func <TSource, TSecondKey> secondKeySelector, Func <IEnumerable <TSource>, TValue> aggregate)
        {
            Encapsulation.TryValidateParam <ArgumentNullException>(aggregate != null);
            Encapsulation.TryValidateParam <ArgumentNullException>(firstKeySelector != null);
            Encapsulation.TryValidateParam <ArgumentNullException>(secondKeySelector != null);

            var returnValue = new Dictionary <TFirstKey, Dictionary <TSecondKey, TValue> >();

            var lookup = source.ToLookup(firstKeySelector);

            foreach (var item in lookup.AsParallel())
            {
                var collection = new Dictionary <TSecondKey, TValue>();

                returnValue.Add(item.Key, collection);

                var secondLookup = item.ToLookup(secondKeySelector);

                foreach (var subitem in secondLookup.AsParallel())
                {
                    collection.Add(subitem.Key, aggregate(subitem));
                }
            }

            return(returnValue);
        }
        /// <summary>
        /// Safes the directory search.
        /// </summary>
        /// <param name="rootDirectory">The root directory.</param>
        /// <param name="searchPattern">The search pattern.</param>
        /// <returns>IEnumerable&lt;DirectoryInfo&gt;.</returns>
        public static IEnumerable <DirectoryInfo> SafeDirectorySearch(DirectoryInfo rootDirectory, string searchPattern = ControlChars.DoubleQuote)
        {
            Encapsulation.TryValidateParam(rootDirectory, nameof(rootDirectory));

            var folders = new List <DirectoryInfo>
            {
                rootDirectory
            };

            foreach (var topFolder in rootDirectory.GetDirectories(searchPattern, SearchOption.TopDirectoryOnly))
            {
                try
                {
                    foreach (var folder in SafeDirectorySearch(topFolder, searchPattern))
                    {
                        folders.Add(folder);
                    }
                }
                catch (UnauthorizedAccessException ex)
                {
                    System.Diagnostics.Trace.WriteLine(ex.Message);
                }
            }

            return(folders);
        }
        /// <summary>
        /// Deletes the file.
        /// </summary>
        /// <param name="files">The files.</param>
        /// <returns>IEnumerable&lt;KeyValuePair&lt;System.String, System.String&gt;&gt;.</returns>
        public static IEnumerable <(string FileName, string ErrorMessage)> DeleteFiles(this IEnumerable <string> files)
        {
            Encapsulation.TryValidateParam <ArgumentNullException>(files != null, nameof(files));

            var errors = new List <(string FileName, string ErrorMessage)>();

            var result = Parallel.ForEach(source: files, body: (fileName) =>
            {
                try
                {
                    File.Delete(fileName);
                }
                catch (Exception ex) when(ex is ArgumentException ||
                                          ex is ArgumentNullException ||
                                          ex is DirectoryNotFoundException ||
                                          ex is IOException ||
                                          ex is NotSupportedException ||
                                          ex is PathTooLongException ||
                                          ex is UnauthorizedAccessException)
                {
                    errors.Add((FileName: fileName, ErrorMessage: ex.GetAllMessages()));
                }
            });

            return(errors.AsEnumerable());
        }
        public static ImmutableDictionary <string, string> GetPropertyValues <T>(T input)
        {
            Encapsulation.TryValidateParam <ArgumentNullException>(input.IsNotNull(), nameof(input));

            var returnValue = new Dictionary <string, string>();

            var properties = input.GetType().GetAllProperties().Where(p => p.CanRead == true).ToArray();

            foreach (var propertyInfo in properties.OrderBy(p => p.Name))
            {
                if (propertyInfo.PropertyType.Name == "IDictionary")
                {
                    var propertyValue = propertyInfo.GetValue(input) as IDictionary;

                    if (propertyValue?.Count > 0)
                    {
                        returnValue.AddIfNotExists(new KeyValuePair <string, string>(propertyInfo.Name, propertyValue.ToDelimitedString()));
                    }
                }
                else
                {
                    // Get property value
                    var propertyValue = propertyInfo.GetValue(input);

                    if (propertyValue.IsNotNull())
                    {
                        returnValue.AddIfNotExists(propertyInfo.Name, propertyValue.ToString());
                    }
                }
            }

            return(returnValue.ToImmutableDictionary());
        }
示例#15
0
        /// <summary>
        /// Copies directory to a new location.
        /// </summary>
        /// <param name="sourceDirectory">The source directory.</param>
        /// <param name="destinationDirectory">The destination directory.</param>
        /// <param name="overwrite">if set to <c>true</c> [overwrite].</param>
        public static void CopyDirectory(string sourceDirectory, string destinationDirectory, bool overwrite = true)
        {
            Encapsulation.TryValidateParam(sourceDirectory, nameof(sourceDirectory));
            Encapsulation.TryValidateParam(destinationDirectory, nameof(destinationDirectory));

            var directory = new DirectoryInfo(sourceDirectory);

            var directiories = directory.GetDirectories();

            if (Directory.Exists(destinationDirectory) == false)
            {
                Directory.CreateDirectory(destinationDirectory);
            }

            var files = directory.GetFiles();

            for (int i = 0; i < files.Length; i++)
            {
                var file = files[i];

                file.CopyTo(Path.Combine(destinationDirectory, file.Name), overwrite);
            }

            for (int i = 0; i < directiories.Length; i++)
            {
                var subDirectory = directiories[i];

                CopyDirectory(subDirectory.FullName, Path.Combine(destinationDirectory, subDirectory.Name), overwrite);
            }
        }
示例#16
0
        /// <summary>
        /// Determines whether the <see cref="ConcurrentHashSet{T}" /> contains the specified
        /// item.
        /// </summary>
        /// <param name="item">The item to locate in the <see cref="ConcurrentHashSet{T}" />.</param>
        /// <returns>true if the <see cref="ConcurrentHashSet{T}" /> contains the item; otherwise, false.</returns>
        public bool Contains(T item)
        {
            Encapsulation.TryValidateParam <ArgumentNullException>(item != null, nameof(item));

            var hashcode = this._comparer.GetHashCode(item);

            // We must capture the _buckets field in a local variable. It is set to a new table on each table resize.
            var tables = this._tables;

            var bucketNo = GetBucket(hashcode, tables._buckets.Length);

            // We can get away w/out a lock here.
            // The Volatile.Read ensures that the load of the fields of 'n' doesn't move before the load from buckets[i].
            var current = Volatile.Read(ref tables._buckets[bucketNo]);

            while (current != null)
            {
                if (hashcode == current._hashCode && this._comparer.Equals(current._item, item))
                {
                    return(true);
                }

                current = current._next;
            }

            return(false);
        }
示例#17
0
        /// <summary>
        /// Copies a file to a new directory as an asynchronous operation.
        /// </summary>
        /// <param name="file">The file.</param>
        /// <param name="destinationFolder">The destination folder.</param>
        /// <returns>Task&lt;System.Int32&gt;.</returns>
        public static async Task <long> CopyFileAsync(FileInfo file, DirectoryInfo destinationFolder)
        {
            Encapsulation.TryValidateParam(file, nameof(file));
            Encapsulation.TryValidateParam(destinationFolder, nameof(destinationFolder));

            var newFileName = Path.Combine(destinationFolder.FullName, file.Name);

            using (var sourceStream = File.Open(file.FullName, FileMode.Open))
            {
                if (File.Exists(newFileName))
                {
                    File.Delete(newFileName);
                }

                using (var destinationStream = File.Create(newFileName))
                {
                    await sourceStream.CopyToAsync(destinationStream).ConfigureAwait(true);

                    await destinationStream.FlushAsync().ConfigureAwait(true);

                    destinationStream.Close();
                }
            }

            return(file.Length);
        }
示例#18
0
        /// <summary>
        /// Copies the elements of the <see cref="T:System.Collections.Generic.ICollection`1"></see> to an <see cref="T:System.Array"></see>, starting at a particular <see cref="T:System.Array"></see> index.
        /// </summary>
        /// <param name="array">The one-dimensional <see cref="T:System.Array"></see> that is the destination of the elements copied from <see cref="T:System.Collections.Generic.ICollection`1"></see>. The <see cref="T:System.Array"></see> must have zero-based indexing.</param>
        /// <param name="arrayIndex">The zero-based index in array at which copying begins.</param>
        /// <exception cref="ArgumentException">The index is equal to or greater than the length of the array, or the number of elements in the set is greater than the available space from index to the end of the destination array.</exception>
        /// <exception cref="System.ArgumentException">The index is equal to or greater than the length of the array, or the number of elements in the set is greater than the available space from index to the end of the destination array.</exception>
        /// <exception cref="ArgumentNullException">The index is equal to or greater than the length of the array, or the number of elements in the set is greater than the available space from index to the end of the destination array.</exception>
        /// <exception cref="ArgumentOutOfRangeException">The index is equal to or greater than the length of the array, or the number of elements in the set is greater than the available space from index to the end of the destination array.</exception>
        void ICollection <T> .CopyTo(T[] array, int arrayIndex)
        {
            Encapsulation.TryValidateParam(array, nameof(array));
            Encapsulation.TryValidateParam <ArgumentOutOfRangeException>(arrayIndex < 0, nameof(arrayIndex));

            var locksAcquired = 0;

            try
            {
                this.AcquireAllLocks(ref locksAcquired);

                var count = 0;

                for (var i = 0; i < this._tables._locks.Length && count >= 0; i++)
                {
                    count += this._tables._countPerLock[i];
                }

                // "count" itself or "count + arrayIndex" can overflow
                if (array.Length - count < arrayIndex || count < 0)
                {
                    throw new ArgumentException("The index is equal to or greater than the length of the array, or the number of elements in the set is greater than the available space from index to the end of the destination array.");
                }

                this.CopyToItems(array, arrayIndex);
            }
            finally
            {
                this.ReleaseLocks(0, locksAcquired);
            }
        }
        /// <summary>
        /// Gets the registry key value.
        /// </summary>
        /// <typeparam name="T">The type of T.</typeparam>
        /// <param name="key">The key.</param>
        /// <param name="name">The name.</param>
        /// <returns>T.</returns>
        /// <exception cref="PlatformNotSupportedException">The exception.</exception>
        public static T GetValue <T>(this RegistryKey key, string name)
        {
            Encapsulation.TryValidateParam <ArgumentNullException>(key != null, nameof(key));
            Encapsulation.TryValidateParam(name, nameof(name));

#pragma warning disable CS8653 // A default expression introduces a null value for a type parameter.
            var returnValue = default(T);
#pragma warning restore CS8653 // A default expression introduces a null value for a type parameter.

            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
#pragma warning disable CS8602 // Dereference of a possibly null reference.
                var keyValue = key.GetValue(name);
#pragma warning restore CS8602 // Dereference of a possibly null reference.

                if (keyValue != null)
                {
                    returnValue = (T)keyValue;
                }

#pragma warning disable CS8603 // Possible null reference return.
                return(returnValue);

#pragma warning restore CS8603 // Possible null reference return.
            }
            else
            {
                throw new PlatformNotSupportedException();
            }
        }
示例#20
0
        /// <summary>
        /// Progressive retry for a function call.
        /// </summary>
        /// <param name="operation">The operation to perform.</param>
        /// <param name="retryCount">The retry count (default 3).</param>
        /// <param name="retryWaitMilliseconds">The retry wait milliseconds (default 100).</param>
        /// <returns>System.Int32.</returns>
        public static int ProgressiveRetry(Action operation, byte retryCount = 3, int retryWaitMilliseconds = 100)
        {
            Encapsulation.TryValidateParam <ArgumentNullException>(operation != null);
            Encapsulation.TryValidateParam <ArgumentOutOfRangeException>(retryCount > 0);
            Encapsulation.TryValidateParam <ArgumentOutOfRangeException>(retryWaitMilliseconds > 0);

            var attempts = 0;

            do
            {
                try
                {
                    attempts++;

                    operation();

                    return(attempts);
                }
                catch (Exception ex)
                {
                    if (attempts == retryCount)
                    {
                        throw;
                    }

                    Debug.WriteLine(ex.GetAllMessages());

                    Task.Delay(retryWaitMilliseconds * attempts).Wait();
                }
            } while (true);
        }
        /// <summary>
        /// Decrypts array to string using Rijndael security.
        /// </summary>
        /// <param name="cipherText">The cipher text.</param>
        /// <param name="key">The secret key.</param>
        /// <param name="iv">The initialization vector.</param>
        /// <returns>System.String.</returns>
        public static string RijndaelDecrypt(byte[] cipherText, byte[] key, byte[] iv)
        {
            Encapsulation.TryValidateParam(cipherText, nameof(cipherText));
            Encapsulation.TryValidateParam(key, nameof(key));
            Encapsulation.TryValidateParam(key, nameof(iv));

            string text = null;

            // Create RijndaelManaged
            using (var aes = new RijndaelManaged())
            {
                // Create a decryptor
                using (var decryptor = aes.CreateDecryptor(key, iv))
                {
                    // Create the streams used for decryption.
                    using (var ms = new MemoryStream(cipherText))
                    {
                        // Create crypto stream
                        using (var cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read))
                        {
                            // Read crypto stream
                            using (var reader = new StreamReader(cs))
                            {
                                text = reader.ReadToEnd();
                            }
                        }
                    }
                }
            }

            return(text);
        }
        /// <summary>
        /// Copies a file as an asynchronous operation.
        /// </summary>
        /// <param name="file">The file.</param>
        /// <param name="destinationFolder">The destination folder.</param>
        /// <returns>Task&lt;System.Int32&gt;.</returns>
        public static async Task <long> CopyFileAsync(FileInfo file, DirectoryInfo destinationFolder)
        {
            Encapsulation.TryValidateParam(file, nameof(file));
            Encapsulation.TryValidateParam(destinationFolder, nameof(destinationFolder));

            var backUpFolderRoot = destinationFolder.FullName.Split(ControlChars.BackSlash).Last().Trim();

            var newFileName = file.FullName.Replace(destinationFolder.FullName, backUpFolderRoot);

            using (var sourceStream = File.Open(file.FullName, FileMode.Open))
            {
                if (File.Exists(newFileName))
                {
                    File.Delete(newFileName);
                }

                using (var destinationStream = File.Create(newFileName))
                {
                    await sourceStream.CopyToAsync(destinationStream);

                    await destinationStream.FlushAsync();
                }
            }

            return(file.Length);
        }
示例#23
0
        /// <summary>
        /// Finds the derived types.
        /// </summary>
        /// <param name="currentDomain">The current domain.</param>
        /// <param name="baseType">Type of the base.</param>
        /// <param name="classOnly">if set to <c>true</c> [class only].</param>
        /// <returns>IEnumerable&lt;Type&gt;.</returns>
        public static IEnumerable <Type> FindDerivedTypes(AppDomain currentDomain, Type baseType, bool classOnly)
        {
            Encapsulation.TryValidateParam <ArgumentNullException>(currentDomain != null, nameof(currentDomain));

            Encapsulation.TryValidateParam <ArgumentNullException>(baseType != null, nameof(baseType));

            List <Type> types = null;

            foreach (var assembly in currentDomain.GetAssemblies().AsParallel())
            {
                var tempTypes = LoadDerivedTypes(assembly.DefinedTypes, baseType, classOnly).ToList();

                if (tempTypes.Count() > 0)
                {
                    if (types == null)
                    {
                        types = tempTypes;
                    }
                    else
                    {
                        types.AddRange(tempTypes);
                    }
                }
            }

            return(types);
        }
示例#24
0
        /// <summary>
        /// Finds the derived types.
        /// </summary>
        /// <param name="path">The path.</param>
        /// <param name="searchOption">The search option.</param>
        /// <param name="baseType">Type of the base.</param>
        /// <param name="classOnly">if set to <c>true</c> [class only].</param>
        /// <returns>IEnumerable&lt;Type&gt;.</returns>
        /// <exception cref="dotNetTips.Utility.Standard.DirectoryNotFoundException">Could not find path.</exception>
        /// <exception cref="System.IO.DirectoryNotFoundException">Could not find path.</exception>
        /// <exception cref="ArgumentNullException">Could not find path.</exception>
        public static IEnumerable <Type> FindDerivedTypes(string path, SearchOption searchOption, Type baseType, bool classOnly)
        {
            Encapsulation.TryValidateParam(path, nameof(path), "Must pass in path and file name to the assembly.");

            Encapsulation.TryValidateParam <ArgumentNullException>(baseType != null, nameof(baseType), "Parent Type must be defined");

            var foundTypes = new List <Type>();

            if (Directory.Exists(path) == false)
            {
                throw new DirectoryNotFoundException("Could not find path.", path);
            }

            var files = Directory.EnumerateFiles(path, "*.dll", searchOption);

            foreach (var file in files)
            {
                var assy = Assembly.LoadFile(file);

                var containsBaseType = assy.ExportedTypes.Any(p => (p.BaseType != null &&
                                                                    p.BaseType.FullName == baseType.FullName));

                if (containsBaseType)
                {
                    foundTypes.AddRange(LoadDerivedTypes(assy.DefinedTypes, baseType, classOnly));
                }
            }

            return(foundTypes);
        }
        /// <summary>
        /// Finds the derived types.
        /// </summary>
        /// <param name="currentDomain">The current domain.</param>
        /// <param name="baseType">Type of the base.</param>
        /// <param name="classOnly">if set to <c>true</c> [class only].</param>
        /// <returns>IEnumerable&lt;Type&gt;.</returns>
        public static IEnumerable <Type> FindDerivedTypes(AppDomain currentDomain, Type baseType, bool classOnly)
        {
            Encapsulation.TryValidateParam <ArgumentNullException>(currentDomain != null, nameof(currentDomain));
            Encapsulation.TryValidateParam <ArgumentNullException>(baseType != null, nameof(baseType));

            List <Type> types = null;

            var array = currentDomain.GetAssemblies();

            for (var assemblyCount = 0; assemblyCount < array.Length; assemblyCount++)
            {
                var assembly  = array[assemblyCount];
                var tempTypes = LoadDerivedTypes(assembly.DefinedTypes, baseType, classOnly).ToList();

                if (tempTypes.HasItems())
                {
                    if (types == null)
                    {
                        types = tempTypes;
                    }
                    else
                    {
                        types.AddRange(tempTypes);
                    }
                }
            }

            return(types);
        }
        /// <summary>
        /// Finds the derived types.
        /// </summary>
        /// <param name="path">The path.</param>
        /// <param name="searchOption">The search option.</param>
        /// <param name="baseType">Type of the base.</param>
        /// <param name="classOnly">if set to <c>true</c> [class only].</param>
        /// <returns>IEnumerable&lt;Type&gt;.</returns>
        /// <exception cref="dotNetTips.Utility.Standard.Common.DirectoryNotFoundException">Could not find path.</exception>
        /// <exception cref="ArgumentNullException">Could not find path.</exception>
        public static IEnumerable <Type> FindDerivedTypes(string path, SearchOption searchOption, Type baseType, bool classOnly)
        {
            Encapsulation.TryValidateParam(path, nameof(path), "Must pass in path and file name to the assembly.");
            Encapsulation.TryValidateParam <ArgumentNullException>(baseType != null, nameof(baseType), "Parent Type must be defined");

            var foundTypes = new List <Type>();

            if (Directory.Exists(path) == false)
            {
                throw new dotNetTips.Utility.Standard.Common.DirectoryNotFoundException("Could not find path.", path);
            }

            var files = Directory.EnumerateFiles(path, "*.dll", searchOption);

            var list = files.ToList();

            for (var i = 0; i < list.Count; i++)
            {
                string file = list[i];
                var    assy = Assembly.LoadFile(file);

                var containsBaseType = assy.ExportedTypes.ToList().TrueForAll(p => p.BaseType != null &&
                                                                              p.BaseType.FullName == baseType.FullName);

                if (containsBaseType)
                {
                    foundTypes.AddRange(LoadDerivedTypes(assy.DefinedTypes, baseType, classOnly));
                }
            }

            return(foundTypes);
        }
        /// <summary>
        /// Orders a list based on a sort expression. Useful in object data binding scenarios where
        /// the ObjectDataSource generates a dynamic sortexpression (example: "Name desc") that
        /// specifies the property of the object sort on.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="list">The list.</param>
        /// <param name="sortExpression">The sort expression.</param>
        /// <returns>IEnumerable&lt;T&gt;.</returns>
        /// <exception cref="ArgumentNullException">sortExpression - Sort expression cannot be null.</exception>
        /// <exception cref="InvalidCastException"></exception>
        /// <exception cref="System.InvalidCastException"></exception>
        /// <remarks>Code by: C.F.Meijers</remarks>
        public static IEnumerable <T> OrderBy <T>(this IEnumerable <T> list, string sortExpression)
        {
            Encapsulation.TryValidateParam(sortExpression);

            sortExpression += string.Empty;
            var parts      = sortExpression.Split(ControlChars.Space);
            var descending = false;
            var property   = string.Empty;

            if (parts.Length > 0 && !string.IsNullOrEmpty(parts[0]))
            {
                property = parts[0];

                if (parts.Length > 1)
                {
                    @descending = CultureInfo.InvariantCulture.TextInfo.ToLower(parts[1]).Contains("esc");
                }

                var prop = typeof(T).GetRuntimeProperty(property);

                if (prop == null)
                {
                    throw new InvalidCastException(string.Format(CultureInfo.InvariantCulture, "{0}' in + {1}'", string.Format(CultureInfo.InvariantCulture, "{0}{1}", Convert.ToString("No property '", CultureInfo.InvariantCulture), property), typeof(T).Name));
                }

                return(@descending ? list.OrderByDescending(x => prop.GetValue(x, null)) : list.OrderBy(x => prop.GetValue(x, null)));
            }

            return(list);
        }
        /// <summary>
        /// Groups the elements of a sequence according to a specified firstKey selector function and
        /// rotates the unique values from the secondKey selector function into multiple values in
        /// the output, and performs aggregations.
        /// </summary>
        /// <typeparam name="TSource">The type of the t list.</typeparam>
        /// <typeparam name="TFirstKey">The type of the t first key.</typeparam>
        /// <typeparam name="TSecondKey">The type of the t second key.</typeparam>
        /// <typeparam name="TValue">The type of the t value.</typeparam>
        /// <param name="source">The list.</param>
        /// <param name="firstKeySelector">The first key selector.</param>
        /// <param name="secondKeySelector">The second key selector.</param>
        /// <param name="aggregate">The aggregate.</param>
        /// <returns>Dictionary&lt;TFirstKey, Dictionary&lt;TSecondKey, TValue&gt;&gt;.</returns>
        /// <exception cref="ArgumentNullException">
        /// list - Source cannot be null or have a 0 value.
        /// or
        /// list - Aggregate cannot be null.
        /// or
        /// firstKeySelector - First key selector cannot be null.
        /// or
        /// secondKeySelector - Second key selector cannot be null.
        /// </exception>
        /// <remarks>Original code by: Fons Sonnemans</remarks>
        public static Dictionary <TFirstKey, Dictionary <TSecondKey, TValue> > Pivot <TSource, TFirstKey, TSecondKey, TValue>(this IEnumerable <TSource> list, Func <TSource, TFirstKey> firstKeySelector, Func <TSource, TSecondKey> secondKeySelector, Func <IEnumerable <TSource>, TValue> aggregate)
        {
            Encapsulation.TryValidateParam <ArgumentNullException>(aggregate == null, "Aggregate cannot be null.");
            Encapsulation.TryValidateParam <ArgumentNullException>(firstKeySelector == null, "First key selector cannot be null.");
            Encapsulation.TryValidateParam <ArgumentNullException>(secondKeySelector == null, "Second key selector cannot be null.");

            var returnValue = new Dictionary <TFirstKey, Dictionary <TSecondKey, TValue> >();

            var lookup = list.ToLookup(firstKeySelector);

            foreach (var item in lookup)
            {
                var collection = new Dictionary <TSecondKey, TValue>();

                returnValue.Add(item.Key, collection);

                var secondLookup = item.ToLookup(secondKeySelector);

                foreach (var subitem in secondLookup)
                {
                    collection.Add(subitem.Key, aggregate.Invoke(subitem));
                }
            }

            return(returnValue);
        }
示例#29
0
        /// <summary>
        /// Gets the last.
        /// </summary>
        /// <param name="input">The date/ time.</param>
        /// <param name="dayOfWeek">The day of week.</param>
        /// <returns>DateTime.</returns>
        /// <exception cref="ArgumentNullException">input - Input is invalid.</exception>
        public static DateTime GetLast(this DateTime input, DayOfWeek dayOfWeek)
        {
            Encapsulation.TryValidateParam(dayOfWeek, nameof(dayOfWeek));

            var daysToSubtract = input.DayOfWeek > dayOfWeek ? input.DayOfWeek - dayOfWeek : (7 - (int)dayOfWeek) + (int)input.DayOfWeek;

            return(input.AddDays(daysToSubtract * -1));
        }
示例#30
0
        /// <summary>
        /// Return maximum type. Works with value and reference types.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj1">The obj1.</param>
        /// <param name="obj2">The obj2.</param>
        /// <returns>T.</returns>
        /// <remarks>Original code by: Jeremy Clark</remarks>
        public static T Max <T>(this T obj1, T obj2)
            where T : IComparable
        {
            Encapsulation.TryValidateParam <ArgumentNullException>(obj1 != null);
            Encapsulation.TryValidateParam <ArgumentNullException>(obj2 != null);

            return(obj1.CompareTo(obj2) >= 0 ? obj1 : obj2);
        }