HTTP Error 500.50 – URL Rewrite Module Error. The server variable is not allowed to be set.

I recently got this error when updating my rewrite rules in my system.webServer node of my web.config. The error message stated “HTTP Error 500.50 – URL Rewrite Module Error. The server variable “SERVER_PORT” is not allowed to be set. Add the server variable name to the allowed server variable list.”

Here is how you add a server variable using IIS

STEP 1 :

In your IIS with your website selected, select URL Rewrite option step1


Next select the View Server Variable option step2


Add server variable as shown below step3

Alternately you could also add through your web.config like below under <system.webServer></system.webServer> node.

<allowedServerVariables xdt:Transform="Insert">
    <add name="SERVER_PORT" />
    <add name="REMOTE_ADDR" />

Reading from a file hosted on a server using C#

This post describes how to read a file which is hosted on server i.e on some url.

Let’s say I have a .txt file hosted here – I want my code to read from this hosted file. Below is how you do it using WebClient class.

var urlToReadFrom = ""
using(var client = new WebClient()) {
    string s = client.DownloadString(urlToReadFrom);
    return s;

Hope this helps.

Convert a List of items to an XElement in C#

I have always used XElement.Parse() and StringBuilder to create an XElement of a required type. Today I came across this post on some blog and then this thread on stackoverflow which show how to do the same in a more efficient manner. Sharing it here hope this helps.

Requirement 1:



List <int> numbers = new List <int> () {
    1, 2, 3, 4, 5
XElement element = new XElement("students", numbers.Select(i = > new XElement("student", i)));

Requirement 2:

    <student number="1"></student>
    <student number="2"></student>
    <student number="3"></student>
    <student number="4"></student>
    <student number="5"></student>

C# Code:

List <int> numbers = new List <int> () {
    1, 2, 3, 4, 5
var xelement = new XElement("students");
foreach(var item in numbers) {
    xelement.Add(new XElement("student", new XAttribute("number", item)));

Serialize a List of Object to JSON in C#

This can be easily be done using Json.NET. Json.NET is a popular high-performance JSON framework for .NET.

First of all, you will need to download the latest binary from here and include it your project.

using Newtonsoft.Json;

Rest of the code is pretty self explanatory…

public class Employee
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Age { get; set; }

var employees = new List<Employee>
    new Employee {FirstName = "Yasser", LastName = "Shaikh", Age = 26},
    new Employee {FirstName = "Mohsin", LastName = "Shaikh", Age = 22},
    new Employee {FirstName = "Riaz", LastName = "Shaikh", Age = 50}

var jsonSerialiser = new JavaScriptSerializer();
var json = jsonSerialiser.Serialize(employees);

Writing your 1st HttpModule in ASP.NET under 2 minutes

What is a HttpModule ?

An HTTP module is an assembly that is called on every request made to your application. HTTP modules are called as part of the ASP.NET request pipeline and have access to life cycle events throughout the request. HTTP modules therefore give you the opportunity to examine incoming requests and take action based on the request. They also give you the opportunity to examine the outbound response and modify it.

ASP.NET HTTP modules are similar to ISAPI filters in that they run for all requests. However, they are written in managed code and are fully integrated with the life cycle of an ASP.NET application.

Typical uses for HTTP modules include:

  • Security
  • Statistics and logging
  • Custom headers or footers

In simpler words, An HTTP Module lets you add code that will be run every time a page is requested, so it’s a great solution for adding custom security checks.

Creating an HTTP Module

public class IsLocalHostHttpModule:IHttpModule
    public void Init(HttpApplication context)
        context.BeginRequest += new EventHandler(HandleBeginRequest);

    public void HandleBeginRequest(object source, EventArgs e)
        HttpContext context = ((HttpApplication)source).Context;
        string ipAddress = context.Request.UserHostAddress;
        if (ipAddress != "::1" || ipAddress != "")
            context.Response.StatusCode = 403;

    public void Dispose() {}

Registering an HTTP Module

            <!-- full qualified name should be mentioned in type -->


Implementing reCAPTCHA in your ASP.NET MVC Project

What is reCAPTCHA ?

A reCAPTCHA is a program that protects websites against bots by generating and grading tests that humans can pass but current computer programs cannot. For example, humans can read distorted text as the one shown below, but current computer programs can’t. Know more…

img intro

Step 1 – Create a Recaptcha Key

The first thing you need to do is retrieve your public and private keys from reCAPTCHA, these can easily be retrieved by signing up here.

On signup, you will be asked to enter a domain where you intend to use reCAPTCHA, fill in your domain name and press the ‘Create Key’ button.

Note: By default, all keys work on “localhost” (or “”) so you can always develop and test on your local machine.

img signup

Once done with this,you will get your public key and private key for your registered application. Keep it safe with you for now, we will be need them later.

Step 2 – Install Recaptcha for .NET

Now go to your ASP.NET MVC application and open your NuGet Package Manager by right clicking on your project and selecting the “Manage NuGet Packages…” option. Search for recaptcha for .NET and install it. Make sure you download the one shown in the screenshot below as there were plenty others with the same name.

img nuget install

As soon as the installation is complete, you will notice that a change is made to your web.config file, the following fields gets added to your <appSetting> section. Enter the public and private key you had got by registering your app at‎.


    <add key="recaptchaPublicKey" value="" />
    <add key="recaptchaPrivateKey" value="" />

Step 3 – Add the Recaptcha Control to Your MVC View

Open your Views/Account/Register view and add this to the top of the page

@using Recaptcha.Web.Mvc

and include the recaptcha form using the following razor code


Step 4 – Verify User’s Response to Recaptcha Challenge in your Controller/Action

Next step is to configure recaptcha in your controller/action, start with importing the following namespaces in your controller file (AccountController for this example)

using Recaptcha.Web;
using Recaptcha.Web.Mvc;

Next, go to your Register method and use the following code

RecaptchaVerificationHelper recaptchaHelper = this.GetRecaptchaVerificationHelper();

if (String.IsNullOrEmpty(recaptchaHelper.Response))
    ModelState.AddModelError("", "Captcha answer cannot be empty.");
    return View(model);

RecaptchaVerificationResult recaptchaResult = recaptchaHelper.VerifyRecaptchaResponse();

if (recaptchaResult != RecaptchaVerificationResult.Success)
    ModelState.AddModelError("", "Incorrect captcha answer.");

Ready To TEST ?

enter image description here

Run your application and go to your Register page and you now can see the recaptcha form on your register form.

Hope this helps. Any suggestions/feedback/queries if any are welcomed using the comments section below. Cheers!


Using Facebook Login with ASP.NET MVC 4

Login with Facebook is a very common feature that you will come across on the registration/login page on almost all good websites. ASP.NET MVC 4 includes support for OAuth and OpenID providers. Using these providers, you can let users log into your site using their existing credentials from Facebook, Twitter, Microsoft, and Google.

MVC 4 – Starter Template

This image shows the Login page from the Starter Site template, where a user can choose a Facebook, Twitter, Google or Microsoft icon to enable logging in with an external account:

img - starter template

However, In this blog post we will only be discussing about Facebook for Login.

Register your Website with Facebook

To authenticate users with their Facebook credentials, you must register your website with the Facebook. Head to and in the menu bar select App > Create a New App. You will be greeted with the below screen and a captcha. Once done you will be redirected to your App page.

img - create a new app

Your Facebook App Page

img - facebook app page Once you website’s Facebook App page is setup. Now you have you application’s App ID and App Secret keys. These values will be needed in your AuthConfig.cs file. If you open your AuthConfig.cs file you will find that the file contains code to register clients for external authentication providers. By default this code is commented out. For this tutorial, You must uncomment the code written for facebook, after uncommenting your AuthConfig.cs file should look like this.

public static class AuthConfig
    public static void RegisterAuth()
        //    clientId: "",
        //    clientSecret: "");

        //    consumerKey: "",
        //    consumerSecret: "");

            appSecret: "ENTER_SECRET_KEY");


The appId and appSecret key values you will find in your Facebook App page.

First Test

Time to test a few things out now, run your application and go to the login page, Now you will the Facebook option under “Use another service to log in” header.

img - facebook first test

Click on that gives an error message, which says:

Given URL is not allowed by the Application configuration.: One or more of the given URLs is not allowed by the App’s settings. It must match the Website URL or Canvas URL, or the domain must be a subdomain of one of the App’s domains.

Now this is because we have not configured our Facebook App Page properly, go to your app page and in your settings. Add your localhost url along with the port number as shown below. Check out this stackoverflow thread for more info on this error.

img - facebook app settings change

Second Test

Now after making the above set of changes, lets again go to the login page and try logging in using Facebook, and voila !

enter image description here

In the above screenshot you can see the name I had specified while creating the app page “logintestbyyasser”. Press okay and continue. Now what happens when you click on the “Okay” button is interesting and is explained in the next section


When the okay button is pressed control flows into ExternalLoginCallback action of the AccountController. The first line of this action says:

AuthenticationResult result = OAuthWebSecurity.VerifyAuthentication(Url.Action("ExternalLoginCallback", new { ReturnUrl = returnUrl }));

A lot of useful information can be retrieved from this result variable returned by the OAuthWebSecurity.VerifyAuthentication() method. Check the below screenshot of the debug values.

img - debug values

You could read values out from the result variable in the following manner. You should be able to access the basic user info like username, name, facebook link, gender and most important of all the accesstoken.

string username = result.UserName;

var id = result.ExtraData["id"];
var name = result.ExtraData["name"];
var link = result.ExtraData["link"];
var gender = result.ExtraData["gender"];
var accesstoken = result.ExtraData["accesstoken"];

Get user data from Facebook

You can get more user details by talking to facebook api using the facebook sdk. The easiest way is to download and install using the nuget download manager.

enter image description here

Once downloaded now you can use the following set of code to get user details using the userId fetched from the result variable.

var client = new FacebookClient();
dynamic me = client.Get(id);

The above line of code returns a json object as shown below, try this link –

    "id": "790295720",
    "first_name": "Yasser",
    "gender": "male",
    "last_name": "Shaikh",
    "link": "",
    "locale": "en_US",
    "middle_name": "Riaz",
    "name": "Yasser Riaz Shaikh",
    "username": "yrshaikh"

You can get a host of user details using the accesstoken as shown below :

var client = new FacebookClient(accesstoken);
dynamic me = client.Get("me");

In my example I was able to retrieve the below information for the logged in user (myprofile)

  • id
  • bio
  • education
  • favorite_athletes
  • favorite_teams
  • first_name
  • gender
  • hometown
  • last_name
  • link
  • location
  • locale
  • middle_name
  • name
  • sports
  • timezone
  • updated_time
  • username
  • verified
  • work

Get Email, More Permissions, Scope and other details

The above details we fetched were the basic details that you get, incase you want more details of the user like his email adress, pubish_stream or read_stream then it gets a little complicated. Thanks to Matheus Valiente Souza‘s answer to this stackoverflow thread, originally posted on this blog – Authenticating Facebook users with MVC 4 OAuth AND obtaining Scope Permissions!

You will need to create the following class – FacebookScopedClient, taken blindly from here – tested and it works!

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using DotNetOpenAuth.AspNet;
using Newtonsoft.Json;

namespace facebooklogintest.App_Start
    public class FacebookScopedClient : IAuthenticationClient
        private string appId;
        private string appSecret;
        private string scope;

        private const string baseUrl = "";
        public const string graphApiToken = "";
        public const string graphApiMe = "";

        private static string GetHTML(string URL)
            string connectionString = URL;

                System.Net.HttpWebRequest myRequest = (HttpWebRequest) WebRequest.Create(connectionString);
                myRequest.Credentials = CredentialCache.DefaultCredentials;
                //// Get the response
                WebResponse webResponse = myRequest.GetResponse();
                Stream respStream = webResponse.GetResponseStream();
                StreamReader ioStream = new StreamReader(respStream);
                string pageContent = ioStream.ReadToEnd();
                //// Close streams
                return pageContent;
            catch (Exception)
            return null;

        private IDictionary<string, string> GetUserData(string accessCode, string redirectURI)
            string token =
                GetHTML(graphApiToken + "client_id=" + appId + "&redirect_uri=" + HttpUtility.UrlEncode(redirectURI) +
                        "&client_secret=" + appSecret + "&code=" + accessCode);
            if (token == null || token == "")
                return null;
            string access_token = token.Substring(token.IndexOf("access_token="), token.IndexOf("&"));
            string data = GetHTML(graphApiMe + "fields=id,name,email,username,gender,link&" + access_token);

            // this dictionary must contains
            Dictionary<string, string> userData = JsonConvert.DeserializeObject<Dictionary<string, string>>(data);
            return userData;

        public FacebookScopedClient(string appId, string appSecret, string scope)
            this.appId = appId;
            this.appSecret = appSecret;
            this.scope = scope;

        public string ProviderName
            get { return "Facebook"; }

        public void RequestAuthentication(System.Web.HttpContextBase context, Uri returnUrl)
            string url = baseUrl + appId + "&redirect_uri=" + HttpUtility.UrlEncode(returnUrl.ToString()) + "&scope=" +

        public AuthenticationResult VerifyAuthentication(System.Web.HttpContextBase context)
            string code = context.Request.QueryString["code"];

            string rawUrl = context.Request.Url.OriginalString;
            //From this we need to remove code portion
            rawUrl = Regex.Replace(rawUrl, "&code=[^&]*", "");

            IDictionary<string, string> userData = GetUserData(code, rawUrl);

            if (userData == null)
                return new AuthenticationResult(false, ProviderName, null, null, null);

            string id = userData["id"];
            string username = userData["username"];

            AuthenticationResult result = new AuthenticationResult(true, ProviderName, id, username, userData);
            return result;

and then use this newly created class in your AuthConfig.cs like as shown below:

var facebooksocialData = new Dictionary<string, object>();
facebooksocialData.Add("scope", "email, publish_stream, read_stream");

OAuthWebSecurity.RegisterClient(new FacebookScopedClient(
    appId: "1376784812605727",
    appSecret: "ce379ea552bf423b6f8434da14c85f65",
    scope:"email, user_likes, friends_likes, user_birthday"),

Important Note: For re-authenticating your facebook account with the app with new set of permissions, you may need to remove the existing set of permission and trying again.

And now when you try logging in using Facebook the following screen is shown, but this time more permissions are requested this includes friend list, email address, birthday and likes and your friend’s likes.

enter image description here

Now if you check again with the following code

string email =  result.ExtraData["email"];

Hope this help, please give your feedback/suggestions/correction using the comment box below. Thanks.


A Beginners Guide to IIS Logging


Internet Information Server is one of the most powerful web servers provided by Microsoft that is able to host and run your web applications. IIS supports the following protocols: FTP, FTPS, SMTP, NNTP, HTTP/HTTPS. We can host our web sites on IIS, we can use it as an FTP site also. For more information, click here.

IIS Logs

You can configure your Web site or your FTP site to record log entries that are generated from user activity and from server activity. Log data can help you control access to content, determine content popularity, plan security requirements, and troubleshoot potential Web site issues or FTP site issues. For example, you can use the log files to help determine whether a security event has occurred. The data in the log files can provide information about the source of the attack.

IIS can save log files to different file formats. When you enable logging, you can specify the file format that you want to use. By default, IIS uses the W3C Extended log file format. Typically, the W3C Extended log file format is the preferred log type to use. This log format lets you configure lots of extended attributes that are useful to help analyze security.

Enable and configure logging in Internet Information Services (IIS)

Open the IIS management console and expand the server node and select Logging in the features panel



Press the “Select Fields” button to configure the information you wish to log in your log files:

You can customize the data that is logged to log files that use the W3C Extended log file format. To customize the data, select the properties that you want and omit the properties that you do not want. You may want to select the following properties when you customize W3C Extended log file format logs:


Client IP address – This is the IP address of the client that accesses the server. Notice that if a Web proxy computer is in front of the server that is running IIS, the IP address of the proxy may appear in the Client IP Address box. User name – This is the name of the user who accesses the server. If Anonymous authentication is configured, a hyphen (-) is logged instead of the user name. Method – This is the action that the client tries to perform. For example, the action may be a GET command or a POST command. URI stem – This is the resource on the server that is running IIS that the user tries to access. For example, the resource may be an HTML page, a graphic, a CGI program, or a script. Protocol status – This is the status of the action in HTTP terms. This is represented by a code number. Win32 status – This is the status of the action in Win32 code terms. Error numbers are reported. For example, error 5 means that access is denied. User agent – This is the name of the Web browser that accesses the server. Server IP address – This is the IP address of the virtual server where the log entry is generated. This option is helpful if you host multiple virtual servers on the same computer, and the multiple virtual servers use different IP addresses. Server port – This is the port number of the virtual server that receives the client request. This option is helpful if you host multiple virtual servers on the same computer, and the multiple virtual servers use different IP addresses. The default selection of fields will provide a decent amount of information for standard environments. If more detail is desired, select more fields. Next, choose a log file location and rollover frequency. Please note that on heavily accessed websites, log files will demand a fair amount of disk space.

Find IIS Logs

The default place for access logs is c:\inetpub\logs\LogFiles. Otherwise, check under IIS Manager, select the computer on the left pane, and in the middle pane, go under “Logging” in the IIS area. There you will see the default location for all sites (this is however overridable on all sites)

You could also look into C:\Windows\System32\LogFiles\HTTPERR which will contain similar log files that only represents errors.

Reading the IIS Log

Web server log file entries typically look similar to this: - [29/Jul/2001:00:35:33 -0500] "GET /data-mining.htm HTTP/1.1" 200 11631 "" "Mozilla/4.0 (compatible; MSIE 5.5; Windows NT 5.0)"

Note that some of these entries may be in a different order in your log files. = IP Address (or XX if the IP address has been resolved) 29/Jul/2001:00:35:33 = Date and Time of the entry -0500 = Time difference to Greenwich Mean time (Universal Time). This log file entry was created when the web server was on US Central Summer time GET = Action data-mining.htm HTTP/1.1 = Object – i.e. retrieve the page data-mining.htm 200 = result (Result 200 means the task has been completed) 11631 = size of object, in bytes = Referring URL (i.e. this particular page was accessed from the home page of the Internet Marketing Engine) Mozilla/4.0 (compatible; MSIE 5.5; Windows NT 5.0) = Browser / version and platform – i.e. this person was using Microsoft Internet Explorer 5.5 and the Windows 2000 operating system.


Updraft Plus – Yet another good and reliable wordpress backup and restore plugin

I recently installed this backup and restore plugin called Updraft Plus. Its not that this was my first backup plugin installed or I did not have any other backup plugin installed on my site, its just that I wanted 2 backups plugin to be working on my site. The second backup plugin that I have been using for over 2-3 years now is WordPress Backup to Dropbox. I have been using this plugin for quite some time now and have never experienced any problems with it, I had configured it just once when I had installed it years back and it works great, even after every update.

Updraft Plus. The reason I added this additional backup plugin was that I have stopped using Dropbox and have moved to Google Drive. Updraft Plus promises to backup all your WordPress data (theme/plugin/db/uploads/others) all neatly and separately into one of these storage providers – S3, Dropbox, Google Drive, Rackspace, FTP, SFTP, email + others.

One of the good feature I liked here was the “retain this many backups:” feature. Where all other backup plugin will keep on taking n number of backups, this plugin does it a little different. Updraft-backups-options

I have set to retain 2 backups, and here is how my backup structure looks like:


The only thing I didn’t like about this plugin was that it was a little difficult to setup. But with help of this document an average wordpress user should easily be able to set this up.

To know more about Updraft plugin, head right here and get started :

Update: I forgot to mention that this plugin is free, However a premium version of this plugin was also available with many additional features that the time of writing this post.