March 17, 2018

XAMPP - PHP - Connect with MS SQL Server 2008 R2 in Laravel

Few days back I got stuck in this situation, I was developing PHP web application with Laravel 5.6 framework, the problems comes when I tried to connect with MS SQL Server rather than MySQL or MariaDB (that comes as default in XAMPP package), It started giving me error like driver not found. Here is how I solved this problem.

First you need to download Microsoft Drivers 4.3 for PHP for SQL Server, then extract the files to some folder. Copy the file php_pdo_sqlsrv_71_ts_x86.dll to php/ext folder (from XAMPP installation's root folder). Now we have to instruct PHP to use this extension.

Open php/php.ini file and move the cursor to extensions section. Add following new line of extension which directs PHP to use SQL Server driver's dll.


We have successfully set-up our PHP environment with MS SQL Server Driver.

Don't forget to restart your server afterwards.

Now you should be able to successfully connect with SQL Server from PHP.

Here comes the Laravel part. You have to specify connection string parameters in .env file of Laravel root folder.


Or alternative way is to define connection parameters in config/database.php file.

'sqlsrv' => [
            'driver' => 'sqlsrv',
            'host' => 'MY-PC\MYSQL2008R2',
            'port' => '1433',
            'database' => 'ITEMMASTER',
            'username' => 'myuser',
            'password' => 'mypassword',
            'charset' => 'utf8',
            'prefix' => '',

Now Laravel website should be able to connect with SQL Server database.

I hope you found this post helpful. Do you agree? Share your thoughts in the comments below!

February 24, 2018

C# - Set DateTime required format for each request in ASP.NET MVC

I was being asked this question by one of my colleague, if we can set a DateTime format at some global level so that if we need to display/process date at multiple controllers or views, we should not be worried about a specific format. I came up with this solution, I am sharing here, and welcome your suggestion or comments for any improvements or alternative solutions.

Lets say we need to display and save date in yyyy/MM/dd format. Since our server default format is set to dd/MM/yyyy, and we could not change it because some other applications might get affected, so we decided to set the required format at request level in our ASP.Net MVC application. For this we have to set the date format for current culture for each request, i.e. inside Global.asax.cs, in Application_BeginRequest() event.

Here is the real code which will set the format for current culture with the required one.

protected void Application_BeginRequest(Object sender, EventArgs e) 
 CultureInfo newCultureInfo = (CultureInfo)System.Threading.Thread.CurrentThread.CurrentCulture.Clone();
        newCultureInfo.DateTimeFormat.ShortDatePattern = "yyyy/MM/dd";
        //newCultureInfo.DateTimeFormat.LongDatePattern = "yyyy/MM/dd";
        //newCultureInfo.DateTimeFormat.FullDateTimePattern = "yyyy/MM/dd";
        newCultureInfo.DateTimeFormat.DateSeparator = "/";
        Thread.CurrentThread.CurrentCulture = newCultureInfo;

Here I am setting the DateTimeFormatInfo object's ShortDatePattern property to "yyyy/MM/dd", in CurrentCulture. Similarly you can set other required properties like LongDatePattern, FullDateTimePattern, ShortTimePattern or LongTimePattern etc. In this way you don't have to set the required date pattern in multiple places.

January 17, 2018

How to validate only numbers in string variable in C#?

There are multiple ways to validate user input string in order to allow only numbers. Lets say we have a string in variable myInput, following are some tips you can use to check if the input string is only contains numbers.

Check for numbers while entering data

If you are using Winforms and want to validate user input, then you can use TextBox's KeyPress event.

private void txtNumber_KeyPress(object sender, KeyPressEventArgs e)
  if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && e.KeyChar != '.')
    e.Handled = true;

You can set e.Handled property to true if the character entered is not the desired one, it will suppress that key. You can use similar technique in JavaScript if you are working with ASP.NET.

Check for numbers if you have a string variable

In many cases, if you are not using Winforms application or you may need to inspect the string variable other than the KeyPress event, then you can use one of following methods.

If the string variable contains a value within valid integer range, then you can use int.TryParse() function to check if it has valid integer value.

private bool ValidateNumber(string myInput)
    int val;
    if (int.TryParse(myInput, out val))
       return true;
        return false;

Note: This method has limitation that the input is being checked only for valid integers, which can have a maximum value of 2,147,483,647. For example, if you need to verify a string of 15 digits, then this method may not give you the desired result.

In order to validate a string with numbers having more digits, we can use the following options:

Char.IsDigit can be used to check if the character at any specified position in string is a digit, and here we are using Linq function All to our string, which will call Char.IsDigit function for each character in the string, and hence can get the required output.


A more formal method can be used, i.e. Regular Expressions, which can give you more control in different scenarios. Here we are using Regular Expression "^[0-9]*$" to match for numbers in input string.

 System.Text.RegularExpressions.Regex.IsMatch(myInput, "^[0-9]*$")

I hope you find this post helpful, I welcome your comments or suggestions if you may find any more alternative(s) to validate numeric figures in a string.

December 21, 2017

C# - Using Enumeration types as bit flags

Enumeration allows you to define named integral constants that could be hold by a variable, which can be used in client code to clearly specify the valid values for a variable, because in Visual Studio, IntelliSense lists the defined values. You may have a scenario where you need to hold combination of more than one values, there comes the bit flags. You can use enum type to define bit flags, which allows the enumeration type to store a combination of the values that are defined in the enum list.

You can create bit flags enum by applying the Flags attribute and defining the values by including a named constant with a value of zero that means "no flags are set.", then define remaining items and set the value of each enumeration item to be a power of 2, this enables you to define the combination of more than one values, for example WeekDaysEnum.Friday | WeekDaysEnum.Monday.

Lets start with following enum of week days.

 public enum WeekDaysEnum : short
  None = 0, //Use None as the name of the flag constant whose value is zero.
  Friday = 1,
  Saturday = 2,
  Sunday = 4,
  Monday = 8,
  Tuesday = 16,
  Wednesday = 32,
  Thursday = 64

In our client code, we can use this enum as:

 private void Test()
  //Initialize with single value 'Friday'
  WeekDaysEnum visitingDays1 = WeekDaysEnum.Friday;
  // assign with two flags using bitwise OR.
  WeekDaysEnum visitingDays2 = WeekDaysEnum.Friday | WeekDaysEnum.Monday;
  // Add more flags using bitwise OR.
  visitingDays2 = visitingDays2 | WeekDaysEnum.Thursday;
  // Print visitingDays2 variable, it will give you the output : 
  // Selected days are Friday, Monday, Thursday
  // Note that, it will automatically prepare string of comma separated values.
  Console.WriteLine("Selected days are {0}", visitingDays2);
  //Similarly you can remove a flag from variable, using bitwise XOR
  visitingDays2 = visitingDays2 ^ WeekDaysEnum.Thursday;

You can use bitwise AND operator to check whether the variable contains a specific flag/value.

 if ((visitingDays2 & WeekDaysEnum.Friday) == WeekDaysEnum.Friday)
  Console.WriteLine("Friday visit is open.");
  Console.WriteLine("Friday visit is not allowed.");

I hope you find this post helpful. You can find more info about the flags attribute and its usage at:

November 26, 2017

C# Winforms - How to use localized strings/translations using ResourceManager

In this post I will explain how to implement localization in Windows Forms Application using ResourceManager class. We will see an example application with Login form, and change the strings/labels with two different locales (in this example I am using English and Arabic locales). So lets start with this sample Login form.

We want to see the form display with English locale similar to the following screenshot

And with Arabic locale, the form should display similar to this screenshot

First we have to create separate resource files for separate locales (English and Arabic in this example)

Here is the resource file for English locale Messages.en.resx.

And here is the resource file for Arabic locale

Note that the resource file names are ended with .en and .ar and then the actual file extension .resx. Similarly if you want to create resource files for any other language, you have to create separate resource file with correct file name ending with .[locale-name]

In this example I have placed these two resources files in MyResources folder, solution explorer seems like this:

We have written the labels translations in resource files. Its time to write real C# code to use these resource files and display the target translated labels on corresponding controls. For this we are using ResourceManager class found in namespace System.Resources.

Lets create a function which accepts the lang argument, and set labels/controls texts with corresponding string translations from resource files by passing the target CultureInfo argument. To get the desired translated string, we are using helper method rm.GetString().

 private void ChangeLang(string lang)
  CultureInfo ci = new CultureInfo(lang);

  System.Resources.ResourceManager rm = new System.Resources.ResourceManager("WindowsFormsApplication1.MyResources.Messages", typeof(Form1).Assembly);
  lblUserName.Text = rm.GetString("UserName", ci);
  lblPassword.Text = rm.GetString("Password", ci);
  btnLogin.Text = rm.GetString("Login", ci);
  rbEnglish.Text = rm.GetString("English", ci);
  rbArabic.Text = rm.GetString("Arabic", ci);
  this.Text = rm.GetString("Authentication", ci);

Note that ResourceManager constructor accepts argument as the complete assembly name, folder, and resource file name concatenating with dots ("WindowsFormsApplication1.MyResources.Messages" in this case).

Now run the application and you should be able to see the login form displaying the strings/translations based on selected locales.

I hope you have found this article helpful, I welcome your comments and suggestions to analyze this technique, and find if there is any better alternative for implementing localization.