Saturday, September 18, 2010

C# Bitwise Flag Enum

Imagine there was a requirement for a notification system, where users could select multiple days for delivery in a week (eg: MON, TUE, WED, THU, FRI, SAT, SUN). Now you could do this by having Boolean flags for each option or a better way is to use bitwise enum flags. They store very efficiently in memory and manipulation is very fast.

Before reading ahead, I would strongly suggest to read about bitwise operations here, otherwise it will be very hard to understand the logic of the example.

So lets declare our bitwise flag enum:
private enum DeliveryDays
  NONE = 0, // 0000000
  MON = 1,  // 0000001
  TUE = 2,  // 0000010
  WED = 4,  // 0000100
  THU = 8,  // 0001000
  FRI = 16, // 0010000
  SAT = 32, // 0100000
  SUN = 64, // 1000000
  WORKDAYS = MON | TUE | WED | THU | FRI,  //0011111
  WEEKENDS = SAT | SUN  //1100000
The [Flags] attribute indicates that an enumeration can be treated as a bit field. Do use powers of two for a enumeration's values so they can be freely combined using the bitwise OR operation. As you can see for workdays and weekends we have combined the relevant days.

Now lets write down the methods which set these flags on or off.
private DeliveryDays _selectedDays = DeliveryDays.None;

public void AddDeliveryDays(DeliveryDays days)
  _selectedDays |= days;

public void RemoveDeliveryDays(DeliveryDays days)
  _selectedDays &= ~days;

public void testDaysBitEnum()
  //lets select monday and tuesday
  AddDeliveryDays(DeliveryDays.MON | DeliveryDays.TUE);
  //lets change it all the work days
  //now lets remove monday and tuesday and add weekends
  RemoveDeliveryDays(DeliveryDays.MON | DeliveryDays.TUE);
As shown above we can quickly toggle multiple flags. But we also need some functionality to find which flags have been selected. In .NET framework 4.0 the enum has a method called HasFlag which does this for you. For older frameworks you can use the following method.
public bool HasFlag(DeliveryDays day)
  return ((_selectedDays & day) == day);
If you are using .NET 3.5 Framework it will be handy to add the above method as an Extension Method.

Friday, September 10, 2010

Progress Bar using css (cascading style sheet)

Recently I worked on some functionality where we wanted to show progress to users whilst they were answering a survey. Basically as they answered the questions a progress bar would show the completion percentage. As I started playing around with some css, it turned out be quite easy.

Have a look at the example below:


The above progress bar is made of three div tags,
1. The outer container div with a border which works as a place holder for the progress and the text being displayed
The relative positioning of this container ensures that all it's child div tags are contained within.

2. Next is the div container which will sit inside the above div and show the progress. This is just an absolute positioned div with a background color or an repeater image. Basically, we just change the width of this div to show the increase in progress.

3. The third div is another absolute positioned container which will sit inside the place holder div tag to show the text. The important thing to notice about it's style is that, it completely fills the place holder div with a transparent background so you can see the progress. The higher z-index ensures that it will sit on top of the div showing the progress in background.

Now what you need is some jquery to manipulate the width of the div showing the progress. As an example:

Wednesday, September 8, 2010

Vertical Content Scrolling

There are lot of jquery plugins available which provides horizontal or vertical content scroll functionality, like for scrolling through image gallery. Recently I had a requirement where a web page needed vertical scrolling functionality for a navigation system.

Below is a very simple example, where content of a list is being scrolled by two buttons.

So lets get into this,
1. First we need to create a div tag with it's style overflow attribute set to hidden.

2. Add the content.

3. Now for scrolling, we will use jquery's animate function which will provide us a smooth scrolling effect.

function scroll(val) {
                scrollTop: jQuery('#list').scrollTop() + (val)
            }, 450);
The above function takes a integer parameter which gets added to the scrollTop attribute of the div containing the content, which causes the content to scroll. The animate function makes the transition smoother, to read more about animate function go here.

4. Now what we need is just two buttons, which will call this function and pass +ve values to scroll down and -ve values to scroll up.

This a very simple example, but gives a good idea for building cool vertical content scrolling.

Monday, September 6, 2010

Check if string is null or empty.

I have seen so many lines of code where people write checks for a string being null or blank. Also, sometimes there is no check for string being empty.
For example:

There is a better way of doing this, there is very neat static function in the String class which does this check for you String.IsNullOrEmpty(string value).

Sunday, September 5, 2010

Tuple in C# 4.0

C# 4.0 includes a new feature called Tuple. Tuple provides us with a way to group elements of disparate data types together.This is present in functional languages like Haskell and also dynamic languages like Python.

Consider the following code:
It creates a tuple storing name and age of person.

We can create nested tuples as shown below:

The most important thing to know about the Tuple type is that it is a class, not a struct, and thus will be allocated upon the managed heap. Each class instance that is allocated adds to the burden of garbage collection. The properties Item1, Item2, and further do not have setters, so you cannot assign them. The Tuple is immutable once created in memory.

It is difficult for developers to choose between Tuples and Anonymous Types as they serve similar purpose. It can be a difficult to make the best choice between those two solutions.

Read more about it here.

Saturday, September 4, 2010

Extension Methods

Extension methods behavior is similar to that of static methods. You can declare them only in static classes. To declare an extension method, you specify the keyword this as the first parameter of the method, for example

static class StackOps
   public static void Push<T>(this List<T> TheList, T Value)

   public static T Pop<T>(this List<T> TheList)
      if (TheList.Count == 0)
         throw new Exception("Nothing to pop.");
      int LastPos = TheList.Count - 1;
      T Result = TheList[LastPos];

      return Result;

static void Main(string[] args)
   var Stack = new List<int>();

   // Put stuff onto the stack.
   for (int i = 0; i <= 10; i++)

   // And now pop stuff off it.
   while (Stack.Count > 0)

Read more about Extension Methods here.

C# Lambda Expressions

A lambda expression simply defines an anonymous function. All lambda expressions use the lambda operator =>, which is read as "goes to". The left side of the lambda operator specifies the input parameters (if any) and the right side holds the expression or statement block.

Read more about lambda expressions here.

SQL Server - Comma delimited string from a table column

This is a very simple and efficient way of getting values of a column in a delimited string.

USE AdventureWorks 

SELECT @nameslist COALESCE(@nameslist+',' ,'') + Name 
FROM Production.Product 

SELECT @nameslist

Using the COALESCE function ensures that result set does not get affected by null values. For more information about this function check out this link.