Skip to content

Instantly share code, notes, and snippets.

@jaydeepkarena
Created November 2, 2018 11:27
Show Gist options
  • Save jaydeepkarena/6a1b28be859a98bae0ae094917769cc1 to your computer and use it in GitHub Desktop.
Save jaydeepkarena/6a1b28be859a98bae0ae094917769cc1 to your computer and use it in GitHub Desktop.
C# Extension Method Collection
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Globalization;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Windows.Forms;
using Telerik.WinControls;
using Telerik.WinControls.UI;
namespace CommonForms
{
public static class MyExtension
{
#region RadGridView
public static Int64 RowCount(this RadGridView radGrid)
{
try
{
return radGrid.Rows.Count();
}
catch (Exception ex)
{
ErrorLogger.ErrorLog(ex.GetFullExceptionDetail());
return 0;
}
}
public static void SetBackColor(this GridViewCellInfo cell, Color color)
{
try
{
cell.Style.DrawFill = cell.Style.CustomizeFill = true;
cell.Style.BackColor = color;
}
catch (Exception ex)
{
ErrorLogger.ErrorLog(ex.GetFullExceptionDetail());
}
}
public static void SetForeColor(this GridViewCellInfo cell, Color color)
{
try
{
cell.Style.DrawFill = true;
cell.Style.CustomizeFill = true;
cell.Style.ForeColor = color;
}
catch (Exception ex)
{
ErrorLogger.ErrorLog(ex.GetFullExceptionDetail());
}
}
public static void SetColor(this GridViewCellInfo cell, Color ForeColor, Color BackColor)
{
try
{
cell.SetForeColor(ForeColor);
cell.SetBackColor(BackColor);
}
catch (Exception ex)
{
ErrorLogger.ErrorLog(ex.GetFullExceptionDetail());
}
}
public static void SetFont(this GridViewCellInfo cell, Font font)
{
try
{
cell.Style.Font = font;
cell.Style.DrawFill = true;
cell.Style.CustomizeFill = true;
}
catch (Exception ex)
{
ErrorLogger.ErrorLog(ex.GetFullExceptionDetail());
}
}
public static void ResetBackColor(this GridViewCellInfo cell, Color resetColor)
{
try
{
cell.Style.DrawFill = false;
cell.Style.CustomizeFill = false;
cell.Style.BackColor = resetColor;
}
catch (Exception ex)
{
ErrorLogger.ErrorLog(ex.GetFullExceptionDetail());
}
}
public static void ResetForeColor(this GridViewCellInfo cell, Color resetColor)
{
try
{
cell.Style.DrawFill = false;
cell.Style.CustomizeFill = false;
cell.Style.BackColor = resetColor;
}
catch (Exception ex)
{
ErrorLogger.ErrorLog(ex.GetFullExceptionDetail());
}
}
public static void ScrollToRowIndex(this RadGridView radGridView, int RowIndex)
{
try
{
if (RowIndex < 0)
return;
if (RowIndex > radGridView.Rows.Count - 1)
return;
radGridView.TableElement.ScrollToRow(RowIndex);
}
catch (Exception ex)
{
ErrorLogger.ErrorLog(ex.GetFullExceptionDetail());
}
}
public static void ScrollToRow(this RadGridView radGridView, GridViewRowInfo row)
{
try
{
radGridView.TableElement.ScrollToRow(row);
}
catch (Exception ex)
{
ErrorLogger.ErrorLog(ex.GetFullExceptionDetail());
}
}
public static void ScrollToLastRow(this RadGridView radGridView)
{
try
{
if (radGridView.Rows.Count == 0)
return;
radGridView.TableElement.ScrollToRow(radGridView.Rows.Last());
}
catch (Exception ex)
{
ErrorLogger.ErrorLog(ex.GetFullExceptionDetail());
}
}
public static void EnableNumericSort(this RadGridView radGridView, List<string> includeColumns = null,
List<string> excludeColumns = null,
List<string> onlyColumns = null)
{
try
{
includeColumns = includeColumns ?? new List<string> { };
excludeColumns = excludeColumns ?? new List<string> { };
string column = "";
if (onlyColumns != null)
{
foreach (var col in radGridView.Columns)
{
if (onlyColumns.Contains(col.Name))
col.DataType = typeof(double);
}
return;
}
foreach (var col in radGridView.Columns)
{
column = col.Name.ToLower();
if (column.IsIn(excludeColumns.ToArray()))
continue;
if (HelperCommon.isNumberColumn(column) || column.IsIn(includeColumns.ToArray()))
col.DataType = typeof(double);
}
}
catch (Exception ex)
{
ErrorLogger.ErrorLog(ex.GetFullExceptionDetail());
}
}
public static void EnableSortingOnComboboxColumnDisplayValue(this RadGridView radGridView, string[] excludeColumns = null)
{
try
{
excludeColumns = excludeColumns ?? new string[] { "" };
foreach (var col in radGridView.Columns)
{
if (col.GetDefaultEditorType() != null &&
col.GetDefaultEditorType().Name == "RadDropDownListEditor" &&
col.Name.ToString().ToLower().IsNotIn(excludeColumns))
{
(col as GridViewComboBoxColumn).DisplayMemberSort = true;
}
}
}
catch (Exception ex)
{
ErrorLogger.ErrorLog(ex.GetFullExceptionDetail());
}
}
public static string DisplayValue(this GridViewCellInfo cell, RadGridView radGridView)
{
string returnValue = "";
try
{
if (radGridView.Columns[cell.ColumnInfo.Name].GetType().ToString() != "Telerik.WinControls.UI.GridViewComboBoxColumn")
return returnValue;
if (radGridView.Rows.Count > 0)
{
if (radGridView.Rows[cell.RowInfo.Index].Cells[cell.ColumnInfo.Name] != null)
{
GridViewCellInfo cellInfo = radGridView.Rows[cell.RowInfo.Index].Cells[cell.ColumnInfo.Name];
GridCellElement cellElement = radGridView.TableElement.GetCellElement(cellInfo.RowInfo, cellInfo.ColumnInfo);
if (cellElement != null)
returnValue = cellElement.Text;
}
}
}
catch (Exception ex)
{
ErrorLogger.ErrorLog(ex.GetFullExceptionDetail());
}
return returnValue;
}
#endregion
#region DataGridView
public static void SetBackColor(this DataGridViewCell cell, Color color)
{
try
{
cell.Style.BackColor = color;
}
catch (Exception ex)
{
ErrorLogger.ErrorLog(ex.GetFullExceptionDetail());
}
}
public static void SetForeColor(this DataGridViewCell cell, Color color)
{
try
{
cell.Style.ForeColor = color;
}
catch (Exception ex)
{
ErrorLogger.ErrorLog(ex.GetFullExceptionDetail());
}
}
public static void ResetBackGroundColor(this DataGridViewCell cell, Color resetColor)
{
try
{
cell.Style.BackColor = resetColor;
}
catch (Exception ex)
{
ErrorLogger.ErrorLog(ex.GetFullExceptionDetail());
}
}
public static void ResetForeColor(this DataGridViewCell cell, Color resetColor)
{
try
{
cell.Style.BackColor = resetColor;
}
catch (Exception ex)
{
ErrorLogger.ErrorLog(ex.GetFullExceptionDetail());
}
}
#endregion
#region DataTable
public static Int64 RowCount(this DataTable dt)
{
try
{
return dt.Rows.Count;
}
catch (Exception ex)
{
ErrorLogger.ErrorLog(ex.GetFullExceptionDetail());
return 0;
}
}
public static void DeleteFirstRow(this DataTable dt)
{
try
{
if (dt.Rows.Count > 0)
dt.Rows.RemoveAt(0);
}
catch (Exception ex)
{
ErrorLogger.ErrorLog(ex.GetFullExceptionDetail());
}
}
public static void DeleteLastRow(this DataTable dt)
{
try
{
if (dt.Rows.Count > 0)
{
dt.Rows.RemoveAt(dt.Rows.Count - 1);
}
}
catch (Exception ex)
{
ErrorLogger.ErrorLog(ex.GetFullExceptionDetail());
}
}
public static void DeleteRowAt(this DataTable dt, int rowIndex)
{
try
{
if (rowIndex < dt.Rows.Count)
{
dt.Rows.RemoveAt(rowIndex);
}
}
catch (Exception ex)
{
ErrorLogger.ErrorLog(ex.GetFullExceptionDetail());
}
}
public static void ConvertColumnType(this DataTable dt, string columnName, Type newType)
{
try
{
using (DataColumn dc = new DataColumn(columnName + "_new", newType))
{
// Add the new column which has the new type, and move it to the ordinal of the old column
int ordinal = dt.Columns[columnName].Ordinal;
dt.Columns.Add(dc);
dc.SetOrdinal(ordinal);
// Get and convert the values of the old column, and insert them into the new
foreach (DataRow dr in dt.Rows)
dr[dc.ColumnName] = Convert.ChangeType(dr[columnName], newType);
// Remove the old column
dt.Columns.Remove(columnName);
// Give the new column the old column's name
dc.ColumnName = columnName;
}
}
catch (Exception ex)
{
ErrorLogger.ErrorLog(ex.GetFullExceptionDetail());
}
}
#endregion
#region Double
public static bool HasValue(this double value)
{
return !Double.IsNaN(value) && !Double.IsInfinity(value);
}
public static string ToIndianFormat(this double value, int round = 0, bool prefixDollarSymbol = false)
{
string returnValue = value.ToString();
try
{
value = Math.Round(value, round);
CultureInfo culture = new CultureInfo("hi-IN");
string format = "{0:#,#}";
if (round > 0)
format = "{0:#,#." + new string('#', round) + "}";
returnValue = (prefixDollarSymbol ? "$" : "") +
string.Format(culture, format, value);
}
catch (Exception ex)
{
ErrorLogger.ErrorLog(ex.GetFullExceptionDetail());
}
return returnValue;
}
#endregion
#region Exception
public static string GetFullExceptionDetail(this Exception ex)
{
string details = "";
try
{
var st = new StackTrace(ex, true); // create the stack trace
var query = st.GetFrames() // get the frames
.Select(frame => new
{ // get the info
FileName = frame.GetFileName(),
LineNumber = frame.GetFileLineNumber(),
ColumnNumber = frame.GetFileColumnNumber(),
Method = frame.GetMethod(),
Class = frame.GetMethod().DeclaringType
});
var l = query.ToList();
int index = l.Count - 1;
string fileName = "";
if (l[index].FileName != null)
{
fileName = l[index].FileName.ToString();
if (fileName.LastIndexOf("\\") - 1 > 0)
{
fileName = fileName.Substring(fileName.LastIndexOf("\\") + 1);
}
}
details += Environment.NewLine;
details += "File : " + fileName + Environment.NewLine;
details += "Class : " + l[index].Class + Environment.NewLine;
details += "Method : " + l[index].Method + Environment.NewLine;
details += "Line-Col : " + l[index].LineNumber + " - " + l[index].ColumnNumber + Environment.NewLine;
details += "Errro : " + ex.Message + Environment.NewLine;
if (ex.InnerException != null)
details += "Inner Ex.: " + Convert.ToString(ex.InnerException.Message);
return details;
}
catch
{
ErrorLogger.ErrorLog(ex.Message);
return details;
}
}
#endregion
#region String
public static Double Val(this string value)
{
try
{
if (value.Equals(".") || value.Trim().Equals("") || value.Equals("-"))
return 0;
String result = String.Empty;
foreach (char c in value)
{
if (Char.IsNumber(c) ||
(c.Equals('.') && result.Count(x => x.Equals('.')) == 0) ||
(c.Equals('-') && result.Count(x => x.Equals('-')) == 0))
result += c;
else if (!c.Equals(' '))
return String.IsNullOrEmpty(result) ? 0 : Convert.ToDouble(result);
}
return String.IsNullOrEmpty(result) ? 0 : Convert.ToDouble(result);
}
catch (Exception ex)
{
ErrorLogger.ErrorLog(ex.GetFullExceptionDetail());
return 0;
}
}
public static string ToMD5Hash(this string text)
{
StringBuilder strBuilder = new StringBuilder();
try
{
MD5 md5 = new MD5CryptoServiceProvider();
//compute hash from the bytes of text
md5.ComputeHash(Encoding.ASCII.GetBytes(text));
//get hash result after compute it
byte[] result = md5.Hash;
for (int i = 0; i < result.Length; i++)
{
strBuilder.Append(result[i].ToString("x2"));
}
}
catch (Exception ex)
{
ErrorLogger.ErrorLog(ex.GetFullExceptionDetail());
strBuilder.Clear();
}
return strBuilder.ToString();
}
public static bool IsIn<T>(this T valueToBeSearched, params T[] values)
{
try
{
if (valueToBeSearched.GetType().Name.ToLower() == "string")
{
string tValue = valueToBeSearched.ToString().ToLower();
string[] tValues = values.Select(w => w.ToString().ToLower()).ToArray();
return tValues.Contains(tValue);
}
return values.Contains(valueToBeSearched);
}
catch (Exception ex)
{
ErrorLogger.ErrorLog(ex.GetFullExceptionDetail());
}
return false;
}
public static bool IsNotIn<T>(this T word, params T[] strings)
{
return !(word.IsIn(strings));
}
public static Color ToColor(this string color)
{
return (Color)new ColorConverter().ConvertFromString(color); ;
}
public static void SplitIntoTwoParts(this string str, ref string part1, ref string part2, char separator = ',')
{
part1 = "";
part2 = "";
try
{
string[] strArr = str.Split(separator);
if (strArr.Length > 0)
part1 = strArr[0];
if (strArr.Length > 1)
part2 = strArr[1];
}
catch (Exception ex)
{
ErrorLogger.ErrorLog(ex.GetFullExceptionDetail());
}
}
public static string ToTittleCase(this string word) =>
CultureInfo.InvariantCulture.TextInfo.ToTitleCase(word.ToLower());
#endregion
#region DateTime
public static string ToLongSQLiteDateString(this DateTime date)
{
try
{
return string.Format("{0:yyyy-MM-dd HH:mm:ss}", date);
}
catch (Exception ex)
{
ErrorLogger.ErrorLog(ex.GetFullExceptionDetail());
}
return "";
}
public static string ToShortSQLiteDateString(this DateTime date)
{
try
{
return string.Format("{0:yyyy-MM-dd}", date);
}
catch (Exception ex)
{
ErrorLogger.ErrorLog(ex.GetFullExceptionDetail());
}
return "";
}
public static string ToShortIndianDateString(this DateTime date)
{
try
{
return string.Format("{0:dd-MM-yyyy}", date);
}
catch (Exception ex)
{
ErrorLogger.ErrorLog(ex.GetFullExceptionDetail());
}
return "";
}
public static string ToLongIndianDateString(this DateTime date)
{
try
{
return string.Format("{0:dd-MM-yyyy HH:mm:ss}", date);
}
catch (Exception ex)
{
ErrorLogger.ErrorLog(ex.GetFullExceptionDetail());
}
return "";
}
public static void ReplaceDatePart(this DateTime date, DateTime GetDateFrom)
{
try
{
DateTime time = Convert.ToDateTime(date);
date = Convert.ToDateTime(GetDateFrom)
.Date
.AddHours(time.Hour)
.AddMinutes(time.Minute)
.AddSeconds(time.Second);
}
catch (Exception ex)
{
ErrorLogger.ErrorLog(ex.GetFullExceptionDetail());
}
}
#endregion
#region DateTime?
public static string ToLongSQLiteDateString(this DateTime? date)
{
try
{
return string.Format("{0:yyyy-MM-dd HH:mm:ss}", date);
}
catch (Exception ex)
{
ErrorLogger.ErrorLog(ex.GetFullExceptionDetail());
}
return "";
}
public static string ToShortSQLiteDateString(this DateTime? date)
{
try
{
return string.Format("{0:yyyy-MM-dd}", date);
}
catch (Exception ex)
{
ErrorLogger.ErrorLog(ex.GetFullExceptionDetail());
}
return "";
}
public static string ToIndianShortDateString(this DateTime? date)
{
try
{
return string.Format("{0:dd-MM-yyyy}", date);
}
catch (Exception ex)
{
ErrorLogger.ErrorLog(ex.GetFullExceptionDetail());
}
return "";
}
public static string ToIndianLongDateString(this DateTime? date)
{
try
{
return string.Format("{0:dd-MM-yyyy HH:mm:ss}", date);
}
catch (Exception ex)
{
ErrorLogger.ErrorLog(ex.GetFullExceptionDetail());
}
return "";
}
public static bool IsBetween(this DateTime? date, DateTime? fromDate, DateTime? toDate)
{
try
{
if (fromDate == null || toDate == null || date == null)
return false;
return (date >= fromDate && date <= toDate);
}
catch (Exception ex)
{
ErrorLogger.ErrorLog(ex.GetFullExceptionDetail());
}
return false;
}
// this method replaces the date part of current object with passed GetDateFrom's date
public static DateTime? ReplaceDatePart(this DateTime? date, DateTime? GetDateFrom)
{
try
{
DateTime time = Convert.ToDateTime(date);
return date = Convert.ToDateTime(GetDateFrom)
.Date
.AddHours(time.Hour)
.AddMinutes(time.Minute)
.AddSeconds(time.Second);
}
catch (Exception ex)
{
ErrorLogger.ErrorLog(ex.GetFullExceptionDetail());
}
return date;
}
#endregion
#region checkListBox
public static void SetItemChecked(this CheckedListBox checkListBox, string item)
{
int index = checkListBox.GetItemIndex(item);
if (index < 0) return;
checkListBox.SetItemChecked(index, true);
}
public static int GetItemIndex(this CheckedListBox checkListBox, string item)
{
int index = 0;
foreach (object o in checkListBox.Items)
{
if (item == o.ToString())
return index;
index++;
}
return -1;
}
#endregion
#region RadButton
public static void SetBackColor(this RadButton btn, Color color)
{
try
{
btn.ButtonElement.BorderElement.BackgroundShape = null;
btn.ButtonElement.ButtonFillElement.GradientStyle = GradientStyles.Solid;
btn.ButtonElement.ButtonFillElement.BackColor = color;
}
catch (Exception ex)
{
ErrorLogger.ErrorLog(ex.GetFullExceptionDetail());
}
}
public static void SetDangerButton(this RadButton btn)
{
try
{
btn.ButtonElement.BorderElement.BackgroundShape = null;
btn.ButtonElement.ButtonFillElement.GradientStyle = GradientStyles.Solid;
btn.ButtonElement.ButtonFillElement.BackColor = Color.OrangeRed;
btn.ButtonElement.ForeColor = Color.White;
}
catch (Exception ex)
{
ErrorLogger.ErrorLog(ex.GetFullExceptionDetail());
}
}
public static void SetForeColor(this RadButton btn, Color color)
{
try
{
btn.ButtonElement.ForeColor = color;
}
catch (Exception ex)
{
ErrorLogger.ErrorLog(ex.GetFullExceptionDetail());
}
}
#endregion
#region Misc
public static T To<T>(this object input)
{
return To<T>(input, default(T));
}
public static T To<T>(this object input, T defaultValue)
{
T ret = defaultValue;
if (input == null || input == DBNull.Value) return ret;
try
{
ret = (T)Convert.ChangeType(input, typeof(T), System.Globalization.CultureInfo.InvariantCulture);
}
catch { }
return ret;
}
public static void ForEach<T>(this IEnumerable<T> enumeration, Action<T> action)
{
foreach (var item in enumeration)
{
action(item);
}
}
public static void InvokeIfRequired<T>(this T control, Action<T> action) where T : Control
{
if (control.InvokeRequired)
{
control.Invoke(new Action(() => action(control)));
}
else
{
action(control);
}
}
public static bool IsBetween<T>(this T value, T fromValue, T toValue) where T : IComparable
{
try
{
if (value.CompareTo(fromValue) == 0 || value.CompareTo(toValue) == 0)
return true;
return value.CompareTo(fromValue) > 0 && value.CompareTo(toValue) < 0;
}
catch (Exception ex)
{
ErrorLogger.ErrorLog(ex.GetFullExceptionDetail());
}
return false;
}
public static bool IsNumeric(object Expression)
{
bool result = false;
try
{
double retNum;
result = Double.TryParse(Convert.ToString(Expression), System.Globalization.NumberStyles.Any, System.Globalization.NumberFormatInfo.InvariantInfo, out retNum);
}
catch (Exception ex)
{
ErrorLogger.ErrorLog(ex.GetFullExceptionDetail());
return false;
}
return result;
}
public static void AddIfNotAvailable<TKey, TValue>(this Dictionary<TKey, TValue> dict, TKey key)
where TValue : new()
{
TValue value;
if (!dict.TryGetValue(key, out value))
{
value = new TValue();
dict.Add(key, value);
}
}
#endregion
#region List
public static DataTable ToDataTale<T>(this List<T> list)
{
DataTable dt = App.ClassToDataTable<T>();
try
{
var properties = typeof(T).GetProperties();
List<object> values = new List<object>();
foreach (T item in list)
{
foreach (var prop in properties)
{
values.Add(typeof(T).GetProperty(prop.Name).GetValue(item));
}
dt.Rows.Add(values.ToArray());
values.Clear();
}
}
catch (Exception ex)
{
ErrorLogger.ErrorLog(ex.GetFullExceptionDetail());
}
return dt;
}
#endregion
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment