CSS Hacks

Have you ever tried to enforce some consistency checks using CSS. Today I learned how to test if I or any developer has left “alt” attribute blank.

If we see below line of code, there is no “alt” attribute in the image element and there is no way to check it until or unless you do it manually or have some code to test.


Below image is output of above code.

To overcome this I found a simple hack using below code lines which will render red dotted line for all the images which are missing “alt” attributes

    border: 5px dashed red;


I hope this will be useful for someone.


What is my C# version?

Today one of my junior asked me what C# version we are working? To my surprise most of my colleagues had no idea about it and almost none of them knew what is default version of visual studio editor or how to change the default version of C# in visual studio editor. I demonstrated them how to change the default c# version of visual studio and also explained different C# versions in different visual studio editors.

In this blog I will try to explain different version of C# with .net framework and visual studio editor.

These are the versions of C# known about at the time of this writing:

  • C# 1.0 released with .NET 1.0 and VS2002 (January 2002)
  • C# 1.2 (bizarrely enough); released with .NET 1.1 and VS2003 (April 2003). First version to call Dispose on IEnumerators which implemented IDisposable. A few other small features.
  • C# 2.0 released with .NET 2.0 and VS2005 (November 2005). Major new features: generics, anonymous methods, nullable types, iterator blocks
  • C# 3.0 released with .NET 3.5 and VS2008 (November 2007). Major new features: lambda expressions, extension methods, expression trees, anonymous types, implicit typing (var), query expressions
  • C# 4.0 released with .NET 4 and VS2010 (April 2010). Major new features: late binding (dynamic), delegate and interface generic variance, more COM support, named arguments, tuple data type and optional parameters
  • C# 5.0 released with .NET 4.5 and VS2012 (August 2012). Major features: async programming, caller info attributes. Breaking change: loop variable closure.
  • C# 6.0 released with .NET 4.6 and VS2015 (July 2015). Implemented by Roslyn. Features: initializers for automatically implemented properties, using directives to import static members, exception filters, indexed members and element initializers, await in catch and finally, extension Add methods in collection initializers.
  • C# 7.0 released with VS2017 (March 2017) Major new features: tuples, ref locals and ref return, pattern matching (including pattern-based switch statements), inline out parameter declarations, local functions, binary literals, digit separators, and arbitrary async returns.

More detailed information about the relationship between the language, runtime and framework versions is available on the C# in Depth site. This includes information about which features of C# 3.0 you can use when targeting .NET 2.0.

The biggest problem when dealing with C#’s version numbers is the fact that it is not tied to a version of the .NET Framework, which it appears to be due to the synchronized releases between Visual Studio and the .NET Framework. The version of C# is actually bound to the compiler, not the framework. For instance, in VS2008 you can write C# 3.0 and target .NET Framework 2.0, 3.0 and 3.5.

How to change default C# version in visual studio editor?

To target desired version of language for a project in Visual Studio, we need to take following steps:

Open the project properties window:

  • Right click on the Project Name
  • Select “Properties” (last option in menu)
  • Modify Project Properties as per below steps:
  • Select “Build” from left hand side options
  • Click on “Advance” button.
  • It will open a popup and there you will get “Language Version” dropdown
  • Select desired version of C# and Click “OK”

As of May 3, 2017, the C# Language Team created a history of C# versions and features on their github repo: Features Added in C# Language Versions

I hope this tip will this will help someone’s  and save their time and effort.

C# 7.0: Tuple Types and Tuple Literals

Basically, a tuple (Tuple in C#) is an ordered sequence, immutable, fixed-size and of heterogeneous objects, i.e., each object being of a specific type. Tuples were introduced in C# with .NET 4.0

// Implementation
private Tuple<int, string> GetData()
	int id = 1;
	string name = "test";
	return Tuple.Create(id, name);
var tuple = GetData();
var message = $"ID is {tuple.Item1} and Name is {tuple.Item2}";

Tuples provide a quick way to group multiple values into a single result, which is very useful when used as a return of function, without the need to create parameters “ref” and / or “out “. It also facilitated with creation of composite keys to collections of type Dictionaryand eliminates the need to create structs or classes or just to fill combobox or lists.

Along with all advantages it has a major problem, tuples does not have an explicit semantic meaning. In other words, the elements in the tuples don’t have names, they have same names (Item1,Item2,Item3…ItemN). It’s hard to read and understand for teams consuming these functions.

To do better at this, C# 7.0 adds tuple types and tuple literals. Tuples still are not part of .NET framework, to use them we can add them using nuget:

PM> install-package System.ValueTuple

Successfully installed ‘System.ValueTuple 4.3.0’ to EntityFrameworkSample
Executing nuget actions took 3.85 sec
Time Elapsed: 00:00:04.5314317

public (int id, string name, double marks) GetData()
	var id = 1;
	string name = "test";
	double marks = 95.7;
	return (id, name, marks);
var tuple = GetData();
var message = $"ID is {tuple.id}, name is {tuple.name} and marks are {tuple.marks}";

Now with new implementation, it looks much better and readability is also good. There is another nice addition, it fully supports async and await.

public async Task<(int id, string name, double marks)> GetData()

Tuples can also be created as:

var t = new (int sum, int count) { sum = 0, count = 0 };

Final comment, whatever changes C# has made are syntactical changes. If you check the compiled code, the tuples are referred as Item1,Items2 etc not id, name or marks.

I hope this helps someone. Any comments and suggestions are welcome.

SQL Tips: Why we need to have RIGHT OUTER JOIN in SQL

Recently I was reading some article and in comments section I found this interesting question.

Q’s: If we perform left outer join on employee and department it will return all records from left table and only matching from right. similarly, right outer join will return all the records from department and only matching from employee table. NOW… what if we swap the tables in left outer join. i.e if we perform left outer join of department and employee which will return same records as output as right outer join.


Before I dive into the answer, I would love to give a brief intro about Left outer join and Right outer join.


For the sake of this example, lets say you have 100 students, 70 of which have enrollments. You have a total of 50 enrollments, 40 of which have at least 1 student and 10 enrollments have no student.

LEFT OUTER JOIN would be “show me all students, with their corresponding enrollments if they have one”.
This might be a general student list, or could be used to identify students with no enrollments.
Returns 100 rows

RIGHT OUTER JOIN would be “show me all enrollments, and the students assigned to them if there are any”.
This could be used to identify enrollments that have no students assigned, or enrollments that have too many students.
Returns 80 rows (list of 70 students in the 40 enrollments, plus the 10 enrollments with no student)

Lets get back to our main question,”WHY DO WE NEED RIGHT OUTER JOIN”?

Answer to the above question was also provided by some anonymous user then and there in itself.

Anything you can write as a “RIGHT OUTER” could be written as a “LEFT OUTER” by just flipping the tables, so technically “RIGHT OUTER” isn’t functionally required in order to have working code.

It was created to allow the coder to express it that way if it makes more sense to them that way. So basically it exists for readability and potential maintainability.

Having said that I rarely see anyone code a “RIGHT OUTER”, most people just automatically order their tables to be “LEFT OUTER” joins if an outer is needed.

I found it interesting, so thought to share with others also. May be it can be of some help to some one else.

SQL Tips: Parsing special characters in Queries

Recently I was working on some SSIS reports. Everything was working fine up till my queries ran on testing server where it failed during parsing of special characters in the query.

Below query worked fine  when there was no special character in the data.

StudentID INT,
Subjects VARCHAR(8000)

(111,'English French,Maths,Science'),
(112,'English Spanish,English,Science')

SELECT StudentId 'Student Id',
LTRIM(RTRIM(m.n.value('.[1]','varchar(8000)'))) AS 'Subject Name'
 CAST('' + REPLACE(Subjects,',','') + '' AS XML) AS node
CROSS APPLY node.nodes('/XMLRoot/RowData')m(n)



It started failing as soon as I got special characters in my data.

--(111,'English & French,Maths,Science'),
--(112,'English & Spanish,English,Science')

Msg 9421, Level 16, State 1, Line 13
XML parsing: line 1, character 28, illegal name character

This is what I made changes to my query to get the desired results. Here I am using (SELECT ... FOR XML PATH()) instead of the naked Subjects. I am letting FOR XML PATH() do all the hard work for me.

--Changed below line
CAST('' + REPLACE(Subjects,',','') + '' AS XML) AS node
CAST('' + REPLACE((SELECT Subjects AS [*] FOR XML PATH('')),',','') + '' AS XML) 
AS node



We can see now we are getting the results with “&” characters.

I hope this will help someone and will save some precious time.

SQL Tips – Comma separated list

Today in an interview interviewer asked me to make a query to create a comma separated list which I did easily using STUFF and XML Path. Later I realized I could do it through other ways also. I will write in this blog all possible ways I know.
Table Schema

CREATE TABLE Student(StudentId int,SubjectName varchar(100))

INSERT INTO Student VALUES(111,'English')
INSERT INTO Student VALUES(111,'Science')
INSERT INTO Student VALUES(112,'English')
INSERT INTO Student VALUES(112,'Science')
INSERT INTO Student VALUES(111,'Maths')

Query 1: Below query will pull list for each StudentId  one at a time.

SELECT STUFF((SELECT ',' + SubjectName
FROM Student SS
WHERE SS.StudentId = S.StudentId
ORDER BY SubjectName
FOR XML PATH('')), 1, 1, '') AS SubjectList
FROM Student S
GROUP BY S.StudentId


Query 2: Below query will return all the subjects in one string value. Basically, in this code we are checking if the variable has been initialized yet. If it hasn’t, set it to the empty string, and append the first SubjectName (no leading comma). If it has, then append a comma, then append the SubjectName.

SELECT @listStr = COALESCE(@listStr+',' , '') + SubjectName
FROM Student
SELECT @listStr 'Subject List'


Query 3: Below query will also return the same output as above query, but its implementation is different. This is also a good way but not the best way.

SET @listStr = ''
SELECT @listStr = @listStr + SubjectName + ','
FROM Student
SELECT SUBSTRING(@listStr , 1, LEN(@listStr)-1) 'Student List'


We can also use cursors to get same results but they aren’t the efficient way.

Splitting comma separated list

Suppose we have another scenario where we have a string of comma separated list and we have to return a table of it.

StudentID INT,
Subjects VARCHAR(8000)

        STUFF((SELECT  ',' + SubjectName
            FROM Student SS
            WHERE  SS.StudentId = S.StudentId
            ORDER BY SubjectName
        FOR XML PATH('')), 1, 1, '') AS 'Subject List'
FROM Student S
GROUP BY S.StudentId


Using below query we can split a comma separated list into a table.


SELECT StudentId 'Student Id',
LTRIM(RTRIM(m.n.value('.[1]','varchar(8000)'))) AS 'Subject Name'
	CAST('' + REPLACE(Subjects,',','') + '' AS XML) AS node
CROSS APPLY node.nodes('/XMLRoot/RowData')m(n)


We can use above query in UDF’s also to return a table value as output.

I hope it will help someone. Any comments or suggests are welcome.

Algorithms in C#

This is part 3 of Algorithms questions in Interviews.(Part 1 | Part 2 )

In this post we will write an algorithm that finds an element in an array of infinite size.
How to find an element position from an array?

Below function takes an infinite size array and a key to be searched and returns first index position if found else -1. Here, we don’t know size of array and we can assume size to be infinite in this function.

Please note I am assuming the array is a sorted array. For (Quicksort) sorting the array you can refer to part 2 of this blog series.

First Occurence of element

private int FirstOccurrenceBinarySearch(int arr[], int low, int high, int data)
	int mid; 
	// A simple implementation of Binary Search
	if(high >= low)
		mid = low + (high - low)/2; // To avoid overflow
		if((mid == low && arr[mid] == data) || (arr[mid] == data && arr[mid-1] < data)) 		{ 			return mid; 		} 		 		else if(arr[mid] >= data)
			// We need to give preference to left part of the array
			// since we are concerned with the first occurrence
			return FirstOccurrenceBinarySearch(arr, low, mid-1, data);
		else // We need to search in the right half
			return FirstOccurrenceBinarySearch(arr, mid+1, high, data);
	return -1;

Last Occurence of element

private int LastOccurrenceBinarySearch(int[] array, int low, int high, int data)
	int mid;
	// A simple implementation of Binary Search
	if (high >= low)
		mid = low + (high - low) / 2; // To avoid overflow
		if ((mid == high && array[mid] == data) || (array[mid] == data && array[mid + 1] > data))
			return mid;

		// We need to give preference to right part of the array
		// since we are concerned with the last occurrence
		else if (array[mid] <= data)
			return LastOccurrenceBinarySearch(array, mid + 1, high, data);
			// We need to search in the left half
			return LastOccurrenceBinarySearch(array, low, mid - 1, data);
	return -1;

Algorithms in C#

This is part 2 of Algorithms questions in Interviews.(Part 1| Part 3)

Quicksort Algorithm

public void QuickSort(int[] array, int left, int right)
	int i = left;
	int j = right;
	int pivot = array[(left + right) / 2];
	while (true)
		while (array[i] < pivot)
		while (pivot < array[j])
		if (i <= j)
			Swap(array, i, j);
		if (i > j) 
		if (left < j)
			QuickSort(array, left, j);
		if (i < right)
			QuickSort(array, i, right);

private void Swap(int[] array, int a, int b)
	var temp = array[a];
	array[a] = array[b];
	array[b] = temp;

That code is actually a fairly clear implementation of quicksort.
The key to understanding this particular program is that every recursive function call receives the same full string. So the function has to set its own boundaries, i.e., “left” and “right” and ignore the remainder of the string. Every recursive function call only deals with partitioning a small part of the string.

The original function call partitions the string into portions less than the pivot (lower portion) and greater than the pivot (upper portion), leaving any string values equal to the pivot in a “no man’s land” somewhere in between the left and right portions.

As soon as it gets to the recursive function calls, it gets a bit more murky, and it is important to understand that these lower and upper portions are different from the “left” and “right” variables. The “left” variable is the original position of the left boundary of the entire string that the function call is supposed to operate on, and similarly for the “right” variable.

The key to the algorithm is understanding that the first function call leaves nothing necessarily sorted in the upper or lower portions. However, it removes one or more partition values from consideration and ensures that they are above all lower string values, and below all upper string values, i.e., in the “middle” of the string.

This process is repeated recursively on both of the unsorted upper and lower portions of the string until eventually reaching an upper or lower portion size of two or fewer values, which must be sorted already as a result of being partitioned.

The quicksort algorithm has a worst case performance of O(N^2) if the pivot value is always an extreme value, and a best case performance of O(N log N) if the pivot value is close to the middle of the string. For instance, when sorting 31 characters and assuming a perfect median choice of pivot,

first stage:

lower 15, pivot, upper 15

second stage:

(lower 7, pivot, upper 7), pivot, (lower 7, pivot, upper 7)

third stage:

((lower 3, pivot, upper 3), pivot, (lower 3, pivot, upper 3)), pivot, ((lower 3, pivot, upper 3), pivot, (lower 3, pivot, upper 3))

fourth stage:

(((lower 1, pivot, upper 1), pivot, (lower 1, pivot, upper 1)), pivot, ((lower 1, pivot, upper 1), pivot, (lower 1, pivot, upper 1))), pivot, (((lower 1, pivot, upper 1), pivot, (lower 1, pivot, upper 1)), pivot, ((lower 1, pivot, upper 1), pivot, (lower 1, pivot, upper 1)))

Four stages is less than or equal to the base-two logarithm of 31, and at every stage the algorithm is linear (although performed in multiple distinct recursive function calls at each level), so 31 steps are performed, i.e., N steps.

So the total order of the algorithm is 4 stages times 31, or approximately N times log N.

In reality, sometimes a pivot is not the median, and may even be an extreme value, in which case the “lower” or “upper” portions are empty. The algorithm might remove only one value from consideration at each stage, resulting in a total of N-1 stages to complete the algorithm. At every stage, there would be N steps of work, so the total order would be N times (N-1), which is O(N^2) since there is a product of N with N.

All in all, quicksort is a very good algorithm, and very hard to improve, as long as one’s algorithm avoids deliberate pernicious cases which could otherwise be exploited to feed a known codebase with input which produces a pivot sequence of extreme values.

Algorithms in C#

After spending 9 years in IT finally I am being asked to show my skills on Algorithms. On my first interview I could solve 90% not completely. Then I thought to revive something which I had been doing throughout my career.

In this series I will be posting some commonly asked Algorithms in Interviews. Part 2 | Part 3

How to find second highest number from an array?

public int FindSecondHighest(int[] array)
	int first = 0;
	int second = 0;
	foreach(var item in array)
		if(item > first)
			second = first;
			first = item;
		else if(item > second)
			second = item;
	return second;

How to find second lowest number from an array?

public int FindSecondLowest(int[] array)
	var firstlowest = Int32.MaxValue;
	var secondLowest = Int32.MaxValue;

	if (array.Length > 2)
		for (int i = 0; i < array.Length; i++)
			if (array[i] < firstlowest)
				secondLowest = firstlowest;
				firstlowest = array[i];
			else if (array[i] < secondLowest && array[i] > firstlowest)
				secondLowest = array[i];
	return secondLowest;

TFS User Management

In this post I will demonstrate one of my TFS Extension which I created while working for one of my client, I named it as “Manage TFS User”.

Before diving into technical details lets discuss the need of it. The Configuration Team has a requirement where they wanted to have a utility using which they can manage TFS users i.e, Adding/Removing users from TFS Groups during release processes. So I created a TFS Extension and a WindwsUtility to do the job.

In this post I will detail all about the TFS Extension and in next post I will detail about the Windows Utility.

Once the Extension is installed, it comes under Tools menus as displayed in below image.

1Image 1

When a user clicks on menu  “Manage TFS User”, the extension checks if the a TFS Server Name/URL has been set or not. If the extension is triggered for the first time, the below window pop’s up for TFS URL. Once set, the window will be closed and a new window will pop up as in image 3. The saved TFS URL can be reset manually also.

8Image 2

If a TFS URL has been previously set, then the extension will open as shown in the below image(Image 3).

2Image 3

As we can see in the below image (Image 4), the window is pre-populated with all the TFS User groups and their respective members. Using this window we can Add/Remove a user(s) to a TFS Group.

3Image 4

Using this tool a user can be removed individually or all users can be removed completely by using the Remove User(s) button.

In the same way, there are two ways to add a user:

  1. Right click on a Group name and click on Add User pop up button.
  2. Select the Group name and click the Add User(s) button

This will open a new Window using which we can add a user to the group.

Image 5

A user can be added by selecting a user(s) from the grid list or by entering a comma or semi-colon or a new line separated username(s) as seen in below image.

6Image 6

I hope this will help someone.

The source code for this application can be found on my github.