2014/07/29

How to convert JSON object to Dictionary in C# ?

public static Dictionary<string, string> ConvertJsonStr2Dictionary(string jsonStr)
{
Dictionary<string, string> dict = new Dictionary<string, string>();
int start = jsonStr.IndexOf("{", 1) + 2;
int stop = jsonStr.LastIndexOf("}}");
jsonStr = jsonStr.Substring(start, stop - start - 1);
string[] keyValArr = jsonStr.Split(new string[] { "," }, StringSplitOptions.None);
foreach(string keyVal in keyValArr)
{
string key = RemoveLeadingEndingQuotationMarks(keyVal.Substring(0, keyVal.LastIndexOf(":")).Trim());
string val = RemoveLeadingEndingQuotationMarks(keyVal.Substring(keyVal.LastIndexOf(":") + 1).Trim());
dict.Add(key, val);
}
return dict;
}
view raw gistfile1.cs hosted with ❤ by GitHub

How to generate bitmap from url in C# ?

public static Bitmap GenerateScreenshot(string url, int width, int height)
{
// Load the webpage into a WebBrowser control
WebBrowser wb = new WebBrowser();
wb.ScrollBarsEnabled = false;
wb.ScriptErrorsSuppressed = true;
wb.Navigate(url);
while (wb.ReadyState != WebBrowserReadyState.Complete) { Application.DoEvents(); }
// Set the size of the WebBrowser control
wb.Width = width;
wb.Height = height;
if (width == -1)
{
// Take Screenshot of the web pages full width
wb.Width = wb.Document.Body.ScrollRectangle.Width;
}
if (height == -1)
{
// Take Screenshot of the web pages full height
wb.Height = wb.Document.Body.ScrollRectangle.Height;
}
// Get a Bitmap representation of the webpage as it's rendered in the WebBrowser control
Bitmap bitmap = new Bitmap(wb.Width, wb.Height);
wb.DrawToBitmap(bitmap, new Rectangle(0, 0, wb.Width, wb.Height));
wb.Dispose();
return bitmap;
}
view raw gistfile1.cs hosted with ❤ by GitHub

How to convert byte array to string and string to byte array in C# ?

public static byte[] GetByteArrayFromString(string s)
{
byte[] bytes = new byte[s.Length * sizeof(char)];
System.Buffer.BlockCopy(s.ToCharArray(), 0, bytes, 0, bytes.Length);
return bytes;
}
public static string GetStringFromByteArray(byte[] bytesArr)
{
char[] chars = new char[bytesArr.Length / sizeof(char)];
System.Buffer.BlockCopy(bytesArr, 0, chars, 0, bytesArr.Length);
return new string(chars);
}
view raw gistfile1.cs hosted with ❤ by GitHub

How to get HTML page content programatically in C# ?

public static string ReadPageContentFromUrl(string url)
{
WebClient client = new WebClient ();
Stream data = client.OpenRead(url);
StreamReader reader = new StreamReader(data, Encoding.UTF8);
string html = reader.ReadToEnd();
Encoding encFrom = Encoding.GetEncoding(readCharactersetFromHTML(html));
html = ChangeEncoding(encFrom, Encoding.UTF8, html);
data.Close ();
reader.Close();
return html;
}
view raw gistfile1.cs hosted with ❤ by GitHub

Polish NIP validation

public static bool ValidateNip(string nip)
{
if (nip.Length != 10) return false;
try { Int64.Parse(nip); }
catch { return false; }
int[] weights = new int[] { 6, 5, 7, 2, 3, 4, 5, 6, 7 };
int sum = 0;
for (int i = 0; i < weights.Length; i++)
sum += int.Parse(nip.Substring(i, 1)) * weights[i];
return (sum % 11) == int.Parse(nip.Substring(9, 1));
}
view raw gistfile1.cs hosted with ❤ by GitHub

Email address validation in C#

Not exacly compatible with iso:
public static bool ValidateEmailAddress(string email)
{
if (email.Length > 254)
return false;
else
{
string[] emailParts = email.Split(new string[] { "@" }, StringSplitOptions.RemoveEmptyEntries);
if (emailParts.Length != 2 || email.StartsWith("@") || email.EndsWith("@") || (new Regex("[@]{2,}", RegexOptions.None)).IsMatch(email))
return false;
else
{
if (emailParts[0].Length <= 64)
{
// alias
Regex rx1 = new Regex(@"^[a-zA-Z0-9_-][a-zA-Z0-9_\.-]*[a-zA-Z0-9_-]$", RegexOptions.None);
if (emailParts[0].Length > 64 || emailParts[0].Contains("..") || !rx1.IsMatch(emailParts[0]))
return false;
}
else
return false;
// domain
Regex rx2 = new Regex(@"^[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*\.[a-zA-Z]{2,63}$", RegexOptions.None);
if (emailParts[1].Contains("--") || !rx2.IsMatch(emailParts[1]))
return false;
}
}
return true;
}
view raw gistfile1.cs hosted with ❤ by GitHub

Convert datetime to timestamp and timestamp to datetime in C#

public static readonly DateTime EpochUtc = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
public static long ConvertDatetime2Timestamp(DateTime value)
{
TimeSpan elapsedTime = value - EpochUtc;
return (long)elapsedTime.TotalSeconds;
}
public static DateTime ConvertTimestamp2Datetime(double timestampMilisec)
{
DateTime dateTime = DateTime.SpecifyKind(EpochUtc, DateTimeKind.Utc);
return dateTime.AddSeconds(timestampMilisec);
}
view raw gistfile1.cs hosted with ❤ by GitHub

How to convert encoding from one to another in C# ?

public static string ChangeEncoding(Encoding encFrom, Encoding encTo, string srcStr)
{
// Convert the string into a byte[].
byte[] fromBytes = encFrom.GetBytes(srcStr);
// Perform the conversion from one encoding to the other.
byte[] toBytes = Encoding.Convert(encFrom, encTo, fromBytes);
// Convert the new byte[] into a char[] and then into a string.
// This is a slightly different approach to converting to illustrate
// the use of GetCharCount/GetChars.
char[] toChars = new char[encTo.GetCharCount(toBytes, 0, toBytes.Length)];
encTo.GetChars(toBytes, 0, toBytes.Length, toChars, 0);
return new string(toChars);
}
view raw gistfile1.cs hosted with ❤ by GitHub

How to remove directory with all its files and subdirs recursively ?

public static void DeleteDirCompletely(string dirPath)
{
DirectoryInfo di = new DirectoryInfo(dirPath);
foreach (var file in di.GetFiles())
File.Delete(file.FullName);
foreach (var dir in di.GetDirectories())
Directory.Delete(dir.FullName);
Directory.Delete(dirPath);
}
view raw gistfile1.cs hosted with ❤ by GitHub

How to check if url is valid in C# ?

public bool IsUrlValid(string url)
{
string pattern =
@"^(http|https|ftp|)\://|[a-zA-Z0-9\-\.]+\.[a-zA-Z](:[a-zA-Z0-9]*)?/?([a-zA-Z0-9\-\._\?\,\'/\\\+&amp;%\$#\=~])*[^\.\,\)\(\s]$";
Regex reg = new Regex(pattern, RegexOptions.Compiled | RegexOptions.IgnoreCase);
return reg.IsMatch(url);
}
view raw gistfile1.cs hosted with ❤ by GitHub

How to compute MD5 in C# ?

public static string ComputeMd5(string input, bool convert2smallLetters = false)
{
MD5 md5 = MD5.Create();
byte[] inputBytes = Encoding.ASCII.GetBytes(input);
byte[] hash = md5.ComputeHash(inputBytes);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < hash.Length; i++)
{
if (!convert2smallLetters)
sb.Append(hash[i].ToString("X2"));
else
sb.Append(hash[i].ToString("x2"));
}
return sb.ToString();
}
view raw gistfile1.cs hosted with ❤ by GitHub

How to add column to table in TSQL ?

ALTER TABLE table_name
ADD column_name datatype
-- example
ALTER TABLE schClients.tSenders_
ADD Confirmed BIT NOT NULL DEFAULT 0
GO
view raw gistfile1.sql hosted with ❤ by GitHub
Syntax from msdn

2014/07/20

Generate random number in C#

Random rnd = new Random();
int dice = rnd.Next(1, 7); // creates a number between 1 and 6
int card = rnd.Next(52); // creates a number between 0 and 51
view raw gistfile1.cs hosted with ❤ by GitHub

2014/07/15

Insert Google Analitics code to Prestashop

Be carefull. You should not have any strings in your smarty template like this:
"{x.."
, because it's reserved for smarty variable and Prestashop uses smarty templates Instead use this:
"{ x...".
F.g:
<script>
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','//www.google-analytics.com/analytics.js','ga');

  ga('create', 'UA-....', 'auto');
  ga('send', 'pageview');
</script>
->
<script>
  (function(i,s,o,g,r,a,m){ i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','//www.google-analytics.com/analytics.js','ga');

  ga('create', 'UA-....', 'auto');
  ga('send', 'pageview');
</script>

2014/07/14

How to read value returned by stored procedure - TSQL ?

http://msdn.microsoft.com/en-us/library/ms188332.aspx
DECLARE @ret INT
EXEC @ret = [schImports].[uspInsertImport] 1
view raw gistfile1.sql hosted with ❤ by GitHub

CREATE PROCEDURE [schImports].[uspInsertImport] (@importId int)
AS
BEGIN
-- ...
return @insertedNew;
END
view raw gistfile1.sql hosted with ❤ by GitHub

2014/07/07

How to disconnect Skype from Microsoft or Facebook account?

Solution in polish is here

Adding two integers without temporary variable - C#

static void swamp(ref int x, ref int y)
{
x = x + y;
y = x - y;
x = x - y;
}
view raw gistfile1.cs hosted with ❤ by GitHub

Read collection from configuration file app.config in C#

App.config:
<configuration>
<configSections>
<section name="testConfig" type="Testy.ItemsConfigurationSection, Testy" />
</configSections>
<testConfig>
<items>
<item name="One" />
<item name="Two" />
</items>
</testConfig>
</configuration>
Service classes:
namespace Testy
{
public class ItemConfigurationElement : ConfigurationElement
{
[ConfigurationProperty("name", IsKey = true, IsRequired = true)]
public string Name
{
get { return (string)this["name"]; }
}
}
[ConfigurationCollection(typeof(ItemConfigurationElement), AddItemName = "item")]
public class ItemsConfigurationElementCollection : ConfigurationElementCollection
{
protected override ConfigurationElement CreateNewElement()
{
return new ItemConfigurationElement();
}
protected override object GetElementKey(ConfigurationElement element)
{
return ((ItemConfigurationElement)element).Name;
}
}
public class ItemsConfigurationSection : ConfigurationSection
{
[ConfigurationProperty("items", IsDefaultCollection = true)]
public ItemsConfigurationElementCollection Tests
{
get { return (ItemsConfigurationElementCollection)this["items"]; }
}
}
}
view raw gistfile1.cs hosted with ❤ by GitHub
Usage:
try
{
ItemsConfigurationSection configManager = (ItemsConfigurationSection)ConfigurationManager.GetSection("testConfig");
var zmienna = configManager.Tests;
}
catch (Exception ex)
{
throw;
}
view raw gistfile1.cs hosted with ❤ by GitHub