Monday, 19 November 2012

How to mitigate framesniffing with the X-Frame-Options header?

Understanding the Security Issue:
Imagine you have a page on your website, mypage1.aspx. This page can be hosted in an iframe and be shown on any pages and under any external domains and by anyone.

The problem is that when a page is hosted in an iframe, the parent page can steal the data which is communicated on the iframe page which means a decent attacker can benefit from this vulnerability.

One possible solution to prevent these kind of security issues (doesn't work for old browsers) is to configure your IIS so that it only allows a page only being iframed in the domains you trust and prevent all other domains.

To restrict all external domains:

Put the below Field/Value pairs in the HTTPHeaders tab of your IIS Folder which contains your page:

X-Frame-Options = SAMEORIGIN
To allow an external domain:

X-Frame-Options = ALLOW-FROM

  • Instead of adding the X-FRAME-OPTIONS on the site root, put it on each page which requires being protected.
  • For each page or folder, you can only specify one of the three main header values of "DENY, "ALLOW-FROM" or "SAMEORIGIN". You can't mix them unfortunately.
  • ALLOW-FROM does support only 1 origin, not multiple.
  • In IIS 6.0 you can put the header on each page needed but in IIS 7.0 it's not possible via IIS; the workaround for IIS 7.0 is via serverside code for the page.
  • Not all browsers support it. IE 8+ and some other browsers. More details:
More details:

Friday, 9 November 2012

How to use Recaptcha?

List of IP Addresses used:

Create a public and private key for your domain:

Then the below code manages everything you'd need not based on the Session attempts but Application attempts:

public class RecaptchaManager
  #region Local variables

  private static volatile RecaptchaManager _instance;
  private static readonly object SyncRoot = new Object();
  private readonly Byte _maxNumberOfValidFailedAttempts;

  private readonly Byte _durationInMinutes;
  private readonly int _cleanUpMaxSize;
  private readonly string _privateKey;
  private readonly string _publicKey;
  private readonly List _result = new List();

  /// Be careful where and how the locks are used to avoid deadlocks or inter locks.
  private readonly Object _lockObject = new object();


  #region Constructors and class initialization

  private RecaptchaManager()
   if (!Byte.TryParse(SettingHelper.Instance["Recaptcha.ValidFailedAttempts.MaxNumber"], out _maxNumberOfValidFailedAttempts))
    throw new ApplicationException("Invalid or non-existent config key: Recaptcha.ValidFailedAttempts.MaxNumber");

   if (!Byte.TryParse(SettingHelper.Instance["Recaptcha.ValidFailedAttempts.DurationInMinutes"], out _durationInMinutes))
    throw new ApplicationException("Invalid or non-existent config key: Recaptcha.ValidFailedAttempts.DurationInMinutes");

   if (!int.TryParse(SettingHelper.Instance["Recaptcha.CleanUp.MaxSize"], out _cleanUpMaxSize))
    throw new ApplicationException("Invalid or non-existent config key: Recaptcha.CleanUp.MaxSize");

   // private key
   this._privateKey = SettingHelper.Instance["Recaptcha.PrivateKey"];

   if (string.IsNullOrWhiteSpace(this._privateKey))
    throw new ApplicationException("Invalid or non-existent config key: Recaptcha.PrivateKey");

   this._publicKey = SettingHelper.Instance["Recaptcha.PublicKey"];

   if (string.IsNullOrWhiteSpace(this._publicKey))
    throw new ApplicationException("Invalid or non-existent config key: Recaptcha.PublicKey");


  #region Properties

  public static RecaptchaManager Instance
    if (_instance == null)
     lock (SyncRoot)
      if (_instance == null)
       _instance = new RecaptchaManager();

    return _instance;

  public string PublicKey
   get { return this._publicKey; }


  #region public Methods

  public void AddFailedLoginAttempt()
   // we may want to customize these

  public void AddFailedRegistrationAttempt()
   // we may want to customize these

  public bool ShouldRequireRecaptcha()
   return getNumberOfFailedAttemptsDuringThePeriod() > this._maxNumberOfValidFailedAttempts;

  public bool IsRecaptchaAvailableOnPage()
   // if this field exists then the Recaptcha is available
   string challengeValue = Utils.GetStringForm("recaptcha_challenge_field", null);
   return challengeValue != null;

  public bool IsInputValueVerified()
   string challengeValue = Utils.GetStringForm("recaptcha_challenge_field", null);
   string responseValue = Utils.GetStringForm("recaptcha_response_field", null);
   bool result = false;

    var captchaValidtor = new RecaptchaValidator()
     // put it in web.config
     PrivateKey = this._privateKey,

     RemoteIP = HttpContext.Current.Request.UserHostAddress,

     Challenge = challengeValue,

     Response = responseValue

    result = captchaValidtor.Validate().IsValid;
   catch { }

   return result;


  #region Private functions
  private void addFailedLoginOrRegistrationAttempt()
   lock (this._lockObject)
    if (this._result.Count > this._cleanUpMaxSize)


  /// Removes the old data.
  private void removeOldData()
   DateTime startDateTime = getStartDateTime();
   this._result.RemoveAll(item => item < startDateTime);

  private int getNumberOfFailedAttemptsDuringThePeriod()
   DateTime startDateTime = getStartDateTime();

   lock (this._lockObject)
    return this._result.Count(failedAttemp => failedAttemp > startDateTime);

  private DateTime getStartDateTime()
   return DateTime.Now.AddMinutes(-this._durationInMinutes);


Wednesday, 31 October 2012

How to implement Hard Session Expiry in ASP.NET?

Hard Session Expiry means, the session must expire e.g. after 4 hours.

You could write the below code in the global.ascx file:

private const string MyDeadlineSessionKey = "MyDeadline";

 private static readonly int SessionDeadlineInMinutes = initializeSessionDeadline();
 private static int initializeSessionDeadline()
  string sessionDeadlineInString = SettingHelper.Instance.GetFromConfigManager("SessionDeadlineInMinutes");
  int sessionDeadlineInInt = 60; // 1 hour by default
  int.TryParse(sessionDeadlineInString, out sessionDeadlineInInt);
  return sessionDeadlineInInt;

 void Application_PreRequestHandlerExecute(object sender, EventArgs e)
  HttpSessionState session = HttpContext.Current.Session;

  // not all requests have session
  if (session != null && session[MyDeadlineSessionKey] != null)
   var myDeadline = DateTime.Parse(session[MyDeadlineSessionKey].ToString());

   if (DateTime.Now.Subtract(myDeadline).TotalMinutes > 0)

 void Session_Start(object sender, EventArgs e)
  // the value will be read from config file
  Session.Add(MyDeadlineSessionKey, DateTime.Now.AddMinutes(SessionDeadlineInMinutes));

Wednesday, 5 September 2012

Code Generators and ORMs for .NET

  1. Free, not trial
  2. It uses repository pattern to generate the data access
  3. It generates the UI Elements, data access, everything.
  4. Supports creating web, windows, etc applications.
  5. Perhaps the quickest way to build an application!
ADO.NET Entity Framework
  • Visual Studio needed
  • An ORM tool
ASP.NET Dynamic Data
  • Easily and quickly creating data centric web applications from a database.
  • Supports LING to SQL or LINQ and Entity Framework
  • Generates also the UI elements at runtime.
Commercial ones:

Code Complete

Code Smith

Friday, 17 August 2012

Create a Certificate with .Cer and .Pfx files

makecert -r -pe -n "CN=CompanyXYZ Server" -b 01/01/2007 -e 01/01/2010 -sky exchange Server.cer -sv Server.pvk

pvk2pfx.exe -pvk Server.pvk -spc Server.cer -pfx Server.pfx

the .pfx file contains the private key whereas the .cer file contains the public key.

Friday, 6 July 2012

.NET Application Troubleshooting

There are some experts providing troubleshooting services to enhance your application memory usage and performance. One of which is
  • Memory Issues
  • Performance issues

Thursday, 21 June 2012

Memory Management - Value Types and Reference Types
  • The main job of Stack is to keep track of what's executing in our code in a last in first out basis (LIFO).
  • The main job of Heap is to keep track of our objects, data and information.
  • An Orphan Object in Heap is an object, candidate for garbage collection, with no pointer to it.
  • A Reference Type always goes on the Heap.
  • When we are using Reference Types, we're dealing with Pointers to the type, not the thing itself.
  • Value Types and Pointers always go where they were declared. more complex.
  • A Value Type declared within the body of a method, will be placed on the stack.
  • A Value Type declared outside of a method but inside a Reference Type, will be placed within the Reference Type on the Heap.
  • A pointer to a Reference Type declared whithin a method body, will be placed on the stack.
  • A pointer to a Value Type declared whithin a method body, will be placed on the stack.
  • Items are first get deleted from Stack, then orphan items are deleted from Heap using GC
  • When we're using Value Types, we're using the thing itself. 


Tuesday, 27 March 2012

Security Testing

Imagine you have an important website, how could you make sure that it's safe in all aspects of it?!

this Company can help: running security tests on your site including SQL Injection, etc.

Monday, 19 March 2012

An Extension Method to Convert a Type to another Type

public static class ObjectExtensions
public static class ObjectExtensions
        public static T To(this object obj)
            if (obj == DBNull.Value || obj == null)
                return default(T);

            Type newType = typeof(T);
            Type underLyingNewType = Nullable.GetUnderlyingType(newType);

            if (underLyingNewType == null)
                // it means it's not a nullable type, so just convert it as normal
                return (T)Convert.ChangeType(obj, newType);

            // it's a nullable type so convert it to the underlying type.
            return (T)Convert.ChangeType(obj, underLyingNewType);
And you can use it simply like:
        public void TypeConversionTest()
            var dbNullValue = DBNull.Value;
            var stringValue = "12";

            var convertedToDateTime = dbNullValue.To();
            var convertedToNullableDateTime = dbNullValue.To();
            var stringConvertedToNullableInt = stringValue.To();

Friday, 24 February 2012

How to Convert a Value to a Type when both defined in String?

static void Main(string[] args) {
Object result =
"System.Nullable`1[[System.DateTime, mscorlib, Version=, Culture=neutral, PublicKeyToken=b77a5c561934e089]]",
"2012-02-23 10:00:00");

public static Object ConvertValue(string typeInString, string value) {
Type originalType = Type.GetType(typeInString);

var underlyingType = Nullable.GetUnderlyingType(originalType);

// if underlyingType has null value, it means the original type wasn't nullable
object instance = Convert.ChangeType(value, underlyingType ?? originalType);

return instance; } 

Wednesday, 15 February 2012

How to Create QR Code Image Using Google API?

Make a request to this page:

chl query string gets a url then the page generates a code like below:

Then using a QR Code reader (an app on your mobile), you can scan this image and it takes you to this url.

Friday, 3 February 2012

All You'd Need to Know About String Type in C#

  • string is an alias for the String object which means they are equivalent.
  • String object is an Immutable Reference Type because it inherits directly from System.Object.
  • String object is not a Value Type because it doesn't inherit from System.ValueType (although the ValueType itself inherits from System.Object ultimately) but behaves like a Value Type.
  • A String object is internally stored as a Read-Only Collection of Char Objects.
What Does it Mean "String Object is Immutable"?
It simply means that once the object is defined, it can not be changed internally. If you change its value once initialized, then a new String Object will be created and the old one becomes ready for Garbage Collection.

In What Way a String Object Behaves Like a Value Type?
  1. Equality Operators "==", compares the value within the 2 String Objects like Value Types and unlike other Reference Types.
How was it achieved?
Well, you can override any operator that you like in classes including the Equality and Inequality operators. This is how:
public static bool operator ==(
    string a,
    string b
public static bool operator !=(
    string a,
    string b

In What Way a String Object Behaves like a Reference Type?
It has a reference and an actual object.
  1. Parameter Passing: When you pass a String object to a method as an input parameter, its reference is copied and passed while the object stays the same (in the String Intern Pool).
  2. In assignments, It makes a copy of the pointer and points to the same object in the String Intern Pool. String.Clone() also just returns a reference to the same String Object.
static string messageVar = "C#";
public static void Main(string[] args)
    bool isSame = Test(messageVar); //true

    // what about in assignement?
    string messageVar2 = messageVar;
    isSame = Object.ReferenceEquals(messageVar2, messageVar);//also true
public static bool Test(string messageParam)
    // logic
    bool isSame = Object.ReferenceEquals(messageParam, messageVar);
    return isSame;
What is String Intern Pool?
Where String objects are cached to achieve better memory management.


Thursday, 2 February 2012

How to Create and Use A Twitter Application?

On Twitter, everyone knows that you can create User Accounts but not everyone knows that you can also create Applications!

Twitter Applications can be used to send automatic tweets or re-tweets to other user accounts that have authorized this application to post tweets on their wall!

Examples Where Can It Be Used?
  • For example, you have a page on your site and you'd like to allow the user, who has logged on to your system, to send the link to your page on his/her twitter account.
  • Assuming you have a system which publishes articles, posts, videos and other types of contents onto a different website or webservice. Using a Twitter Application, you can automatically post a message unto your Company Twitter Account that such contents have been released. 
  • Imagine Burger King publishes Promotional Offers on their website, using a Twitter Application, they can publish such offers to their Company Twitter Account automatically when such offers become available.
  • Imagine BBC has a Twitter Account e.g. BBC_Business and every news that they publish unto their website, they'd like to be published automatically to this Twitter Account. Using Twitter that would be possible.
  • ...
I think any Company which publishes news/articles/information could potentially benefit from this.

How to Create a Twitter Application?
Each Twitter User can create 1 or more Twitter Applications. To create a new Application for your account go here:

What are Consumer Tokens?
Once your Twitter Application is created, it generates 2 main keys called ConsumerKey and ConsumerSecretKey.

These 2 keys will be used later so that you can authorize this app to post to a user account.

What are the Access Tokens?
Access tokens are 2 tokens using which you allow a Twitter Application to have access or post tweets on another Twitter Account; therefore Each Access Token Pair belongs to only one Twitter User Account and one Twitter Application.

How to Create Access Tokens?
The below page, would generate the the access tokens for a given application.

How to Connect to the Twitter API and Get User Details or Tweet?
Ok, by now you have 4 keys; 2 Consumer Tokens and 2 Access Tokens.

Download Twitterizer, using which you can communicate with the Twitter API.

Once you have those 4 keys and you have the Twitterizer, now you can do what you want. Posting an update to a user account using the newly created Twitter Application:

Another Tutorial:

Wednesday, 1 February 2012

NUnit with TeamCity, Working with IFrames When Writing System Tests

System tests are structured differently than normal unit tests in the sense that we won't have specific Arrange/Act/Verify sections. System tests have to test whether the whole process works correctly and can contain many steps.

public void LoginRegisterPage_WithValidEmailAddress_ShouldSendReminderEmail()

// go to loginregister url

// click the forgotten password
this.ClickElementByLinkText("Forgotten your password?");

// enter your email address
this.TypeInTextBox("PasswordResetRequest1_PasswordResetRequest_Username", TestEmailAddress);
DateTime dateTimeBeforeSubmit = DateTime.Now;

// click submit

// assert Thank You

// wait for 2sec

// Find the email log from database
string urlForResettingPassword = getPasswordReminderUrl(dateTimeBeforeSubmit);

// navigate to the url

string newPassword = this.generateRandomPassword();
// enter a new password

this.TypeInTextBox("PasswordReset1_PasswordReset_Password", newPassword);
this.TypeInTextBox("PasswordReset1_PasswordReset_PasswordConfirmation", newPassword);

// click submit

// Thank you exists
var pageTitle = this.FireFoxWebDriver.FindElement(By.XPath(@"//div/h1"));

Assert.AreEqual("Thank you", pageTitle.Text);

// go to the login page


// login using the new password
this.TypeInTextBox("UserLogin1_UserLogin_Username", TestEmailAddress);
this.TypeInTextBox("UserLogin1_UserLogin_Password", newPassword);

// verify whether the login was successful

Wednesday, 25 January 2012

Automated System/Functional/UI Testing

What tools could we use to create automated system tests using C# code? Or sometimes to record/replay UI activity?

Note: these are just my findings so far, they may change...

Test Complete

  • Commercial but very good

  • Free
  • Using which you can write C# test code and interact with the UI elements; entering text, clicking, etc.
  • Very easy to use for a C# Developer within Visual Studio.
  • Multibrowser support including IE.
  • Has no IDE.
  • Packaged with Nugget.
  • No native xpath support unlike Selenium.
  • Doesn't support record/replay natively; however, you could try using WatiN Test Recorder to record and replay your site by IE 6.0! Therefore, Selenium is better in this sense.
  • Unlike Selenium, it automatically waits for the page to finish loading, and can detect when it's finished loading.
Selenium WebDriver:
Visual Studio Ultimate/Premium Edition:

  • Allows load testing functional behaviour and measure performance.
  • Allows us to record and replay user activity on the page
  • Good for load and performance testing

Thursday, 5 January 2012

Code Reviewing

Who does it?
  • The tech expert within the team or
  • All team members?
When is it done?
  • Every time a code is checked in by a team member or
  • Only once or twice a week at a certain time
  • Check whether the code design could be improved or is good enough?
    • Readability
    • Maintainability
    • Low coupling
    • Reusability
    • ...
  • Check whether the code performance could be improved?
  • Check for any Code Smells
    • Code duplication
    • Long methods
    • Large classes
    • ...
How is it done?
  • Manually or
  • By a tool depending on your source control e.g. TFS or Subversion