예제 #1
0
        /// <summary>
        /// Uses a <see cref="IDbCommand" /> to retrieve a scalar value using the given <paramref name="commandText" />.
        /// </summary>
        /// <typeparam name="TResult">The type of the expected result.</typeparam>
        /// <param name="commandText">The command text to execute.</param>
        /// <param name="connection">The connection to use for the query.</param>
        /// <param name="commandTimeout">The command timeout in seconds.</param>
        /// <returns>The result or the default value of <typeparamref name="TResult" /> if an error occurs.</returns>
        /// <exception cref="ArgumentException">
        /// Is thrown if the <paramref name="commandText" /> or <paramref name="connection" /> are invalid.
        /// </exception>
        public static async Task <TResult> GetScalarResultAsync <TResult>(string commandText, IDbConnection connection, int commandTimeout = 30)
        {
            CheckUtil.ThrowIfNull(() => connection);
            CheckUtil.ThrowIfNullOrEmpty(() => commandText);
            try
            {
                using (var command = connection.CreateCommand())
                {
                    command.CommandTimeout = commandTimeout;
                    var commandToUse = command as DbCommand;
                    CheckUtil.ThrowIfNull(() => commandToUse);
                    // ReSharper disable once PossibleNullReferenceException
                    commandToUse.CommandText = commandText;
                    var result = await commandToUse.ExecuteScalarAsync();

                    if (result == null)
                    {
                        return(default(TResult));
                    }
                    return((TResult)result);
                }
            }
            catch (Exception ex)
            {
                ExceptionCallback?.Invoke(ex);
                return(default(TResult));
            }
        }
예제 #2
0
        /// <summary>
        /// Retrieves a DateTime for the given <paramref name="columnName" />.
        /// </summary>
        /// <param name="reader">The reader to extend.</param>
        /// <param name="columnName">The name of the column in the reader result.</param>
        /// <returns>The value.</returns>
        public static DateTime?GetDateTimeValue(this IDataReader reader, string columnName)
        {
            CheckUtil.ThrowIfNull(() => reader);
            CheckUtil.ThrowIfNullOrEmpty(() => columnName);
            var offset = GetColumnOffset(reader, columnName);

            return(reader.IsDBNull(offset) ? default(DateTime?) : reader.GetDateTime(offset));
        }
예제 #3
0
        /// <summary>
        /// Retrieves a value from a reader.
        /// </summary>
        /// <typeparam name="TResult">The expected result.</typeparam>
        /// <param name="reader">The reader to extend.</param>
        /// <param name="columnName">The name of the column in the reader result.</param>
        /// <returns>The value of the column.</returns>
        public static TResult GetValue <TResult>(this IDataReader reader, string columnName)
        {
            CheckUtil.ThrowIfNull(() => reader);
            CheckUtil.ThrowIfNullOrEmpty(() => columnName);
            var offset = GetColumnOffset(reader, columnName);
            var value  = reader.GetValue(offset);

            return((TResult)value);
        }
예제 #4
0
 /// <summary>
 /// Retrieves the offset of a column with the specified <paramref name="columnName" />.
 /// </summary>
 /// <param name="reader">The reader to extend.</param>
 /// <param name="columnName">The name of the column in the reader result.</param>
 /// <returns>The index of the column.</returns>
 public static int GetColumnOffset(this IDataReader reader, string columnName)
 {
     CheckUtil.ThrowIfNull(() => reader);
     CheckUtil.ThrowIfNullOrEmpty(() => columnName);
     if (reader.IsClosed)
     {
         throw new InvalidOperationException("Reader is closed");
     }
     return(reader.GetOrdinal(columnName));
 }
예제 #5
0
        /// <summary>
        /// Iterates through a list of T and retrieves the index of the element matching the <paramref name="compareFunc" /> inside
        /// the enumerable.
        /// </summary>
        /// <typeparam name="T">The type of an element inside the <paramref name="enumerable" />.</typeparam>
        /// <param name="enumerable">The enumerable to extend.</param>
        /// <param name="compareFunc">The element to find.</param>
        /// <returns>The offset of the element or -1 if the element wasn't found in the enumerable.</returns>
        public static int GetIndexOf <T>(this IEnumerable <T> enumerable, Func <T, bool> compareFunc)
        {
            var enumerableToUse = enumerable as T[] ?? enumerable.ToArray();

            CheckUtil.ThrowIfNull(() => enumerableToUse);
            for (var i = 0; i < enumerableToUse.Count(); i++)
            {
                if (compareFunc(enumerableToUse[i]))
                {
                    return(i);
                }
            }
            return(-1);
        }
예제 #6
0
        /// <summary>
        /// Gets the value for a given <paramref name="secureValue"/>.
        /// </summary>
        /// <param name="secureValue">The secured text.</param>
        /// <returns>The readable text.</returns>
        public static string ToUnsecureString(this SecureString secureValue)
        {
            CheckUtil.ThrowIfNull(() => secureValue);
            var unmanagedString = IntPtr.Zero;

            try
            {
                unmanagedString = Marshal.SecureStringToGlobalAllocUnicode(secureValue);
                return(Marshal.PtrToStringUni(unmanagedString));
            }
            finally
            {
                Marshal.ZeroFreeGlobalAllocUnicode(unmanagedString);
            }
        }
예제 #7
0
        /// <summary>
        /// Retrieves the result asynchronously.
        /// </summary>
        /// <param name="ctx">The entity context to use.</param>
        /// <param name="cancellationToken">A token for cancelling the opertation.</param>
        /// <param name="query">An optional query on the entities to use (if <c>null</c>, GetValidEntities is used).</param>
        /// <param name="filter">An optional filter expression.</param>
        public async Task GenerateAsync(TContext ctx, CancellationToken cancellationToken, IQueryable <TEntity> query = null, Expression <Func <TEntity, bool> > filter = null)
        {
            if (query == null)
            {
                CheckUtil.ThrowIfNull(() => Util);
                query = Util.GetValidEntities(ctx, filter);
            }
            CompleteItemsCount = await query.CountAsync(cancellationToken);

            if (Request.OrderByExpressions != null && Request.OrderByExpressions.Any())
            {
                // we habe to cycle through each desired order-expression and build up our query-
                var firstItem = true;
                foreach (var orderBy in Request.OrderByExpressions)
                {
                    if (firstItem)
                    {
                        // this is the first item so that ThenBy can not be applied
                        query     = orderBy.OrderDirection == OrderByDirections.Ascending ? query.OrderBy(orderBy.PropertyName) : query.OrderByDescending(orderBy.PropertyName);
                        firstItem = false;
                    }
                    else
                    {
                        // this is not the first item so that each order has to be done using Then*
                        var ordered = query as IOrderedQueryable <TEntity>;
                        if (ordered == null)
                        {
                            throw new InvalidOperationException("Could not retrieve ordered elements from previous iteration.");
                        }
                        query = orderBy.OrderDirection == OrderByDirections.Ascending ? ordered.ThenBy(orderBy.PropertyName) : ordered.ThenByDescending(orderBy.PropertyName);
                    }
                }
            }
            else
            {
                // order by Id if no other order is defined
                query = query.OrderBy(e => e.Id);
            }
            // generate and return the result
            var itemsToSkip = Request.EntriesToSkip ?? (Request.PageToDeliver - 1) * Request.ItemsPerPage;

            Items = await query.Skip(itemsToSkip).Take(Request.ItemsPerPage).ToListAsync(cancellationToken);
        }
예제 #8
0
        /// <summary>
        /// Uploads a single image to an Azure blob.
        /// </summary>
        /// <param name="container">The storage container to use.</param>
        /// <param name="image">The image to upload,</param>
        /// <param name="remoteFileName">The name the file should have in the storage container.</param>
        /// <param name="remoteFolder">A folder name to use or create in the storage container.</param>
        /// <returns><c>true</c> if the upload succeeds otherwise <c>false</c>.</returns>
        public static async Task <bool> UploadImageAsync(CloudBlobContainer container, Image image, string remoteFileName, string remoteFolder = null)
        {
            var name = remoteFileName;

            CheckUtil.ThrowIfNullOrEmpty(() => name);
            CheckUtil.ThrowIfNull(() => image);
            if (!remoteFolder.IsNullOrEmpty())
            {
                // ReSharper disable once AssignNullToNotNullAttribute
                remoteFileName = Path.Combine(remoteFolder, remoteFileName);
            }
            var newBlob = container.GetBlockBlobReference(remoteFileName);

            newBlob.Properties.ContentType = image.GetMimeContentType();
            var bytes = image.GetByteArrayFromImage(image.RawFormat);
            await newBlob.UploadFromByteArrayAsync(bytes, 0, bytes.Length);

            return(true);
        }
예제 #9
0
 /// <summary>
 /// Sends a RFC conform email using default .NET classes.
 /// </summary>
 /// <param name="messageToSend">The pre-configured <see cref="MailMessage" /> to send.</param>
 /// <param name="settings">A structure containing the settings for the server.</param>
 /// <returns><c>True</c> if the mail was sent, otherwise <c>false</c>.</returns>
 public static async Task <bool> SendMailAsync(MailMessage messageToSend, MailServerSettings settings)
 {
     CheckUtil.ThrowIfNull(() => messageToSend);
     try
     {
         // Send the mail and use credentials if given.
         using (var client = new SmtpClient(settings.ServerAddress, settings.Port))
         {
             if (settings.UseDefaultCredentials)
             {
                 client.Credentials = CredentialCache.DefaultNetworkCredentials;
             }
             else
             {
                 if (!string.IsNullOrEmpty(settings.Username) && !string.IsNullOrEmpty(settings.Password))
                 {
                     client.Credentials = new NetworkCredential(settings.Username, settings.Password, settings.Domain ?? string.Empty);
                 }
             }
             await client.SendMailAsync(messageToSend);
         }
         return(true);
     }
     catch (Exception ex)
     {
         var error = string.Format(
             CultureInfo.InvariantCulture,
             "Cannot send e-mail from '{0}' to '{1}' with subject '{2}': {3}",
             messageToSend.From,
             messageToSend.To,
             messageToSend.Subject,
             ex);
         var file = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonDocuments), "mail.error");
         using (var writer = File.AppendText(file))
         {
             writer.Write(error);
             writer.Close();
         }
         throw new InvalidOperationException(error, ex);
     }
 }
예제 #10
0
        /// <summary>
        /// Searches for an app setting with the provided <paramref name="key"/> from the calling configuration and returns its value converted to <typeparamref name="T"/>.
        /// </summary>
        /// <remarks>
        /// This method will throw exceptions on any failure.
        /// </remarks>
        /// <param name="key">The unique key out of the app-settings.</param>
        /// <typeparam name="T">Target type which has to be an <see cref="IConvertible"/>.</typeparam>
        /// <returns>The value of type <typeparamref name="T"/> if one could be obtained.</returns>
        public static T Get <T>(string key) where T : IConvertible
        {
            CheckUtil.ThrowIfNull(() => key);
            var value = AppSettings[key];

            if (value == null)
            {
                var error = string.Format(CultureInfo.InvariantCulture, "Cannot find key '{0}' in config-file.", key);
                throw new KeyNotFoundException(error);
            }
            try
            {
                var result = (T)Convert.ChangeType(value, typeof(T), CultureInfo.CurrentCulture);
                return(result);
            }
            catch (Exception ex)
            {
                var error = string.Format(CultureInfo.InvariantCulture, "Cannot convert '{0}' to type '{1}': {2}", value, typeof(T), ex);
                throw new InvalidOperationException(error, ex);
            }
        }
예제 #11
0
 /// <summary>
 /// Retrieves a reader for a given <paramref name="commandText" /> on the <paramref name="connection" />.
 /// </summary>
 /// <param name="commandText">The command text to execute.</param>
 /// <param name="connection">The connection to use for the query.</param>
 /// <param name="behavior">The command beavior for the reader.</param>
 /// <param name="commandTimeout">The command timeout in seconds.</param>
 /// <returns>The reader or <c>null</c> if an error occurs.</returns>
 /// <exception cref="ArgumentException">
 /// Is thrown if the <paramref name="commandText" /> or <paramref name="connection" /> are invalid.
 /// </exception>
 public static async Task <IDataReader> GetReaderAsync(string commandText, IDbConnection connection, CommandBehavior behavior = CommandBehavior.CloseConnection, int commandTimeout = 30)
 {
     CheckUtil.ThrowIfNull(() => connection);
     CheckUtil.ThrowIfNullOrEmpty(() => commandText);
     try
     {
         using (var command = connection.CreateCommand())
         {
             command.CommandTimeout = commandTimeout;
             var commandToUse = command as DbCommand;
             CheckUtil.ThrowIfNull(() => commandToUse);
             // ReSharper disable once PossibleNullReferenceException
             commandToUse.CommandText = commandText;
             return(await commandToUse.ExecuteReaderAsync(behavior));
         }
     }
     catch (Exception ex)
     {
         ExceptionCallback?.Invoke(ex);
         return(null);
     }
 }
예제 #12
0
        /// <summary>
        /// Encrypts a given <paramref name="plainText"/> symetrically using <see cref="RijndaelManaged"/>.
        /// </summary>
        /// <param name="plainText">The plain text.</param>
        /// <param name="key">The secret key.</param>
        /// <param name="iv">The initialization vector of the alogrithm.</param>
        /// <returns>The encrypted text coded in Base64.</returns>
        public static string EncryptText(string plainText, byte[] key, byte[] iv)
        {
            CheckUtil.ThrowIfNullOrEmpty(() => plainText);
            CheckUtil.ThrowIfNull(() => key);
            CheckUtil.ThrowIfNull(() => iv);
            string encrypted;

            using (var rijndael = new RijndaelManaged())
            {
                rijndael.Key = key;
                rijndael.IV  = iv;
                var encryptor   = rijndael.CreateEncryptor(rijndael.Key, rijndael.IV);
                var memStream   = new MemoryStream();
                var cryptStream = new CryptoStream(memStream, encryptor, CryptoStreamMode.Write);
                using (var writer = new StreamWriter(cryptStream))
                {
                    writer.Write(plainText);
                }
                encrypted = Convert.ToBase64String(memStream.ToArray());
            }
            return(encrypted);
        }
예제 #13
0
        /// <summary>
        /// Decrypts a given <paramref name="cipherText"/> symetrically using <see cref="RijndaelManaged"/>.
        /// </summary>
        /// <param name="cipherText">The encrypted Base64-encoded text.</param>
        /// <param name="key">The secret key.</param>
        /// <param name="iv">The initialization vector of the alogrithm.</param>
        /// <returns>The decrypted text.</returns>
        public static string DecryptText(string cipherText, byte[] key, byte[] iv)
        {
            CheckUtil.ThrowIfNullOrEmpty(() => cipherText);
            CheckUtil.ThrowIfNull(() => key);
            CheckUtil.ThrowIfNull(() => iv);
            string plaintext;

            using (var rijndael = new RijndaelManaged())
            {
                rijndael.Key = key;
                rijndael.IV  = iv;
                var decryptor       = rijndael.CreateDecryptor(rijndael.Key, rijndael.IV);
                var cipherTextBytes = Convert.FromBase64String(cipherText);
                var memStream       = new MemoryStream(cipherTextBytes);
                var cryptStream     = new CryptoStream(memStream, decryptor, CryptoStreamMode.Read);
                using (var reader = new StreamReader(cryptStream))
                {
                    plaintext = reader.ReadToEnd();
                }
            }
            return(plaintext);
        }
예제 #14
0
 /// <summary>
 /// Executes a given <paramref name="commandText" /> on the <paramref name="connection" />.
 /// </summary>
 /// <param name="commandText">The command text to execute.</param>
 /// <param name="connection">The connection to use for the query.</param>
 /// <param name="commandTimeout">The command timeout in seconds.</param>
 /// <returns>The amount of affected rows or -1 if an error occured.</returns>
 /// <exception cref="ArgumentException">
 /// Is thrown if the <paramref name="commandText" /> or <paramref name="connection" /> are invalid.
 /// </exception>
 public static async Task <int> ExecuteCommandAsync(string commandText, IDbConnection connection, int commandTimeout = 30)
 {
     CheckUtil.ThrowIfNull(() => connection);
     CheckUtil.ThrowIfNullOrEmpty(() => commandText);
     try
     {
         using (var command = connection.CreateCommand())
         {
             command.CommandTimeout = commandTimeout;
             var commandToUse = command as DbCommand;
             CheckUtil.ThrowIfNull(() => commandToUse);
             // ReSharper disable once PossibleNullReferenceException
             commandToUse.CommandText = commandText;
             return(await commandToUse.ExecuteNonQueryAsync());
         }
     }
     catch (Exception ex)
     {
         ExceptionCallback?.Invoke(ex);
         return(-1);
     }
 }
예제 #15
0
 /// <summary>
 /// Starts handling of one or many alarms.
 /// </summary>
 /// <param name="alarmTimes">The times when to start alarms.</param>
 /// <param name="onlyOnces">Indicates whether the clock should run forever.</param>
 public void Start(IEnumerable <TimeSpan> alarmTimes, bool onlyOnces = true)
 {
     if (IsRunning)
     {
         throw new InvalidOperationException("Stop a running alarm clock first.");
     }
     CheckUtil.ThrowIfNull(() => alarmTimes);
     if (!alarmTimes.Any())
     {
         throw new ArgumentException("No times specified.");
     }
     if (AlarmOccured == null)
     {
         throw new InvalidOperationException("No listener on AlarmOccured event. Alarm is useless.");
     }
     IsRunning   = true;
     _alarms     = 0;
     _alarmTimes = alarmTimes.ToList();
     _onlyOnce   = onlyOnces;
     AlarmClockStarted?.Invoke(this, EventArgs.Empty);
     StartNextTimer();
 }
예제 #16
0
 /// <summary>
 /// Iterates through a list of T and retrieves the index of the <paramref name="element" /> inside the enumerable.
 /// </summary>
 /// <typeparam name="T">The type of an element inside the <paramref name="enumerable" />.</typeparam>
 /// <param name="enumerable">The enumerable to extend.</param>
 /// <param name="element">The element to find.</param>
 /// <returns>The offset of the element or -1 if the element wasn't found in the enumerable.</returns>
 public static int GetIndexOf <T>(this IEnumerable <T> enumerable, T element)
     where T : IComparable
 {
     CheckUtil.ThrowIfNull(() => enumerable);
     return(enumerable.GetIndexOf(t => t.Equals(element)));
 }
예제 #17
0
 /// <summary>
 /// Retrieves the <see cref="DbSet" /> from the given <paramref name="ctx" /> which holds all items of the current
 /// <typeparamref name="TEntity" />.
 /// </summary>
 /// <param name="ctx">The EF context to use.</param>
 /// <returns>The entity set from the EF context.</returns>
 public DbSet <TEntity> GetEntitiesSet(TContext ctx)
 {
     CheckUtil.ThrowIfNull(() => ctx);
     return(ctx.Set <TEntity>());
 }