Thursday, 24 May 2012

Why int is 16-bit in 16-bit compilers but even if long, float are 32 bits?

This is because of processor size. As the default data type is int so, if this matches then it optimizes the operations. another important thing is that int depends on OS, Processor, etc. so it is 16-bit in 16 bit compiler.

IEnumerable.Count() is a bad style of Coding, Why?

IEnumerable<Participant> participants=GetParticipants();

if(products.count()==0)
{
       SomeControls.Visible=false;
}
else
{
     SomeControls.Visible=true;
}
The wrong thing with the above code is that Count() is a Linq extension Method that literally iterates through every item in an  enumerable( here it is participants). In other words it won't short circuit after it finds more than zero items and will continue iterating through every single item. And while, that one may be fast operation in Dev environment but it will be a slow process in production. This is because of Linq's deferred Execution.

How we can refine the above Code

The above Code can be refined by changing it into as:
IEnumerable<Participant> participants=GetParticipants();

if(products.Any())
{
       SomeControls.Visible=false;
}
else
{
     SomeControls.Visible=true;
}

In the above code once the expression finds more than one item, it simply stops iterating and just increasing the Optimization time.

Happy Coding.........!

Thursday, 17 May 2012

Function to find GCD using Euclidean Algorithm

int GCD(int a, int b)
{
     while (a != 0 && b != 0)
     {
         if (a > b)
            a %= b;
         else
            b %= a;
     }

     if (a == 0)
         return b;
     else
         return a;
}

Using "Bitflags" in C

Bitflags are a method of storing multiple values, which are not mutucally exclusive, in one variable. You've probably seen them before. Each flag is a bit position which can be set on or off. You then have a bunch of bitmasks #defined for each bit position so you can easily manipulate it:
 
#define LOG_ERRORS            1  // 2^0, bit 0
#define LOG_WARNINGS          2  // 2^1, bit 1
#define LOG_NOTICES           4  // 2^2, bit 2
#define LOG_INCOMING          8  // 2^3, bit 3
#define LOG_OUTGOING         16  // 2^4, bit 4
#define LOG_LOOPBACK         32  // and so on...

// Only 6 flags/bits used, so a char is fine
unsigned char flags;

// initialising the flags
// note that assignming a value will clobber any other flags, so you
// should generally only use the = operator when initialising vars.
flags = LOG_ERRORS;
// sets to 1 i.e. bit 0

//initialising to multiple values with OR (|)
flags = LOG_ERRORS | LOG_WARNINGS | LOG_INCOMING;
// sets to 1 + 2 + 8 i.e. bits 0, 1 and 3

// setting one flag on, leaving the rest untouched
// OR bitmask with the current value
flags |= LOG_INCOMING;

// testing for a flag
// AND with the bitmask before testing with ==
if ((flags & LOG_WARNINGS) == LOG_WARNINGS)
   ...

// testing for multiple flags
// as above, OR the bitmasks
if ((flags & (LOG_INCOMING | LOG_OUTGOING))
         == (LOG_INCOMING | LOG_OUTGOING))
   ...

// removing a flag, leaving the rest untouched
// AND with the inverse (NOT) of the bitmask
flags &= ~LOG_OUTGOING;

// toggling a flag, leaving the rest untouched
flags ^= LOG_LOOPBACK;

 
WARNING: DO NOT use the equality operator (i.e. bitflags == bitmask) for testing if a flag is set - that expression will only be true if that flag is set and al others are unset. To test for a single flag
 
if (flags == LOG_WARNINGS) //DON'T DO THIS
   ...
 

Using Enumerations in C and C++

Whenever you need to define a set of mutually exclusive states, always use an enumeration. Don't use an int and a bunch of #defines. If space is really a premium and you only need a few things, you could settle for a char and a few letters as a code. If you need to represent some states that aren't mutually exclusive, use bitflags (see the next section).
An enumeration is basically an integer type associated with a bunch of special tokens. These tokens can be used for assignment and is-equal or not-equal checks - you can think of them as a sort of special #define.
 
//declare the enumeration _type_
enum BirdState {FLYING, LANDING, STANDING, TAKEOFF, EATING, SLEEPING};

//create a variable of it (in c or c++)
enum BirdState bs1 = SLEEPING;
//create a variable of it (in c++ only)
BirdState bs2 = SLEEPING;

//compare state
if (bs1 == EATING)
   bird1.hungry--;

//set and compare state
if (bs1 == TAKEOFF && bird1.velocity > 0.3)
   bs1 = FLYING;
 
There are some differences between enums in C and C++. First, in C++ you do not need the enum keyword when declaring a variable. Second, in C++ you cannot use general integer operators (such as arithmetic and bitwise operators) on enumerations
 
enum BirdState bs2;  // legal in C and C++
BirdState bs3;       // legal in C++ only

typedef enum BirdState BirdState_t
BirdState_t bs4;     // can use typedef like this
                     // to make it legal in C as well

bs2++;               // Illegal in C++
bs3 = 2;             // Illegal in C++
bs4 = bs2 | bs3;     // Illegal in C++
 

Polymorphic Structures in C

This can be achieved with a little creative union and struct work. The basic idea is to have a structure representing a superclass, which contains a union of all the other subclasses.
You will need another entity (preferably an enumeration) in the superclass and all subclasses to determine what type of struct it is.
Example:

typedef struct{
   int type;
   float ypos;
   float xpos;
   float length;
   float height;
} Shape_Triangle

typedef struct{
   int type;
   float ypos;
   float xpos;
   float length;
} Shape_Square

typedef struct{
   int type;
   float ypos;
   float xpos;
   float radius;
} Shape_Circle

typedef union{
  int type;
  Shape_Square square;
  Shape_Triangle triangle;
  Shape_Circle circle;
} Shape;

...

Shape s = getShape();
switch(s.type)
{
   case SHAPE_SQUARE:
      s.Shape_Square.length=3;
      break;
   case SHAPE_TRIANGLE:
      s.Shape_Triangle.height=4;
      break;
   case SHAPE_CIRCLE:
      s.Shape_Circle.radius=5;
      break;
}

A drawback of this method is that you need to duplicate the members in the substructure, and you must make sure the type variables are all in the same physical position (first is best) in the struct/union. Alternatively, use a struct for the superclass and subclass:

typedef struct{
   float length;
   float height;
} Shape_Triangle

typedef struct{
   float length;
} Shape_Square

typedef struct{
   float radius;
} Shape_Circle

typedef union{
  Shape_Square square;
  Shape_Triangle triangle;
  Shape_Circle circle;
} Shape_Union;

typedef struct{
   int type;
   float xpos;
   float ypos;
   Shape_Union subshape;
}

...

Shape s = getShape();
switch(s.type)
{
   case SHAPE_SQUARE:
      s.subshape.Shape_Square.length=3;
      break;
   case SHAPE_TRIANGLE:
      s.subshape.Shape_Triangle.height=4;
      break;
   case SHAPE_CIRCLE:
      s.subshape.Shape_Circle.radius=5;
      break;
}


This requires extra typing "through" the union.

Bit Masks in C

Bit masks are where you specify the number of bits to use in a integral member of a class or struct. C has more restrictions than C++ on this. In particular, only "int", "signed int" or "unsigned int" can have bit masks in C. Many C compilers ignore bit masks altogether.
First rule of bit masks: Don't. Don't unless you have a really bad need to save a tiny amount of memory, and slowing down your code a lot isn't a problem (the compiler will have to work around things as they are not properly aligned). Bit masks are also inherently non-portable and differ on different compilers on different machines. Some compilers will ignore them totally.
If you really want to go ahead with it, all you do is put a colon after the member followed by the number of bits it should occupy. Here's an example:

struct TwelveHourTime
{
   unsigned hour     : 4;     //4 bits (16), enough for 1-12
   unsigned minute   : 6;     //6 bits (64), enough for 0-59
   unsigned am       : 1;     //1 bit, on for am off for pm
};

//   0 1 2 3 4 5 6 7 8 9 A
//  |_ _ _ _|_ _ _ _ _ _|_|
//    hour     minute    am 

You can use bit masks with a blank identifier to add some padding:

struct TwelveHourTime
{
   unsigned hour     : 4;     //4 bits (16), enough for 1-12
   unsigned minute   : 6;     //6 bits (64), enough for 0-59
   unsigned          : 5;     //5 unused bits
   unsigned am       : 1;     //1 bit, on for am off for pm
};

//   0 1 2 3 4 5 6 7 8 9 A B C D E F
//  |_ _ _ _|_ _ _ _ _ _|_ _ _ _ _|_|
//    hour     minute    (unused)  am 

You can a blank identifier with bit mask of 0 to force the next element to align to the boundary of the given type:

struct TwelveHourTime
{
   unsigned hour     : 4;     //4 bits (16), enough for 1-12
   char              : 0;     //push minute to the next byte boundary
   unsigned minute   : 6;     //6 bits (64), enough for 0-59
   unsigned am       : 1;     //1 bit, on for am off for pm
};

//   0 1 2 3 4 5 6 7 8 9 A B C D E
//  |_ _ _ _|_ _ _ _|_ _ _ _ _ _|_|
//    hour  (unused)  minute     am

Again, bit masks are very non-portable and the exact layout depends on the compiler and platform. The diagrams are a guide only.

Wednesday, 9 May 2012

Writing log files for Applications in C# with time stamp

 A sample code which creates a log file (one per day & instance) 
and puts in time-stamped log entries into it. The file names are such 
that sorting them in Windows File Explorer is very easy for the SysAdmin
 
 
using System.IO;
public void WriteLogLine(string sCallerName, string sLogFolder, 
                        long lCallerInstance, string sLogLine)
{
  lock(this)
  {
    string sFileName;
    sFileName = String.Format("{0}_{1:yyyy.MM.dd}_{2:00}.log", 
                  sCallerName, DateTime.Now, lCallerInstance);
    StreamWriter swServerLog = 
           new StreamWriter(sLogFolder + sFileName, true);
    swServerLog.WriteLine(
           String.Format("[{0:T}] {1}", DateTime.Now, sLogLine));
    swServerLog.Close();
  }
}

Title: Get the description of a Enum value.

Some times it is required to get the Enum description to be used inside your drop down control 
or list box control or some where else, here is a small program that will help you to do this.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Reflection;
using System.Text;

namespace LinkedIn.Utility
{
  /// <summary>
  /// A helper class for enums.
  /// </summary>
  public static class EnumHelper
  {
    /// <typeparam name="TValue">usually int</typeparam>
    public static List<TValue> GetValues<TEnum, TValue>()
    {
      List<TValue> values = new List<TValue>();
      Array array = Enum.GetValues(typeof(TEnum));
      foreach (TValue item in array)
      {
        values.Add(item);
      }

      return values;
    }

    /// <summary>
    /// Get the description of a <see cref="Enum" /> value.
    /// </summary>
    /// <param name="value">The value.</param>
    /// <returns>A description of the <see cref="Enum" /> value.</returns>
    public static string GetDescription(Enum value)
    {
      FieldInfo fieldInfo = value.GetType().GetField(value.ToString());
      DescriptionAttribute[] attributes =
            (DescriptionAttribute[])fieldInfo.GetCustomAttributes(
            typeof(DescriptionAttribute), false);

      return (attributes.Length > 0) ? attributes[0].Description : value.ToString();
    }

    /// <summary>
    /// </summary>
    /// <typeparam name="TEnum"></typeparam>
    /// <param name="enumeratedType"></param>
    /// <param name="value"></param>
    /// <returns></returns>
    public static bool HasFlag<TEnum>(this TEnum enumeratedType, TEnum value)
        where TEnum : struct, IComparable, IFormattable, IConvertible
    {
      if ((enumeratedType is Enum) == false)
      {
        throw new InvalidOperationException("Struct is not an Enum.");
      }

      if (typeof(TEnum).GetCustomAttributes(
          typeof(FlagsAttribute), false).Length == 0)
      {
        throw new InvalidOperationException("Enum must use [Flags].");
      }

      long enumValue = enumeratedType.ToInt64(CultureInfo.InvariantCulture);
      long flagValue = value.ToInt64(CultureInfo.InvariantCulture);

      if ((enumValue & flagValue) == flagValue)
      {
        return true;
      }

      return false;
    }
  }
}

Enjoy............!