C#: Image to byte array 2
Image to byte array 2 ... Показать код
Храните, отслеживайте и делитесь с друзьями вашими сниппетами
Image to byte array 2 ... Показать код
public static class ImageExtentions { public static byte[] ToByteArray(this Image image, ImageFormat imageFormat) { using (MemoryStream ms = new MemoryStream()) { image.Save(ms, imageFormat); return ms.ToArray(); } } }
StringExtentions ... Показать код
public static class StringExtentions { public static String Format(this String str, params Object[] args) { return String.Format(str, args); } public static String Format(this String str, IFormatProvider provider, params Object[] args) { return String.Format(provider, str, args); } }
Misc helper methods for deserializing and serializing objects. ... Показать код
public static class SerializeHelpers { ////// Takes an array of bytes and attempts to deserialize it into an object. /// /// ///public static T DeserializeFromByteArray (byte[] source) where T : class { return DeserializeFromByteArray (source, s => { }, r => { }); } /// /// Takes an array of bytes and attempts to deserialize it into an object. /// /// /// /// ///public static T DeserializeFromByteArray (byte[] source, Action deserializingAction, Action deserializedAction) where T : class { if (source == null) throw new ArgumentNullException("source"); if (source.Length <= 0) throw new ArgumentException("Can not deserialize from an empty byte array!", "source"); if (deserializingAction == null) throw new ArgumentNullException("deserializingAction"); if (deserializedAction == null) throw new ArgumentNullException("deserializedAction"); deserializingAction(source); var ms = new MemoryStream(); ms.Write(source, 0, source.Length); ms.Seek(0, SeekOrigin.Begin); var b = new BinaryFormatter(); var result = (T)b.Deserialize(ms); deserializedAction(result); return result; } /// /// Takes any object and attempts to serialize it into an array of bytes. /// /// ////// public static byte[] SerializeToByteArray (T source) where T : class { return SerializeToByteArray (source, s => { }, r => { }); } /// /// Takes any object and attempts to serialize it into an array of bytes. /// /// /// /// ////// public static byte[] SerializeToByteArray (T source, Action serializingAction, Action serializedAction) where T : class { if (source == null) throw new ArgumentNullException("source"); if (serializingAction == null) throw new ArgumentNullException("serializingAction"); if (serializedAction == null) throw new ArgumentNullException("serializedAction"); serializingAction(source); var b = new BinaryFormatter(); var ms = new MemoryStream(); b.Serialize(ms, source); ms.Seek(0, SeekOrigin.Begin); var result = ms.ToArray(); serializedAction(result); return result; } /// /// Takes any object and attempts to serialize it into a string. /// /// ////// public static string SerializeToString (T source) where T : class { return SerializeToString(source, s => { }, r => { }); } /// /// Takes any object and attempts to serialize it into a string. /// /// /// /// ////// public static string SerializeToString (T source, Action serializingAction, Action serializedAction) where T : class { if (source == null) throw new ArgumentNullException("source"); if (serializingAction == null) throw new ArgumentNullException("serializingAction"); if (serializedAction == null) throw new ArgumentNullException("serializedAction"); serializingAction(source); string serialString = null; using (var ms1 = new System.IO.MemoryStream()) { var b = new BinaryFormatter(); b.Serialize(ms1, source); var arrayByte = ms1.ToArray(); serialString = Convert.ToBase64String(arrayByte); } serializedAction(serialString); return serialString; } /// /// Takes a string and attempts to deserialize it into an object. /// /// ///public static T DeserializeFromString (string source) where T : class { return DeserializeFromString (source, s => { }, r => { }); } /// /// Takes a string and attempts to deserialize it into an object. /// /// /// /// ///public static T DeserializeFromString (string source, Action deserializingAction, Action deserializedAction) where T : class { if (string.IsNullOrEmpty(source)) throw new ArgumentNullException("source"); if (source.Length <= 0) throw new ArgumentException("Can not deserialize from an empty byte array!", "source"); if (deserializingAction == null) throw new ArgumentNullException("deserializingAction"); if (deserializedAction == null) throw new ArgumentNullException("deserializedAction"); deserializingAction(source); T deserializedObject = null; var arrayByte = Convert.FromBase64String(source); using (var ms1 = new MemoryStream(arrayByte)) { var b = new BinaryFormatter(); deserializedObject = (T)b.Deserialize(ms1); } deserializedAction(deserializedObject); return deserializedObject; } public static string SerializeToXml(object source) { return SerializeToXml(false); } public static string SerializeToXml(object source, bool omitXmlDeclaration) { var xmlString = new StringBuilder(); var xmlSettings = new XmlWriterSettings { Encoding = new UTF8Encoding(), OmitXmlDeclaration = omitXmlDeclaration }; var xmlWriter = XmlWriter.Create(xmlString, xmlSettings); var serializer = new XmlSerializer(source.GetType()); if (xmlWriter != null) { serializer.Serialize(xmlWriter, source); xmlWriter.Close(); } return xmlString.ToString(); } public static T DeserializeFromXml (string source) where T : class { var serializer = new XmlSerializer(typeof(T)); var reader = new StringReader(source); T result = (T) serializer.Deserialize(reader); reader.Dispose(); return result; } }
Enum Extensions, method to extract Description attribute of an enum value. ... Показать код
public static class EnumExtensions { public static bool IsDefined(this Enum value) { return Enum.IsDefined(value.GetType(), value); } public static string Description(this Enum value) { var da = (DescriptionAttribute[]) (value.GetType().GetField(value.ToString()).GetCustomAttributes(typeof(DescriptionAttribute), false)); return da.Length > 0 ? da[0].Description : value.ToString(); } }
IDbCommand Extensions ... Показать код
public static class IDbCommandExtensions { public static void AddInParam(this IDbCommand thisObj, string name, DbType type) { thisObj.AddInParam(name, type, null); } public static void AddInParam(this IDbCommand thisObj, string name, DbType type, object value) { IDataParameter param = thisObj.CreateDBParam(name, type, value); thisObj.Parameters.Add(param); //Do not add until after all values have been set, in case of exception } public static void AddInParam(this IDbCommand thisObj, string name, DbType type, object value, int size) { IDbDataParameter param = thisObj.CreateDBParam(name, type, ParameterDirection.Input, value); param.Size = size; thisObj.Parameters.Add(param); //Do not add until after all values have been set, in case of exception } public static void AddOutParam(this IDbCommand thisObj, string name, DbType type) { thisObj.Parameters.Add(CreateDBParam(thisObj, name, type, ParameterDirection.Output, DBNull.Value)); } public static void AddOutParam(this IDbCommand thisObj, String name, DbType type, int size) { IDbDataParameter param = CreateDBParam(thisObj, name, type, ParameterDirection.Output, DBNull.Value); param.Size = size; thisObj.Parameters.Add(param); } public static IDbDataParameter CreateDBParam(this IDbCommand thisObj, string name, DbType type) { return CreateDBParam(thisObj, name, type, ParameterDirection.Input, null); } public static IDbDataParameter CreateDBParam(this IDbCommand thisObj, string name, DbType type, Object value) { return CreateDBParam(thisObj, name, type, ParameterDirection.Input, value); } public static IDbDataParameter CreateDBParam(this IDbCommand thisObj, string name, DbType type, ParameterDirection direction, Object value) { IDbDataParameter param = thisObj.CreateParameter(); param.ParameterName = name; param.DbType = type; param.Value = value ?? DBNull.Value; param.Direction = direction; return param; } public static T ExecuteScalar(this IDbCommand thisObj) { var result = thisObj.ExecuteScalar(); return NullSafeConvert.ConvertTo (result); } public static T ExecuteScalarOrDefault (this IDbCommand thisObj, T defaultValue) { var result = thisObj.ExecuteScalar(); return (Convert.IsDBNull(result) || result == null) ? defaultValue : NullSafeConvert.ConvertTo (result); } public static int ExecuteNonQuery(this IDbCommand thisObj, int retryCount) { if (thisObj.Transaction != null) return ExecuteNonQuery(thisObj, thisObj.Transaction.IsolationLevel, retryCount); else return ExecuteNonQuery(thisObj, IsolationLevel.Unspecified, retryCount); } public static int ExecuteNonQuery(this IDbCommand thisObj, IsolationLevel isolationLevel, int retryCount) { return ExecuteNonQuery(thisObj, isolationLevel, retryCount, 3000); } public static int ExecuteNonQuery(this IDbCommand thisObj, int retryCount, int delayInMilliseconds) { if (thisObj.Transaction != null) return ExecuteNonQuery(thisObj, thisObj.Transaction.IsolationLevel, retryCount, delayInMilliseconds); else return ExecuteNonQuery(thisObj, IsolationLevel.Unspecified, retryCount, delayInMilliseconds); } public static int ExecuteNonQuery(this IDbCommand thisObj, IsolationLevel isolationLevel, int retryCount, int delayInMilliseconds) { if (thisObj.Transaction != null) throw new InvalidOperationException("Command should not be associated with an existing transaction"); const int DEADLOCK_ERROR_NUMBER = 1205; bool wasSuccessful = false; int retryCounter = 0, result = 0; while (!wasSuccessful && retryCounter < retryCount) { thisObj.Transaction = GetTransaction(thisObj, isolationLevel); try { result = thisObj.ExecuteNonQuery(); if (thisObj.Transaction != null) thisObj.Transaction.Commit(); wasSuccessful = true; } catch (SqlException ex) { if (ex.Number != DEADLOCK_ERROR_NUMBER || retryCounter >= retryCount) { if (thisObj.Transaction != null) thisObj.Transaction.Rollback(); throw; } thisObj.Cancel(); Thread.Sleep(delayInMilliseconds); ; // set a delay wasSuccessful = false; retryCounter += 1; } } return result; } private static IDbTransaction GetTransaction(IDbCommand command, IsolationLevel isolationLevel) { return isolationLevel != IsolationLevel.Unspecified ? command.Connection.BeginTransaction(isolationLevel) : null; } }
IDb Connection Extensions ... Показать код
public static class IDbConnectionExtensions { public static IDbCommand CreateTextCommand(this IDbConnection thisObj, string sql) { return CreateCommand(thisObj, sql, CommandType.Text); } public static IDbCommand CreateStoredProcedureCommand(this IDbConnection thisObj, string storedProcedure) { return CreateCommand(thisObj, storedProcedure, CommandType.StoredProcedure); } internal static IDbCommand CreateCommand(this IDbConnection thisObj, string text, CommandType cmdType) { IDbCommand cmd = null; try { cmd = thisObj.CreateCommand(); cmd.Connection = thisObj; cmd.CommandText = text; cmd.CommandType = cmdType; return cmd; } catch (Exception) { cmd.TryDispose(); throw; } } public static T ExecuteScalar(this IDbConnection thisObj, string sql, Action action) { using (var cmd = thisObj.CreateTextCommand(sql)) { action(cmd); return cmd.ExecuteScalar (); } } public static T ExecuteScalar (this IDbConnection thisObj, string sql) { return thisObj.ExecuteScalar (sql, cmd => { }); } public static T ExecuteScalar (this IDbConnection thisObj, Action action) { return thisObj.ExecuteScalar (string.Empty, action); } public static int ExecuteNonQuery(this IDbConnection thisObj, string sql, Action action) { using (var cmd = thisObj.CreateTextCommand(sql)) { action(cmd); return cmd.ExecuteNonQuery(); } } public static int ExecuteNonQuery(this IDbConnection thisObj, Action action) { return thisObj.ExecuteNonQuery(string.Empty, action); } public static int ExecuteNonQuery(this IDbConnection thisObj, string sql) { using (var cmd = thisObj.CreateTextCommand(sql)) { return cmd.ExecuteNonQuery(); } } public static int ExecuteNonQuery(this IDbConnection thisObj, string sql, int retryCount) { return ExecuteNonQuery(thisObj, sql, retryCount, 3000); } public static int ExecuteNonQuery(this IDbConnection thisObj, string sql, int retryCount, int delayInMilliseconds) { using (var cmd = thisObj.CreateTextCommand(sql)) { return cmd.ExecuteNonQuery(retryCount, delayInMilliseconds); } } public static IDataReader ExecuteReader(this IDbConnection thisObj, string sql) { using (var cmd = thisObj.CreateTextCommand(sql)) { return cmd.ExecuteReader(); } } public static void WithinTransaction(this IDbConnection thisObj, Action action) { using (var transaction = thisObj.BeginTransaction()) { action(transaction); transaction.Commit(); } } }
Enterprise Library Database Extensions ... Показать код
public static class DatabaseExtensions { public static void WithConnection(this MSDB.Database thisObj, Actionaction) { using (var connection = thisObj.CreateConnection()) { connection.Open(); action(connection); } } public static T WithConnection (this MSDB.Database db, Func action) { using (var conn = db.CreateConnection()) { conn.Open(); return action(conn); } } public static void WithinTransaction(this MSDB.Database thisObj, Action action) { thisObj.WithConnection(conn => conn.WithinTransaction(action)); } public static T WithinTransaction (this MSDB.Database db, Func action) { return db.WithConnection( conn => { using (var transaction = conn.BeginTransaction()) { var result = action(transaction); transaction.Commit(); return result; } }); } public static void WithTextCommand(this MSDB.Database db, string sql, Action action) { db.WithConnection(conn => { using (var cmd = conn.CreateTextCommand(sql)) { action(cmd); } }); } public static T WithTextCommand (this MSDB.Database db, string sql, Func action) { return db.WithConnection(conn => { using (var cmd = conn.CreateTextCommand(sql)) { return action(cmd); } }); } public static T ExecuteScalar (this MSDB.Database db, string sql, Action action) { using (var conn = db.CreateConnection()) { conn.Open(); return conn.ExecuteScalar (sql, action); } } public static T ExecuteScalar (this MSDB.Database db, string sql) { return db.ExecuteScalar (sql, cmd => { }); } public static T ExecuteScalar (this MSDB.Database db, Action action) { return db.ExecuteScalar (string.Empty, action); } public static int ExecuteNonQuery(this MSDB.Database db, string sql, Action action) { using (var cmd = db.GetSqlStringCommand(sql)) { action(cmd); return db.ExecuteNonQuery(cmd); } } public static int ExecuteNonQuery(this MSDB.Database db, Action action) { return db.ExecuteNonQuery(string.Empty, action); } }