Skip to content

Instantly share code, notes, and snippets.

@Davoodeh
Created October 11, 2021 08:49
Show Gist options
  • Save Davoodeh/f47aa9cb4a3f7909d5a11c5dea2b2c01 to your computer and use it in GitHub Desktop.
Save Davoodeh/f47aa9cb4a3f7909d5a11c5dea2b2c01 to your computer and use it in GitHub Desktop.
C# Common Static Helper Methods/Classes and Extensions
using System;
using System.Linq;
using System.IO;
using System.Drawing.Imaging;
using System.Drawing;
using System.Configuration;
using System.Collections.Generic;
using System.Globalization;
namespace Helpers
{
static class Extensions
{
public static DateTime DateStringToPersianDateTime(this string str, char dateSeparator = '-')
{
string[] split = str.Split(dateSeparator);
return new PersianCalendar().ToDateTime(short.Parse(split[0]), short.Parse(split[1]), short.Parse(split[2]), 0, 0, 0, 0);
}
public static bool IsToday(this DateTime dateTime) =>
DateTime.Today.Day == dateTime.Day && DateTime.Today.Month == dateTime.Month && DateTime.Today.Year == dateTime.Year;
public static bool IsSameHour(this DateTime dateTime) =>
dateTime.Hour >= DateTime.Now.Hour && dateTime.Hour < DateTime.Now.Hour + 1;
public static string ToBase64(this Bitmap bitmap) =>
Statics.Bitmap.ToBase64(bitmap);
public static void Log(this string message, string postfix = null) =>
Statics.Log(message, postfix);
}
// Static functions/actions as Tools
public static class Statics
{
public static class Bitmap
{
/// <value>All the codecs to cherry-pick one or two from</value>
private static readonly ImageCodecInfo[] s_codecs = ImageCodecInfo.GetImageDecoders();
/// <value>Hardcoded deafult ecoding parameters</value>
private static EncoderParameter parameter = new EncoderParameter(Encoder.Quality, 50L);
/// <value>JPEG codec encoder used to generate, compress or manipulate pictures</value>
public static ImageCodecInfo JpegCodec = GetEncoder("image/jpeg");
/// <summary>
/// Convert and compress a bitmap to its base64 encoded value.
/// </summary>
///
/// <param name="pic">Is the bitmap which gets compressed and then
/// converted to base64.</param>
///
/// <returns>The base64 string</returns>
public static string ToBase64(System.Drawing.Bitmap pic)
{
EncoderParameters encoderParameters = new EncoderParameters(1);
encoderParameters.Param[0] = parameter;
MemoryStream ms = new MemoryStream();
pic.Save(ms, JpegCodec, encoderParameters); // Compressing the pic
return Convert.ToBase64String(ms.ToArray());
}
/// <summary>
/// Get an <c>ImageCodecInfo</c> object based on a mimetype.
/// </summary>
///
/// <param name="mime">Is the mimetype name in standard format.</param>
///
/// <returns>The encoder</returns>
public static ImageCodecInfo GetEncoder(string mime)
{
foreach (ImageCodecInfo codec in s_codecs)
if (codec.MimeType == mime)
return codec;
return null;
}
}
public static Tuple<string, string> ExternalProcess(string filename, string arguments = "")
{
System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo(filename, arguments);
psi.UseShellExecute = false;
psi.CreateNoWindow = true;
psi.RedirectStandardOutput = true;
psi.RedirectStandardError = true;
psi.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
System.Diagnostics.Process process = System.Diagnostics.Process.Start(psi);
string stderr = process.StandardError.ReadToEnd();
string stdout = process.StandardOutput.ReadToEnd();
return new Tuple<string, string>(stdout, stderr);
}
[Obsolete("Use a proper logging mechanism. This exists just for the sake of backward compatibility.")]
public static void Log(string message, string postfix = null)
{
StreamWriter sw = null;
try
{
postfix = postfix == null ? "" : "_" + postfix;
sw = new StreamWriter(AppDomain.CurrentDomain.BaseDirectory + "\\process" + postfix + ".log", append: true);
sw.WriteLine(DateTime.Now.ToString() + ": " + message);
sw.Flush();
sw.Close();
}
catch { }
}
public static class ExtractAppSettingsData
{
public static string Get(string index) =>
ConfigurationManager.AppSettings.Get(index);
/// <summary>
/// If there are any properly formatted <c>{ "parent:subvar",
/// "value" }</c> entries in AppSettings, makes a dictionary out of
/// them.
/// </summary>
///
/// <param name="parent">Common prefix for sub-variables</param>
/// <param name="delimiter">The separator for spilitting parents
/// from sub-variables in the keys</param>
///
/// <returns>A dictionary containing all the variables that have a
/// common <c>parent</c></returns>
public static Dictionary<string, string> GetDictionary(string parent, char delimiter = ':')
{
Dictionary<string, string> pairs = new Dictionary<string, string>() { };
foreach (string i in ConfigurationManager.AppSettings)
{
try
{
if (parent + delimiter == i.Substring(0, parent.Length + 1))
pairs.Add(i.Substring(parent.Length + 1), Get(i));
}
catch (ArgumentOutOfRangeException)
{
// It's too short to be the candidate
}
}
return pairs;
}
/// <summary>
/// Create a dictionary out of <c>{ "parent:subvar:subsubvar", "v1"
/// }</c>s in your config where every <c>subvar</c> is a key in the
/// dictionary.
/// </summary>
///
/// <exception cref="IndexOutOfRangeException">If given parent does
/// not have any children.</exception>
public static Dictionary<string, Dictionary<string, string>> GetIndexedDictionary(string parent, char delimiter = ':')
{
List<string> subvars = new List<string>();
foreach (string i in ConfigurationManager.AppSettings)
{
string[] iSplitted = i.Split(delimiter);
if (parent == iSplitted[0])
subvars.Add(iSplitted[1]);
}
// Get all distinct parent:"subvars":key to make a dictionary for each
subvars = subvars.Distinct().ToList();
Dictionary<string, Dictionary<string, string>> pairs = new Dictionary<string, Dictionary<string, string>>() { };
foreach (string i in subvars)
pairs.Add(i, GetDictionary(parent + delimiter + i));
return pairs;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment