Micro Performance optimisation using If-Else
Posted: October 18, 2011 Filed under: C#.net | Tags: Conditional (programming), if-else, performance-optimization Leave a comment »This post is actually a question I asked on Stackoverflow,
The question is Which performs better if or if-else ?, this might seem to be a silly question for a few because of 2 reasons.
- If block will have relatively less lines of code, if both the blocks are having the same code, it is apparently a matter of commonsense.
- And if they are not having the same code then we should not compare them in the first place
The If Block
public long WithOnlyIf(int myFlag)
{
Stopwatch myTimer = new Stopwatch();
string someString = "";
myTimer.Start();
for (int i = 0; i < 1000000; i++)
{
string height = "80%";
string width = "80%";
if (myFlag == 1)
{
height = "60%";
width = "60%";
}
someString = "Height: " + height + Environment.NewLine + "Width: " + width;
}
myTimer.Stop();
File.WriteAllText("testif.txt", someString);
return myTimer.ElapsedMilliseconds;
}
The If-Else Block
public long WithIfAndElse(int myFlag)
{
Stopwatch myTimer = new Stopwatch();
string someString = "";
myTimer.Start();
for (int i = 0; i < 1000000; i++)
{
string height;
string width;
if (myFlag == 1)
{
height = "60%";
width = "60%";
}
else
{
height = "80%";
width = "80%";
}
someString = "Height: " + height + Environment.NewLine + "Width: " + width;
}
myTimer.Stop();
File.WriteAllText("testifelse.txt", someString);
return myTimer.ElapsedMilliseconds;
}
So Which one actually performs better, well lets look into the results
When Condition is true, the If Block took 1700 milliseconds to execute the 1000000 iterations, where as the if-else block took only 1688 milliseconds
When the conditions fails, the if scored 1677 Milliseconds which is still a bit late than the If-Else block’s 1664 Milliseconds
So the results say that If-Else performs better than If and guess according to most of SO posters the If-Else block is more readable too
Sql Query to get domain Name from email column
Posted: June 27, 2011 Filed under: SQL Server | Tags: Microsoft SQL Server, SQL, T-SQL 3 Comments »The following T-SQL Query will retrieve anything that is after the @ symbol, the query can be very useful for retrieving the domain of an email address
SELECT SUBSTRING(T.Email,(CHARINDEX('@',T.Email)+1),LEN(T.Email) - (CHARINDEX('@',T.Email))) as DomainName FROM EmailTable T
A simple C#class to implement rijndael encryption
Posted: March 26, 2011 Filed under: C#.net Leave a comment »For all those paranoids out there who fear there data might be stolen
here is a simple helper class to implemnet rijndael encryption in C#.net.
I found this code long back on the net, i added some coments and made it int a class, so if you find it usefull and know the original coder, just post a comment and let me know.
using System;
using System.IO;
using System.Text;
using System.Collections.Generic;
using System.Security.Cryptography;
namespace EasyCipher
{
public class EC_Rijndael
{
#region Encryption Stuff goes here
/// <summary>
/// Encrypts a given string using Rijndael algorithm, salted
/// </summary>
/// <param name="plain_text">The string you want to encrypt</param>
/// <param name="password">Password used for encryption</param>
///<returns></returns>
public static string Encrypt(string clearText, string Password)
{
byte[] clearBytes = System.Text.Encoding.Unicode.GetBytes(clearText);
//Don't worry about the string "~t)o!o(s@a*l#t&y", you can replace it with your own string, it is better to make it unpredictable
PasswordDeriveBytes pdb = new PasswordDeriveBytes(Password, Encoding.ASCII.GetBytes("~t)o!o(s@a*l#t&y"));
byte[] encryptedData = Encrypt(clearBytes, pdb.GetBytes(32), pdb.GetBytes(16));
return Convert.ToBase64String(encryptedData);
}
/// <summary>
/// Encrypts a given string using Rijndael algorithm
/// </summary>
/// <param name="plain_text">The string you want to encrypt</param>
/// <param name="password">Password used for encryption</param>
/// <param name="salt">Salt value in bytes to stop dictionary attack, remember the same salt value must be used to decryption</param>
///<returns></returns>
public static string Encrypt(string plain_text, string password, byte[] saltvalue)
{
byte[] plain_bytes = System.Text.Encoding.Unicode.GetBytes(plain_text);
PasswordDeriveBytes pdb = new PasswordDeriveBytes(password, saltvalue);
byte[] encrypted_data = Encrypt(plain_bytes, pdb.GetBytes(32), pdb.GetBytes(16));
return Convert.ToBase64String(encrypted_data);
}
/// <summary>
/// Encrypts a byte array, instead of string
/// </summary>
/// <param name="plain_bytes">byte array to be encrypted</param>
/// <param name="password">password for encryption</param>
/// <param name="saltvalue">Salt value is any byte array that is attached to a password to stop dictionary attack</param>
/// <returns>Encrypted byte array</returns>
public static byte[] Encrypt(byte[] plain_bytes, string password, byte[] saltvalue)
{
PasswordDeriveBytes pwd = new PasswordDeriveBytes(password, saltvalue);
byte[] encryptedData = Encrypt(plain_bytes, pwd.GetBytes(32), pwd.GetBytes(16));
return encryptedData;
}
/// <summary>
/// Encrypts a byte array, instead of string, salted
/// </summary>
/// <param name="plain_bytes">byte array to be encrypted</param>
/// <param name="password">password for encryption</param>
/// <returns>Encrypted byte array</returns>
public static byte[] Encrypt(byte[] clearBytes, string Password)
{
PasswordDeriveBytes pdb = new PasswordDeriveBytes(Password, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
byte[] encryptedData = Encrypt(clearBytes, pdb.GetBytes(32), pdb.GetBytes(16));
return encryptedData;
}
#endregion
#region Decryption Stuff Goes here
/// <summary>
/// Decyphers an encrypted string, salted
/// </summary>
/// <param name="cipher_text">Encrytped string to be deciphered</param>
/// <param name="password">password used for encrypting string</param>
/// <returns>Plain deciphered string</returns>
public static string Decrypt(string cipherText, string Password)
{
byte[] cipherBytes = Convert.FromBase64String(cipherText);
//Don't worry about the string "~t)o!o(s@a*l#t&y", you can replace it with your own string, it is better to make it unpredictable
PasswordDeriveBytes pdb = new PasswordDeriveBytes(Password, Encoding.ASCII.GetBytes("~t)o!o(s@a*l#t&y"));
byte[] decryptedData = Decrypt(cipherBytes, pdb.GetBytes(32), pdb.GetBytes(16));
return System.Text.Encoding.Unicode.GetString(decryptedData);
}
/// <summary>
/// Decyphers an encrypted string
/// </summary>
/// <param name="cipher_text">Encrytped string to be deciphered</param>
/// <param name="password">password used for encrypting string</param>
/// <param name="saltvalue">Salt value is any byte array that is attached to a password to stop dictionary attack</param>
/// <returns>Plain deciphered string</returns>
public static string Decrypt(string cipher_text, string password, byte[] saltvalue)
{
byte[] cipher_bytes = Convert.FromBase64String(cipher_text);
PasswordDeriveBytes pdb = new PasswordDeriveBytes(password, saltvalue);
byte[] decrypted_data = Decrypt(cipher_bytes, pdb.GetBytes(32), pdb.GetBytes(16));
return System.Text.Encoding.Unicode.GetString(decrypted_data);
}
/// <summary>
/// Decyphers an encrypted byte array, salted
/// </summary>
/// <param name="cipher_bytes">Encrytped byte array to be deciphered</param>
/// <param name="password">Salt value is any byte array that is attached to a password to stop dictionary attack</param>
/// <returns></returns>
public static byte[] Decrypt(byte[] cipherBytes, string Password)
{
//Don't worry about the string "~t)o!o(s@a*l#t&y", you can replace it with your own string, it is better to make it unpredictable
PasswordDeriveBytes pdb = new PasswordDeriveBytes(Password, Encoding.ASCII.GetBytes("~t)o!o(s@a*l#t&y"));
byte[] decryptedData = Decrypt(cipherBytes, pdb.GetBytes(32), pdb.GetBytes(16));
return decryptedData;
}
/// <summary>
/// Decyphers an encrypted byte array
/// </summary>
/// <param name="cipher_bytes">Encrytped byte array to be deciphered</param>
/// <param name="password">Salt value is any byte array that is attached to a password to stop dictionary attack</param>
/// <param name="saltvalue">Plain deciphered byte array</param>
/// <returns></returns>
public static byte[] Decrypt(byte[] cipher_bytes, string password, byte[] saltvalue)
{
PasswordDeriveBytes pdb = new PasswordDeriveBytes(password, saltvalue);
byte[] decrypted_data = Decrypt(cipher_bytes, pdb.GetBytes(32), pdb.GetBytes(16));
return decrypted_data;
}
#endregion
#region Private Encryption Methods
private static byte[] Encrypt(byte[] plain_bytes, byte[] Key, byte[] IV)
{
MemoryStream ms = new MemoryStream();
Rijndael alg = Rijndael.Create();
alg.Key = Key;
alg.IV = IV;
CryptoStream cs = new CryptoStream(ms, alg.CreateEncryptor(), CryptoStreamMode.Write);
cs.Write(plain_bytes, 0, plain_bytes.Length);
cs.Close();
byte[] encrypted_data = ms.ToArray();
return encrypted_data;
}
private static byte[] Decrypt(byte[] cipherData, byte[] Key, byte[] IV)
{
MemoryStream ms = new MemoryStream();
Rijndael alg = Rijndael.Create();
alg.Key = Key;
alg.IV = IV;
CryptoStream cs = new CryptoStream(ms, alg.CreateDecryptor(), CryptoStreamMode.Write);
cs.Write(cipherData, 0, cipherData.Length);
cs.Close();
byte[] decrypted_data = ms.ToArray();
return decrypted_data;
}
#endregion
}
}
2010 in review
Posted: January 2, 2011 Filed under: General | Tags: WordPress.com, Yearly Review Leave a comment »The stats helper monkeys at WordPress.com mulled over how this blog did in 2010, and here’s a high level summary of its overall blog health:

The Blog-Health-o-Meter™ reads This blog is doing awesome!.
Crunchy numbers

A helper monkey made this abstract painting, inspired by your stats.
A Boeing 747-400 passenger jet can hold 416 passengers. This blog was viewed about 3,300 times in 2010. That’s about 8 full 747s.
In 2010, there were 10 new posts, growing the total archive of this blog to 16 posts. There was 1 picture uploaded, taking a total of 33kb.
The busiest day of the year was October 27th with 60 views. The most popular post that day was Implementing oauth twitter search in C# and JSON.
Where did they come from?
The top referring sites in 2010 were in.answers.yahoo.com, google.co.in, google.com, ead.ipleiria.pt, and mail.live.com.
Some visitors came searching, mostly for oauth twitter c#, twitter oauth c#, check domain availability in c sharp, coderbuddy, and c# twitter search.
Attractions in 2010
These are the posts and pages that got the most views in 2010.
Implementing oauth twitter search in C# and JSON August 2010
8 comments
C# code to publish, delete, retrieve tweets using oauth August 2010
1 comment
Changing array length at runtime in C#.net October 2009
3 comments
A simple C# class to get whois information October 2010
4 comments
C# code to extract Email October 2009
2 comments
Auto increment using identity in SQL Server
Posted: November 1, 2010 Filed under: SQL Server | Tags: auto increment in sql server, Data type, FAQs Help and Tutorials, identity property, Microsoft SQL Server, SQL, Table (database) Leave a comment »Auto increment feature can be implemented very easily in an SQL server table using the IDENTITY property.
The following query can be used for creation of one such table that can implement auto increment feature on one of its columns
CREATE TABLE EMPLOYEE(EID INT IDENTITY(1,1), ENAME VARCHAR(30), E_DOB DATETIME)
when the above query is executed, a table with the name EMPLOYEE is created with a column EID whose values are auto incremented.
Syntax
The syntax of the identity property is very simple
DataType IDENTITY [ (seed ,increment) ]
DataType : Identity only supports INT, BIGINT, SMALLINT, TINYINT, DECIMAL data types
seed: seed is the value that is assigned for the first row that is loaded into the table
increment: Is the incremental value that is added to the identity value of the previous row that was loaded.
seed and increment are optional, but not individually, that means we have to either specify both the values or none of them.
If the values are not provided for seed and increment than the default values of (1, 1) are taken
For more information on IDENTITY property visit http://msdn.microsoft.com/en-us/library/aa933196(SQL.80).aspx
Domain name search in C#
Posted: October 13, 2010 Filed under: C#.net | Tags: C# whois, C#.net article, C#.net code, Domain name, Domain name registry, domain search C#, domain search sdk C#, how to domain search, Name Search, Whois Leave a comment »I always wondered how the big domain registration companies searched for domain availability, but thanks to the advice of Anthony of http://bruteforcenaming.com who kindly responded to my childish question of how do you do it ?
Based on his advice of using the whois lookup to search for domain availability, i wrote a C# class to lookup whois information and a domain search class, which i am sharing with you now
Note: this class uses the whois lookup class, i posted earler on my blog at http://coderbuddy.wordpress.com/2010/10/12/a-simple-c-class-to-get-whois-information/, so for all of you who want to use this class, first go check my post on whois class or you can download the complete source code by clicking the download button at the bottom of this post.
public class DomainSearch
{
/// <summary>
/// Check whether a given domain name is available or not
/// </summary>
/// <param name="domainname">daomain name to be verified</param>
/// <param name="whois_server_address">use null value (that is "") or "whois.internic.net" if you dont know any whois servers</param>
/// <returns></returns>
public static bool isAvailable(string domainname,string whois_server_address)
{
List<string> ws = Whois.lookup(domainname, Whois.RecordType.domain, whois_server_address);
return ws[7].Contains("No match for domain \"" + domainname.ToUpper() + "\".");
} }
Click the download button bellow to download the complete source code (Visual studio 2005, C#.net, Windows Class Library Project) including the whois lookup class.
A simple C# class to get whois information
Posted: October 12, 2010 Filed under: C#.net | Tags: C# whois, create whois tool for windows, domain search C#, whois API, whois lookup C# 6 Comments »I have searched on the web and found C# classes to obtain whois information, but none of those classes has addressed my issue of obtaining only the domain information, for example if i search for whois information of microsoft.com using the code available on the net you will also get all the name servers that have microsoft in the name.
None of the code i saw addressed the issue of excluding the name servers from the list and only obtaining the whois information for the domain name. So after a bit of research and coding this is what i got, i am sharing it with you. I will be very happy if it is of some use to anybody
using System;
using System.IO;
using System.Text;
using System.Net.Sockets;
using System.Collections.Generic;
namespace WebTools
{
/// <summary>
/// A class to lookup whois information.
/// </summary>
public class Whois
{
public enum RecordType { domain, nameserver, registrar };
/// <summary>
/// retrieves whois information
/// </summary>
/// <param name="domainname">The registrar or domain or name server whose whois information to be retrieved</param>
/// <param name="recordType">The type of record i.e a domain, nameserver or a registrar</param>
/// <returns>The string containg the whois information</returns>
public static string lookup(string domainname, RecordType recordType)
{
List<string> res = lookup(domainname, recordType, "whois.internic.net");
string result = "";
foreach (string st in res)
{
result += st + "\n";
}
return result;
} /// <summary>
/// retrieves whois information
/// </summary>
/// <param name="domainname">The registrar or domain or name server whose whois information to be retrieved</param>
/// <param name="recordType">The type of record i.e a domain, nameserver or a registrar</param>
/// <param name="returnlist">use "whois.internic.net" if you dont know whoisservers</param>
/// <returns>The string list containg the whois information</returns>
public static List<string> lookup(string domainname, RecordType recordType, string whois_server_address)
{
if (whois_server_address == "")
whois_server_address = "whois.internic.net";
TcpClient tcp = new TcpClient();
tcp.Connect(whois_server_address, 43);
string strDomain = recordType.ToString() + " " + domainname + "\r\n";
byte[] bytDomain = Encoding.ASCII.GetBytes(strDomain.ToCharArray());
Stream s = tcp.GetStream();
s.Write(bytDomain, 0, strDomain.Length);
StreamReader sr = new StreamReader(tcp.GetStream(), Encoding.ASCII);
string strLine = "";
List<string> result = new List<string>();
while (null != (strLine = sr.ReadLine()))
{
result.Add(strLine);
}
tcp.Close();
return result;
}
}
}
You can use obtain the whois information by simple using the following code
string info = Whois.lookup("google.com", Whois.RecordType.domain);
or you can alternatively use
List<string> info = Whois.lookup("google.com", Whois.RecordType.domain, "whois.internic.net");
This post is first published on coderbuddy.wordpress.com.
I will try and post a entry about whois queries, for those who are interested go to coderbuddy Home
Click the download button bellow to download the complete source code (Visual studio 2005, C#.net, Windows Class Library Project) including the C# class to search for domain name search using whois information.
- What is WHOIS? (brainz.org)
- WHOIS database hacked – Who is behind it and how could it happen? (sophos.com)
- Another Expanded Whois Service (firstrate.co.nz)
- Identifying a Website Owner Using Whois (brighthub.com)
Microsoft releases WebMatrix Beta
Posted: July 7, 2010 Filed under: ASP.net, Dev Tools | Tags: IIS Express, New ASP.net Features, WebMatrix 2 Comments »Microsoft has released WebMatrix Beta, it is a collection of tools that will be help you develop a web application with minimal effort.The tools included in this package are IIS Developer Express (a development Web server), ASP.NET, and SQL Server Compact (an embedded database). A web server, a Web Framework, a database that’s almost everything a developer may need to create a simple dynamic web pages.
Microsoft also introduces a new way to embedding C#/VB code directly into your HTML with a new Viewing Engine called Razor or APS.net Razor
An example code using razor will look something like this
<h1>Razor Example Code</h1><br/>
Hello @name, the year is @DateTime.Now.Year
The equalent ASPX code may look something like this
<h1>ASPX Page Example</h1><br />Hello <%=name %>, the year is <%= DateTime.Now.Year %>
For more on this topic visit WebMatrix, Introduction to Razor and to download webmatrix go to http://www.microsoft.com/web/webmatrix/
Microsoft has also selected a few web hosts that can host web pages using this new technology, to see the list go to http://www.microsoft.com/web/webmatrix/learn/ and scroll down to the section called “Recommended web hosts”.Since this is still in beta you may experience some bugs, so use it with caution.


