C#: Image to byte array
Image to byte array ... Reveal Code
Keep, track and share your code snippets with your friends
Image to byte array ... Reveal Code
public static byte[] imageToByteArray(Image imageIn) { MemoryStream ms = new MemoryStream(); imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Gif); return ms.ToArray(); }
Image to byte array 2 ... Reveal Code
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(); } } }
Gets the first day of the month from the given date.
Gets the last day of month from the given date. ... Reveal Code
public static class MonthExtensions { ////// Gets the first day of the month. /// /// The given date. ///the first day of the month public static DateTime GetFirstDayOfMonth(DateTime givenDate) { return new DateTime(givenDate.Year, givenDate.Month, 1); } ////// Gets the last day of month. /// /// The given date. ///the last day of the month public static DateTime GetTheLastDayOfMonth(DateTime givenDate) { return GetFirstDayOfMonth(givenDate).AddMonths(1).Subtract(new TimeSpan(1, 0, 0, 0, 0)); } }
DeSerialize object to xml file ... Reveal Code
private static void DeSerialize() { try { var testObject = new TestClass(); var serializer = new XmlSerializer(testObject.GetType()); var reader = new StreamReader(Filename); var deserialized = serializer.Deserialize(reader.BaseStream); testObject = (TestClass)deserialized; reader.Dispose(); } catch (Exception ex) { throw new Exception(ex.Message); } }
StringExtentions ... Reveal Code
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); } }
Update record in database using entity framework ... Reveal Code
try { using (var context = new myEntities()) { var document = context.ORDERS.Single(parameter => parameter.ID_ORDER == idOrder); document.ORDER_STATUS = status; context.SaveChanges(); } } catch (Exception ex) { Logger.TraceError(ex.Message); }
Calculate Age ... Reveal Code
public static int GetAge(DateTime birthday) { DateTime now = DateTime.Today; int age = now.Year - birthday.Year; if (now < birthday.AddYears(age)) age--; return age; }
If you want to create a screenshot out of your application, this is the perfect snippet suitable to your needs. ... Reveal Code
using System; using System.Drawing; using System.Windows.Forms; ////// Saves an image of the screen to the specified path. /// /// /// Path, where output file will be saved at. ///Path of the successfully saved image or errormessage public string ScreenToPicture(string Location) { try { Size currentScreenSize = new Size(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height); Bitmap ScreenToBitmap = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height); System.Drawing.Graphics gGraphics = System.Drawing.Graphics.FromImage(ScreenToBitmap); gGraphics.CopyFromScreen(new Point(0, 0), new Point(0, 0), currentScreenSize); ScreenToBitmap.Save(Location); return Location; } catch (Exception ex) { throw new Exception(ex.Message); } }
Serialize object to xml file ... Reveal Code
private static void Serialize(TestClass testObject) { try { var serializer = new XmlSerializer(testObject.GetType()); var writer = new StreamWriter(Filename); serializer.Serialize(writer.BaseStream, testObject); writer.Close(); } catch (Exception) { throw new Exception(); } }
A keyed collection that implements TryGetValue ... Reveal Code
[Serializable] public class TryKeyedCollection: KeyedCollection , IEquatable > { private readonly Func _KeyFunction; public TryKeyedCollection(Func keyFunction) : this(keyFunction, null) { } public TryKeyedCollection(Func keyFunction, IEqualityComparer comparer) : base(comparer) { _KeyFunction = keyFunction; } protected override TKey GetKeyForItem(TItem item) { return _KeyFunction(item); } public bool TryGetValue(TKey key, out TItem value) { if(Dictionary == null) { value = default(TItem); return false; } return Dictionary.TryGetValue(key, out value); } public void AddRange(IEnumerable items) { foreach(var item in items) Add(item); } public override Boolean Equals(Object obj) { return Equals(obj as TryKeyedCollection ); } public bool Equals(TryKeyedCollection other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; if (other.Count != Count) return false; for (var idx = 0; idx < Count; idx++) if (!Equals(this[idx], other[idx])) return false; return true; } public override int GetHashCode() { return base.GetHashCode(); } }
Misc helper methods for deserializing and serializing objects. ... Reveal Code
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. ... Reveal Code
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(); } }
Trace Execution Time Extension ... Reveal Code
public static class TraceExecutionTimeExtension { public static void TraceExecutionTime(this object thisObj, string name, Action action) { var timer = new Stopwatch(); timer.Start(); try { action(); } finally { timer.Stop(); Debug.WriteLine(string.Concat(name + " elapsed ms: " + timer.ElapsedMilliseconds)); } } public static T TraceExecutionTime(this object thisObj, string name, Func func) { var timer = new Stopwatch(); timer.Start(); try { return func(); } finally { timer.Stop(); Debug.WriteLine(string.Concat(name + " elapsed ms: " + timer.ElapsedMilliseconds)); } } }
IDbCommand Extensions ... Reveal Code
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 ... Reveal Code
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 ... Reveal Code
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); } }
A readonly dictionary implementation ... Reveal Code
public class ReadOnlyDictionary: IDictionary { private readonly IDictionary _Impl; public ReadOnlyDictionary(IDictionary impl) { if (impl == null) throw new ArgumentNullException("impl"); _Impl = impl; } public ReadOnlyDictionary(IEnumerable > impl) { if (impl == null) throw new ArgumentNullException("impl"); _Impl = new Dictionary (); foreach (var pair in impl) _Impl.Add(pair); } public ReadOnlyDictionary(IEnumerable > impl, IEqualityComparer comparer) { if (impl == null) throw new ArgumentNullException("impl"); _Impl = new Dictionary (comparer); foreach (var pair in impl) _Impl.Add(pair); } void IDictionary .Add(TKey key, TValue value) { throw new NotSupportedException(); } public bool ContainsKey(TKey key) { return _Impl.ContainsKey(key); } public ICollection Keys { get { return _Impl.Keys; } } bool IDictionary .Remove(TKey key) { throw new NotSupportedException(); } public bool TryGetValue(TKey key, out TValue value) { return _Impl.TryGetValue(key, out value); } public ICollection Values { get { return _Impl.Values; } } public TValue this[TKey key] { get { return _Impl[key];} set { throw new NotSupportedException(); } } void ICollection >.Add(KeyValuePair item) { throw new NotSupportedException(); } void ICollection >.Clear() { throw new NotSupportedException(); } bool ICollection >.Contains(KeyValuePair item) { return ((ICollection >) _Impl).Contains(item); } void ICollection >.CopyTo(KeyValuePair [] array, int arrayIndex) { ((ICollection >) _Impl).CopyTo(array, arrayIndex); } public int Count { get { return _Impl.Count; } } public bool IsReadOnly{get { return true; }} bool ICollection >.Remove(KeyValuePair item) { throw new NotSupportedException(); } public IEnumerator > GetEnumerator() { return _Impl.GetEnumerator(); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator(){return _Impl.GetEnumerator();} }
INotifyPropertyChanged implementation using EqualityComparer. ... Reveal Code
namespace Tools { public class NotifyPropertyChangedBase { private event PropertyChangedEventHandler PropertyChanged; public void SetProperty(ref T field, T value, string name) { if (EqualityComparer .Default.Equals(field, value)) return; field = value; var handler = PropertyChanged; if (handler != null) { handler(this, new PropertyChangedEventArgs(name)); } } } } namespace Tools { public class NotifyPropertyChangedExample : NotifyPropertyChangedBase { private int _unitsInStock; private const string UnitsInStockPropertyName = "UnitsInStock"; public int UnitsInStock { get { return _unitsInStock; } set { SetProperty(ref _unitsInStock, value, UnitsInStockPropertyName); } } } }