Friday, July 16, 2010

Use Fiddler to Debug An ASP.NET Page

If you are using Windows Server 2008 you won't be able to view HTTP response/requests while working with ASP.NET applications that are hosted on LocalHost. To be able to monitor the request/responses that are initiating from your local machine include a "." after the localhost so Instead
http://localhost:4303/Default.aspx
try
http://localhost.:4303/Default.aspx
There is also one option in Fiddler which can cause problems and has to be turned off So in Fiddler goto Tools --> Fiddler Options -->General Tab --> Uncheck "Enable IPv6 (if available)"

An interpretation of "Application Domains" in .NET

An Application Domain is an abstraction of a library/process. .NET provides Application Domains to abstract away the concept of processes from the underlying operating system. We can think of Application Domain as the process/library that is on top of CLR, not the process/library that is on top of the actual operating system. That's what makes .NET, platform independent!

SharePoint Extensibility with Excel Web Services

SharePoint 2007 supports an extensibility mechanism using Web Parts.
ASP.NET Web Part controls are an integrated set of controls for creating Web sites that enable end users to modify the content, appearance, and behavior of Web pages directly in a browser.
Excel Services is part of Microsoft Office SharePoint Server 2007 which is built on ASP.NET and Windows SharePoint 3.0 technologies. Using Excel Web Services we can create Web Parts which can be dropped into SharePoint and add custom functionality into it. More Here Using Excel Web Services in a SharePoint Web Part

"Run As Administrator" From the command line

Both Vista And Server 2008 emphasize on using "Run As..." option to provide a more secure environment. For those that are interested in using the command-line it might be annoying to right click on each application that they want to "Run as Administrator" especially for developers. Here is the sequence to get the applications "Run as Administrator" (I used to create a shortcut for the application and in the "Advanced" options of the shortcut properties check the "Run As Administrator") Press Windows button, in the immediate text box that appears type the name of the application that you want to run e.g. cmd, then instead of pressing Enter, press Ctrl+Shift+Enter which might ask you to provide user-name password but then you can save it. Do not overuse this option, things like internet explorer (iexplore) don't need to be run as an admin.

How to Open an MDF file!

That might be wrong to ask "how to open an MDF file". Although the data comes as a file, DB engine needs extra information while opening this file which comes with other files including the log information. So when we use Microsoft SQL Server Express the right way to say that is to "Attach to an MDF file"

Bind a DropDownList in ASP.NET to an enum

It is quite common to bind a DropDown control in an ASP.NET page to an Enum. the right syntax is
 ddlWeekDays.DataSource = Enum.GetNames(typeof(EnumWeekDays)); ddlWeekDays.DataBind();

iFrame in an ASP.NET page

iFrame controls are standard HTML controls and are not available as an ASP.NET object in the code behind file. If you want to access this object the only way to do that is to find the control and set the attributes of the control manually For example if the control is named myIFrame in the HTML file in a code-behind event handler we can get a hold on the control by calling
 HtmlControl myCodeBehindAcceddToIFrame = (HtmlContrl)this.FindControl(myIFrame); 
To set one of its attributes we can make a call similar to
 myCodeBehindAcceddToIFrame.Attributes["src"] = "…new url..." 

.NET Immutable vs. Mutable objects

Mutable: Changeable
Immutable: Unchangeable

Immutable objects

  • Remain constant after they are created.

  • Their internal state always remain valid

  • They are thread safe and multiple readers can read them simultaneously.

  • They are perfect for atomic, immutable value types e.g. a person's address

  • We can define the members of such class using the "readonly" keyword

  • To construct an immutable object we have to either provide a proper .ctor or a factory method

.NET Compile-Time constants vs. Run-Time constants

There are two types of constants in .NET (C# to be more specific)

  • Compile-Time constants are defined using the keyword "const"

  • Run-Time constants are defined using the keyword "readonly"



Compile-Time constants are relatively faster than run-time constants but are less flexible. Generally speaking run-time constants are better than compile constants despite the fact that they might be slightly slower.



//Compile-Time constant
public const int Pi=3.14;
//Run-Time constant
public static readonly float Pi=3.14;



Compile-Time constants are resolved at compile time, and their value will be placed directly in the code, even across the assemblies.

An Overview of ASP.NET Architecture

Application Life Cycle Events

  • IIS Picks up the request

  • IIS looks for the server extension

  • If the extension is .aspx then IIS maps the request into aspnet_isapi.dll

  • aspnet_isapi.dll hosts an ASP.NET worker process that creates an HTTP Pipeline

  • The Http Pipeline object hosts objects like HttpRuntime, HttpApplicationFactory, and HttpWorkerRequest

  • The HttpApplicationFactory either creates a new HttpApplication or selects an existing one from the pool of applications

  • The appropriate PageHandlerFactory will be called



Page Life Cycle Events
The events that are executed in the life cycle of the page

  • Page_Init (Create Page Controls and initialize them)

  • LoadViewState (Restores the view state of the page)

  • LoadPostData (Populates the controls with previously posted data)

  • Page_Load (To bind data from database to controls)

  • RaisePostDataChangedEvent

  • RaisePostBackEvent (It is only raised if there is a postback)

  • Page_PreRender (Right before rendering)

  • SaveViewState

  • Page_Render

  • Page_UnLoad



ASP.NET ArchitectureWe can write custom handlers to override these events

Source
A Nice Article

Design Patterns: Chain of Responsibility

It is one of those design patterns that have a very fundamental idea but their usage under this specific title is limited. The idea of the pattern which converges with other design patterns is that we have to decouple a "Requester" from a specific "Handler" by introducing a chain of handlers that are derived from a parent "handler" class. As the request "bubbles up" a chain of handlers, eventually it will be handled by one of them.

A classic example is an "Approval" that has to be obtained from a certain office. As the client turns in his request for the approval, it starts to travel from employee to his boss and then to the boss's boss etc... until someone in this chain is in a position to approve the request.

Major Players of this pattern are:

  • Handler (The abstract Employee)

  • Real Handlers (The main players - Programmer, Manager, CEO)

  • Client



The idea is common as part of the Windows event handling mechanism. For example UI programmers have noticed different UI events (Painting event) that are bubbled up along the chain of parent-child windows, until one of them handles it.


class Program
{
static void Main(string[] args)
{
// Setup Chain of Responsibility
Employee h1 = new Programmer();
Employee h2 = new Manager();
Employee h3 = new CEO();
h1.SetBoss(h2);
h2.SetBoss(h3);

// Generate and process request
int[] inquiries = { 1, 2, 3, 3, 2, 4, 1, 1 };

foreach (int inquiry in inquiries)
{
h1.Approve(inquiry);
}

// Wait for user
Console.Read();
}
}

abstract class Employee
{
protected Employee Boss;

public void SetBoss(Employee boss)
{
this.Boss = boss;
}

public abstract void Approve(int inquiry);
}

class Programmer : Employee
{
public override void Approve(int inquiry)
{
if (inquiry <= 1)
{
Console.WriteLine("Inquiry approved by the employee");
}
else if (Boss != null)
{
Boss.Approve(inquiry);
}
}
}

class Manager : Employee
{
public override void Approve(int inquiry)
{
if (inquiry <= 2)
{
Console.WriteLine("Inquiry approved by the manager");
}
else if (Boss != null)
{
Boss.Approve(inquiry);
}
}
}

class CEO : Employee
{
public override void Approve(int inquiry)
{
Console.WriteLine("Inquiry approved by the CEO");
}
}

Design Patterns: Adapter

Let's say you are working on an application which has different layers (upper layers are using the lower layers). Now there is a new requirement, and you have to add a new component to the lower layer but you will realize that there is already an "older piece of code" that does the same functionality, so instead of implementing a new component from scratch you want to use this older code, but the problem with the older code is that it does not completely follow the specification of your application and you can not simply drop it into your existing code. This is a perfect scenario to use an "Adapter", A piece of code that encapsulates that older code and exposes its functionality in terms of the interface that is in place.

Major Players of this pattern are:

  • Target (An abstract base class for the adapters)

  • Adapter

  • Adaptee (The older piece of code)

  • Client



The idea is common in .NET framework, for example every time you use a legacy COM component and import it into .NET, what happens is that the imported code will be wrapped inside an adapter .NET class (interop assembly) that translates the functionality and patterns that were common in the COM era to the .NET era. For example if a method fails to operate properly in COM, it will return a non-zero HRESULT value; this functionality is changed by the adapter (interop assembly) to raise an exception instead (which is more common in .NET)


class Program
{
static void Main(string[] args)
{
//The client has no idea about the older code
Target target = new Adapter();
target.NewerMethod();
}
}

class Target
{
public virtual void NewerMethod()
{
Console.WriteLine("Called Target-NewerMethod");
}
}

// The actual "Adapter"
class Adapter : Target
{
//Points to the older piece of code
private Adaptee adaptee = new Adaptee();

public override void NewerMethod()
{
adaptee.OlderMethod();
}
}

// "Adaptee"
class Adaptee
{
public void OlderMethod()
{
Console.WriteLine("Called OlderMethod");
}
}

Hash Table vs. STL's map

Based on "Programming Pearls" page 161
The favorite data structure in the implementation of STL's sets and maps is a balanced search tree. These containers are based on these balanced trees to perform better in find and retrieval procedures; as a result, implementation of a dictionary requires the usage of such a mechanism that is not necessary optimized in "insertion" scenarios, as an alternative we can use a custom hash table + hash algorithm that performs much faster in inserting the words into a dictionary. Here is a basic comparison of these two methods STL's map container
 #include  #include  #include  #include  #include   using namespace std;  int main(int argc, char* argv[]) {   const static char* InputFilePath  = argv[1];   const static char* OutputFilePath = argv[2];    if(argc != 3)   {     cout << "The first argument is the input file path,"       " and the second one is the output file path"       << int=""> mapWords;    //Read Data   ifstream fileInput(InputFilePath);   string word;    cout << "Clock Before Read Map:" <<>> word)     mapWords[word]++;    cout << "Clock After Read Map:" << int="">::iterator mapIterator;    cout << "Clock Before Write Map:" << mapiterator =" mapWords.begin();">first                    << "\t\t\t\t"                    <<>second                   <<>
Running on a text file of the Bible The result is: Clock Before Read Map:1 Clock After Read Map:8428 Clock Before Write Map:8430 Clock After Write Map:8830 Press any key to continue . . . The following version uses a cusom hash table + hash algorithm, notice the read time
 #include  #include  #include  #include   using namespace std;  struct node {   char *word;   int count;   node* next; };  #define NHASH 22189 #define MULT 31 node* bin[NHASH];  unsigned int hash(const char *p) {   unsigned int h = 0;   for(; *p; p++)     h = MULT * h + *p;   return h % NHASH; }  void incword(string word) {   int hashCode = hash(word.data());   node* hashNode;   for(     hashNode = bin[hashCode];     hashNode != NULL;     hashNode = hashNode->next)   {     if(strcmp(word.data(), hashNode->word) == 0)     {       hashNode->count++;       return;     }   }    hashNode = new node();   hashNode->count = 1;   hashNode->word = new char[word.size()];   strcpy(hashNode->word, word.data());   hashNode->next = bin[hashCode];   bin[hashCode] = hashNode; }  int main(int argc, char* argv[]) {   const static char* InputFilePath  = argv[1];   const static char* OutputFilePath = argv[2];    if(argc != 3)   {     cout << "The first argument is the input file path,"       " and the second one is the output file path"       << counter =" 0;">> word)   {     incword(word);   }    cout << "Clock After Read Hash:" << counter =" 0;" hashnode =" bin[counter];" hashnode =" hashNode-">next)     {       fileOutputHash          <<>word          << "\t\t\t\t"          <<>count          <<>
Output: Clock Before Read Map:1 Clock After Read Map:8428 Clock Before Write Map:8430 Clock After Write Map:8830 Press any key to continue . . .

Find a Substring

The conventional way of finding a substring with size m in a string of n characters is implemented here, the performance is m*n and not really exciting. A better approach is using a data structure called “Suffix Array”
 #include  #include   using namespace std;  int find_substring(const char* mainString, const char* subString) {   assert(mainString);   assert(subString);    int iFoundIndex = 0;    const char* subPointer;   bool bFound;    for(; *mainString != 0; mainString++, iFoundIndex++)   {     for(bFound = true, subPointer = subString;       *subPointer != 0;       ++subPointer)     {       if(*(mainString + ((int)subPointer - (int)subString))               != *subPointer)       {         bFound = false;         break;       }     }      if(bFound)       return iFoundIndex;   }    return -1; }

Agile Software Development

On February 2001 a group of high profile engineers got together and started discussing different Extreme Programming (XP) methodologies, they came up with a new term for all light-weight process methodologies called "Agile" Agile has a manifesto. As it name implies, it is a set of 12 simple rules that each process must pursue to be effective The highlights of Agile
  • "The best architectures, requirements, and designs emerge from self-organizing teams. ": People are more important than processes or tools, as a result we have to see each person as a groups of peers rather than manager/developer hierarchies. Each person will be important as much as he/she wants to be important (It is unfortunate though!)
  • “Working software is the primary measure of progress”: There is a greater emphasis on working code rather than documentation; it is a good practice to have documentation unless it threatens productivity as a result it is good to invest on automated documentation.
  • "Welcome changing requirements, even late in development. Agile processes harness change for the customer's competitive advantage.": Being agile and responsive and dynamic is more important than following a plan. Customers are more important than the contracts and plans

How VC++ and G++ treat uninitialized variables

Here is a sample code that demonstrates a basic C++ application and the different behavior represented by Visual C++ and GCC compilers regrading uninitialized variables
 #include  #include   #define LEARN_UNINITIZLIED_REAL_TYPES  //main can return void or int for VC compiler //main has to return int for GCC compiler int main() { #ifdef LEARN_UNINITIALIZED_INT  int iIsInitialized = 123;  printf("iIsInitialized = %d\n", iIsInitialized);   //Some random value  auto int iautoUninitialized;  //Warning C4700 from VC at compile time, exception         //at run-time (run-time check failure) -858993460  //No warning from GCC, no exception at run-time:         //the value is 1628438944  printf("iautoUninitialized = %d\n", iautoUninitialized);   //Some random value  int iUninitialized;  //Warning C4700 from VC at compile time, exception         //at run-time (run-time check failure) -858993460  //No warning from GCC, no exception at run-time:         //the value is 0 (after we call the previous auto         //value it becomes zero)  printf("iUninitialized = %d\n", iUninitialized); #endif  #ifdef LEARN_UNINITIZLIED_POINTERS  //C4700 from VC compiler, First run-time check         //failure that can be supassed but after that         //we get access violation exception  //that terminates the application  //GCC doesn't complain and actually runs         //it and shows some value  auto int* myIninitializePointerToInt;  printf("myIninitializePointerToInt = %d\n",                *myIninitializePointerToInt); #endif  #ifdef LEARN_UNINITIZLIED_REAL_TYPES  //Unlike integer ojbects, real number objects         //can contain values that correspond to         //no genuine number like NAN  //NAN (Not a number), math.h has especial         //implementation defined values corresponding         //to no actual real numbers.  float fNAN = log((float)-2);   //VCC: -1.#IND00  //GCC: -inf  printf("fNAN = %f\n", fNAN); #endif   return 0; } //For GCC compiler there must be a new line //at the end of file

printf, sprintf, and stdout

stdout or standard output is the stream where an application writes its it. It is the text terminal that has initiated the application; but we have the chance to redirect the output into something else. printf writes its output into the stdout whereas sprintf writes its output into the memory, sprintf is more flexible in terms that it is faster and we can also write the data later into a text terminal. If you notice there is a parameter for sprintf that is a pointer to character, this is the string array that is allocated in memory, but printf is writes data directly into the output stream; that is why printf doesn't need an extra char*parameter

Some string manipulation

Reverse a string
 void ReverseString(char* string) {   if(string == NULL)     return;    int iCharCounter = 0;   for(iCharCounter = 0           ; *(string + iCharCounter) != 0           ; iCharCounter++);    for(int iCharReverse = 0           ; iCharReverse < tempswap ="             *(string">
Make all characters uppercase
 void ToUpper(char* string) {   if(!string)     return;    while(*string)   {     if( ('a' <= *string) && (*string <= 'z') )     {       *string = *string + 'A' - 'a';     }      string++;   }    return; } 
Convert an string of digits to a number(atoi)
 //atoi function: accepts an input string, //extracts all digits from the beginning of //the string and returns the final number int ascii_to_integer(char* string) {   if(!string)     throw std::invalid_argument(       "Null string is not accepted");    int retVal = 0;    if(('0' > *string) || (*string > '9'))     throw std::invalid_argument(       "There must be at least one digit at the beginning of the string");    while( ('0' <= *string) && (*string <= '9') && (*string != 0))   {     retVal = (retVal * 10) + (*string - '0');     string++;   }    return retVal; }  
Print an integer using only putchar
 //Prints an integer using only putchar void print_integer(int value) {   if((value / 10) == 0)   {     putchar('0' + value);   }   else   {     print_integer(value / 10);     putchar('0' + (value % 10));   } }

Recursive vs. Iterative

Here are two famous recursive algorithms that are implemented with iterative algorithmFactorial
 //Find n! using a recursive algorithm int FactorialRecursive(int n) {   int retVal = 1;    if( n < retval =" n" retval =" 1;" numcounter =" 1;">
Fibonacci
 //Fibonacci in recursive f(n) = f(n-1) + f(n-2) //Not a good solution, it doubles the stack size //each time is performs one operation int FibonacciRecursive(int n) {   if(n < n ="="" n ="="" n ="="" n ="="" iminus2sum =" 1;" iminus1sum =" 1;" isum =" 0;" iiterator =" 1;" isum =" iMinus2Sum" iminus2sum =" iMinus1Sum;" iminus1sum =" iSum;">

printf("%d");

Depends on the compiler, and the result is unpredictable:
  1. G++ doesn't complain and compiles, not even a warning, the output is a random number
  2. VC++ compiler complains with C4313, the output is zero
  3. Intel C++ complains with warning #267 the result is a random number

Initialization vs. Assignment

Initialization and assignment are two distinct operations in both C and C++, yet they have the similar outcome, that is why the distinctions are confusing. The difference is more clear in C++. In C argument passing is assignment but in C++ argument passing is initialization; similarly, function return is an assignment in C but an initialization in C++. There are situations where initialization and assignment have different outcomes one example is working with references.

References

The initializer for a non-const T& must be a modifiable lvalue of type T; hence these two conditions are invalid
 double &rd1 = 0.0; double &rd2 = i; 
The initializer of const T& may be any type convertible to T and also it can be an rvalue; hence these two conditions are valid
 const double &rd1 = 0.0; const double &rd2 = i; 
are both valid (the compiler uses temporary objects to resolve these two conditions)

Overriding vs. Overloading

Some excerpts from Dan Saks' article from C++ User's Journal February 1994 Overloading means declaring the same symbol in the same scope to represent two or more different entities. Overriding means redefining a name in a derived class to hide a name inherited from a base class. Overriding is all about parent-child relationship, it is not just about virtual functions. For a given class the translator creates an entry in the vtbl only for each virtual function in the class, not for the non-virtual functions. A derived class can override any of its inherited functions, be they virtual or not. You can't turn off the dynamic binding when you override a virtual function. The translator creates an image for child's vtbl by coping the parent's vtbl, when it parses a declaration in child that overrides a virtual function the translator simply overwrites teh entry for that function in child's vtbl.

Storage Class Specifiers

Excerpts are from an excellent article by Dan Saks from CUJ November 1997 Titled "Storage Classes and Linkage" There are three types of Decl-Specifiers
  1. Storage Class Specifiers(extern, static, mutable, auto, register)
  2. Type Specifiers(float, int, unsigned...)
  3. Function Specifiers(virtual, inline)
Every object and function declaration has two parts:
  1. decl-specifier-sequence(a sequence of decl-specifiers in any order)
  2. declarator-list(a comma-separated list of one or more declarators)
There can be more than one type specifier in the declaration but we can not have more than one storage specifier unsigned long int *p; //Is Valid extern mutable int value;//Is invalid In C++ a declaration introduces a name into a program, and specifies attributes for that name. If the declarator-id in the declaration designates an object or function, and the declaration reserves storage for that object or function then that declaration is also a definition. Rules of thumb
  1. A function declaration is a definition if it includes the function's body.
  2. An object declaration is a definition unless
    1. It contains the extern specifier with no initializer
    2. It declares a static data member in a class declaration
C and C++ provide for three levels of linkage
  1. A name with external linkage denotes an entity that can be referenced via names declared in other scopes in the same or different translation units
  2. A name with internal linkage denotes an entity that can be references via names declared in other scopes in the same translation unit
  3. A name with no linkage
Linkage at namespace scope
  • if a symbol has no storage class or it has extern specifier it has external linkage
  • if it has static specifier it has internal linkage
  • if it is using const specifier it has internal linkage by default unless it is also using extern (it has to be initialized because it is const! unless it is using extern and it makes sense!)
Rules of thumb
  • An object or function has internal linkage if it is explicitly declared static or previously declared with internal linkage
  • A const object has internal linkage if it is neither explicitly declared extern nor previously declared with external linkage
  • Otherwise and object or function at namespace scope has external linkage
In the block scope there is no linkage unless we use extern

A misunderstanding regarding STL containers

You might hear quotes like
vectors are dynamic arrays
or
lists are linked lists
these are not precise definitions. Although in practical situations it is safe to think of vectors as dynamic arrays or lists as linked lists (especially with the level of abstraction that we employ while designing our code); there is a whole different idea behind it. Standard Template library's perception of vector is something that provides cheap and fast access to the items; similarly, list is a container that performs item insertion and removal at its minimum cost, definitely when the implementers of these classes are doing their job, their first choice for internal representation of these structures are arrays and linked lists, but it is an excellent practice to think of them as independent concepts. If you think of a list as a linked list and an iterator as a pointer then it is hard to accept one of the main ideas behind containers and iterators that saysthese are two standalone entities, because linked list and pointers are completely one body.

STL Containers

There are two categories of STL containers
  • Sequence containers: Variable sized and store elements in the original order
    • std::vector, C-style array that is re-sizable and must be the default choice. Element access can be performed in constant time. We can access the elements with a pointer like syntax *(vect.begin() + location).
    • std::list, doubly linked lists
    • std::deque, a vector that can be used to add items at the beginning
  • Sorted Associative Containers: Hold data in a sorted data structure and are optimized for fast lookup of elements
    • std::set, fast lookup of the elements, uses its own find algorithm
    • std::multiset
    • std::map, key value pair instead of plain objects
    • std::multimap, stores more than one key-value pair that have the same key

Polymorphism

Polymorphism, although mostly referred to virtual function usage, can actually be categorized into two different types
  • Static Polymorphism: refers to the ability of having overrided functions in one scope
  • Dynamic Polymorphism: Refers to the ability to override functions that are called virtual in the parent class
Please notice that if we have a non-virtual function in the parent class and weoverride it in the child class it is still called Static Polymorphism. Lots of people use the terminology in the context of virtual functions, but it is better to consider the actual meaning that is "has many forms" The other important misunderstanding that is related somehow, is that C++ not only introduced polymorphism in form of virtual function overriding, it also introduced function overloading. Function overloading was not a part of the C language and is new in C++.

Bitmapped Graphics

Just to sharpen my bits and bytes teeth, I decided to implement a Bitmapped graphics surface. The definition is simple and you can find it in most C++ books. We have a (Length * Height) screen of bits. All of the bits are placed inside a byte array. Implement a class with two basic functions of setting and resetting the bits in each.(15 + 37) MyBitmap.h
 class MyBitmap { public:  MyBitmap(int length, int height);  ~MyBitmap(void);   void set(int iHPos, int iVPos);  void reset(int iHPos, int iVPos);   void printBitmap();  private:  int _length;  int _height;  char* _pBitHolder;   void validateCoordinate(int iHPos, int iVPos); }; 
MyBitmap.cpp
 MyBitmap::MyBitmap(int length, int height) {  if( ((length * height) % 8 ) != 0)   throw std::invalid_argument(                   "Length by Height must be dividable by 8");   _length = length;  _height = height;  const int bitHolderSize = (length * height) / 8;  _pBitHolder = new char[bitHolderSize];  for(int iInitializer = 0; iInitializer < itotalbitcount            =" iVPos" ibytecounter            =" iTotalBitCount" ibitcounter             =" iTotalBitCount" itotalbitcount            =" iVPos" ibytecounter            =" iTotalBitCount" ibitcounter             =" iTotalBitCount"> iHPos)   throw std::out_of_range(                 "Invalid Argument for iHPos");  if(0 > iVPos)   throw std::out_of_range(                 "Invalid Argument for iVPos");  if(iHPos >= _length)   throw std::out_of_range(                 "Invalid Argument for iHPos");  if(iVPos >= _height)   throw std::out_of_range(                 "Invalid Argument for iVPos"); }  void MyBitmap::printBitmap() {  int iTotalBitCount = 0;  int iByteCounter = 0;  int iBitCounter  = 0;   for(int iRowCounter = 0;                  iRowCounter < icolcounter =" 0;" itotalbitcount                           =" iRowCounter" ibytecounter                           =" iTotalBitCount" ibitcounter                            =" iTotalBitCount" cholderbyte                           =" _pBitHolder[iByteCounter];">

Bitwise operator's tricks and questions

To find out if a value is even
return ((i & 1) == 0)
To see if a number is a power of 2 (2^n)
return ((i & -i) == i); or return ((i & (i -1)) == 0); //By My Friend Zolio
Bitwise Tricks Bit Twiddling Hacks

An integer to ascii implementation

Using Basic C++
 #define ENOUGH_SIZE 10  char* itoa_plain(int value) {   char* digits = new char[ENOUGH_SIZE];   char* temp = new char[ENOUGH_SIZE];    digits[0] = '\0';    do   {     int lastDigit = value % 10;     value = value / 10;          temp[0] = lastDigit + '0';     temp[1] = '\0';      strncat(temp, digits, strlen(digits));     strcpy(digits, temp);    }while(value != 0);    return digits; }  
Using standard library
 char* itoa_standard(int value) {   std::string digits;    do   {     int lastDigit = value % 10;     value = value / 10;      digits.insert(digits.begin(), lastDigit + '0');    }while(value != 0);    const unsigned long resultSize = digits.length();   char* result = new char[resultSize];   digits.copy(result, resultSize);   result[resultSize] = 0;    return result; }

Binary Tree

How to find the depth of a binary tree
 struct Node {   Node(int value)   {     _value = value;     _left = NULL;     _right = NULL;   }    Node* _left;   int _value;   Node* _right; };  int MaxDepth(const Node* root) {   if(root == NULL)     return 0;    int iLeftDepth = MaxDepth(root->_left);   int iRightDepth = MaxDepth(root->_right);    return (iLeftDepth > iRightDepth)          ? (iLeftDepth + 1)          : (iRightDepth + 1); }

Finding the Greatest Common Divisor

It is Euclid's method on finding the GCD. Although there are several applications for this algorithm, finding the GCD of two numbers is the most famous one.
 int findGreatestCommonValue(unsigned int m, unsigned int n) {   if( (m == 0) || (n == 0) )     throw exception();    //Ensure that m is greater than n   //otherwise swap them   if(m < temp =" n;" n =" m;" m =" temp;" remainder =" m" m =" n;" n =" remainder;" remainder =" m">

XSLT on .NET

Template instructions => to match the root document Defines the transformation rules for the nodes that match the XPath expression set in the match attribute Applies all the possible templates to the elements that match the XPath description To apply an XSL to an XML add this to the XML file When you know that only one template applies to a given block of XML source code, you might want to use a more direct instruction: but you have to give the target template a name

XPath on .NET

  1. XPath defines a common syntax for accessing XML nodes through the XML DOM as well as from XML Stylesheet language tranformation
  2. System.Xml.XPath is the parent namespace for XPath functionality in .NET framework
  3. XPath expression => Run time evaluation engine => Against a data source (XML DOM)
  4. XPath expressions are always evaluated in the context of a node (context node similar to current directory)
  5. The result of execution is a context node set
  6. XML DOM (Select nodes within the context of the XMLDocument class)
  7. An XML Node Name is the Namespace + Local Name
  8. An XPath expression returns: Boolean, String, Number, or Node-Set
Context of an XPath query:
  • Context Node (XmlNode.SelectNodes or XmlNode.SelectSingleNode)
  • Context Node-set(axis like drive letters)
  • Position (Ordinal position of the context node in the context node-set to which it belongs)
  • Size (The number of nodes being parsed by expression)
  • Namespace
  • Variable binding
  • Standard library of functions
Location Path:
  • Absolute path starts with forward slash /
  • Relative path is in the context of the context node
Location path => Location step/location step/location step A Fully Qualified Path (axis::node-test[predicate])
  1. Axis
    1. self
    2. child
    3. descendant
    4. ancestor
    5. following
    6. following-sibling
    7. preceding
    8. preceding-sibling
    9. attribute
  2. Node-test => Sequence of node names in the node-set
  3. Predicate => criteria
Abbreviations for axis:
  • . for context node
  • .. for parent node
  • no axis for child::
  • @ for attribute
  • * for all
Sample XPath queries To get all children with name attribute = "AttName"child::*[@Name='AttName'] To get all the attribute nodes attribute::* To get those that have the name attribute regardless of the value child::*[@Name] To find the last child child::*[position() = last()] Get the first next node following-sibling::*[position() = 1] To get all of the processing instructions /processing-instruction() To get all of the processing instructions that the name starts with "proccins_sheet" /processing-instruction()[starts-with(local-name(), "proccins_sheet")]To get all the processing instructions that the value starts with "Name="style-sheet" /processing-instruction()[starts-with(string(), 'Name="style-sheet')]

An Excellent Article about interviewing in general

Here is an excellent article on interviewing.

Bit Twiddling

A very thorough article on bit twiddling called Bit Twiddling Hacks, must read

Reflection in C#

There are several scenarios in C# that reflection comes into use
  • Every time we use "is" and "as" operators
  • Every time we use data bindings for user controls
  • The ValueType.Equals and ValueType.operator== are implemented using reflection only
  • Serialization uses reflection
And several other scenarios, but there is one interesting case that is not well-known and that is when we write unit tests. There are situations where we want to write a unit test for a function that is private to a class, this is where we can use reflection to get access to that function and call it. Here is a sample code that we can use to access a private static member of a class, the same routine can be used to invoke a private member function(The difference is that for static members we don't need instantiation )
 try {   System.Reflection.Assembly assembly =  Assembly.LoadFile(/*Path*/);    Console.WriteLine("Full Name:{0}\nName:{1}\nMajor Version:{2}\n                             Minor Version:{3}\nCodeBase:{4}"  , assembly.FullName  , assembly.GetName().Name  , assembly.GetName().Version.Major  , assembly.GetName().Version.Minor  , assembly.CodeBase);    Type[] allTypes = assembly.GetTypes();   foreach (Type type in allTypes)   {  FieldInfo[] fieldInfos = type.GetFields(                BindingFlags.Static | BindingFlags.NonPublic);  foreach (FieldInfo fieldInfo in fieldInfos)  {    Console.WriteLine("Field name:{0}                                   , Declaring Type:{1}                                   , Filed Type:{2}                                   , Static:{3}"                 , fieldInfo.Name                 , fieldInfo.DeclaringType.ToString()                 , fieldInfo.FieldType                 , fieldInfo.IsStatic);     if (fieldInfo.IsStatic)    {      Console.WriteLine("Static = {0}"                      , fieldInfo.GetValue(null));      fieldInfo.SetValue(null                      , 200);             Console.WriteLine("Static = {0}"                      , fieldInfo.GetValue(null));    }        }   }   Console.WriteLine("Done Loading Assembly"); } catch (Exception exception) {   Console.WriteLine(exception.Message); }

Design Patterns: Singleton in C++ and C#

There are certain situations where there has to be one and only one instance of a class (or any component) in a problem domain. The best practice in these situations is to let the class itself to manage its instantiation process, this pattern of creational behavior is called Singleton.
This pattern is not necessary related to a class. for example in COM there are situations where we need to have one instance of a COM component, this component can be a collection of classes, still this is called Singleton
Depending on the language there are different ways to implement this pattern. The only common point is that it is implemented by the class itself, and it is the class itself that manipulates its instantiation process. All the client requests for instantiation will go through one particular channel and will end-up in retrieving one similar instance. The first request for instance retrieval will cause instantiation, the subsequent requests will retrieve the already created instance. C++
  • The constructor of the class must be either private or protected, by making it non-public any attempt for regular instantiation will fail.
  • There must be one Instance method that builds the instance for the first time or returns the same instance if it already exists. This instance method must be static for one good reason, we can’t call it from an instance variable because there is no way to have instance variables! It must be a member of the class because it needs to access the private constructor.
  • There is one member instance of the class that is defined static so it is accessible to the static instance method Class
/////////Header File class ASingleInstanceClass { private://To seal the class   ASingleInstanceClass()   {   }  public:   static ASingleInstanceClass* GetInstance();  private:   static ASingleInstanceClass* m_instance; };  ////////////CPP File #include "ASingleInstanceClass.h"  ASingleInstanceClass* ASingleInstanceClass::m_instance = NULL;  ASingleInstanceClass* ASingleInstanceClass::GetInstance() {   if(m_instance == NULL)   {     m_instance = new ASingleInstanceClass;   }    return m_instance; } 
C# We can employ the same approach in C# to create a singleton class; however C# has this new capability called static constructors that can be used instead
public sealed class ASingleInstanceClass {   static readonly ASingleInstanceClass instance     = new ASingleInstanceClass();    static ASingleInstanceClass()   {   }    ASingleInstanceClass()   {   }    public static ASingleInstanceClass Instance   {     get     {       return instance;     }   } }

Standard C++ file I/O

We want to use C++ to read a text file line by line, sort the content and write the result back to a new text file. We assume the file size is small enough to fit into the memory, several edge cases are not covered; although the power of STL will cover most of them!
 //See: http://www.cppreference.com/cppio/index.html //The  library allows programmers to do file //input and output with the ifstream and ofstream classes #include  #include  #include  #include   using namespace std;  int main(int argc, char* argv[]) {   const static char* InputFilePath  = argv[1];   const static char* OutputFilePath = argv[2];    //At least two arguments must be provided   if(argc != 3)   {     cout << "The first argument is the input file path,"       " and the second one is the output file path" <<> setFileData;    //Read Data   ifstream fileInput(InputFilePath);   copy( istream_iterator (fileInput)         , istream_iterator ()         , inserter(setFileData, setFileData.begin()) );    //Write Sorted Data   ofstream fileOutput(OutputFilePath);   copy( setFileData.begin()         , setFileData.end()         , ostream_iterator(fileOutput, "\n"));    return 1;
}

Binary, Decimal, Hexadecimal

Each hexadecimal digit represents 4 binary bits 0000 => 0 and 1111 => F

Big O notation

I am preparing for interviews. These are the points that I extracted from Analyzing Algorithm Performance about big O notation.
  • When we say that one algorithm is more efficient than another one it means that is uses less resource.
  • By resource we mean CPU cycles and Computer Memory; however due to the fact that the price of computer memory is constantly decreasing, it mostly refers to the CPU Cycles or the duration of the execution
  • The other important concern is with significant differences in efficiency
  • Since we are only interested in significant differences between algorithms, we can ignore everything except the dominant terms and express the algorithm growth function in terms of the order of magnitude of the growth rate or O(N)
  • This allows the analyst to ignore computer/compiler/coding tricks. When evaluating an algorithm and focus on the general behavior of the algorithm.
  • O(1) time to perform the algorithm is constant and does not depend on the size of the problem
  • O(log2N) time requirement is logarithmic
  • O(N) time requirement is linear
  • O(Nlog2N) is N logarithmic (N logarithmic growth rate)
  • O(N2) time requirement is quadratic (quadratic growth rate)
  • O(N3) time requirement is cubic (cubic growth rate)
  • O(2N) time requirement is exponential (exponential growth rate)
  • The performance of many algorithms is based on the data there are three cases we consider (Base case, average case, and worst case)
 // Sequential search = O(N) int find1(int n, char array[MAX_STR][MAX_LEN],char key[MAX_LEN]) {    int i;     for(i=0;i<>
 //O(log2 N) int find2(int n, char array[MAX_STR][MAX_LEN],char key[MAX_LEN]) {    int low  = 0;    int high = n-1;    int mid;     int outcome;     while( low <= high )    {       mid = (low+high) / 2;       outcome = strcmp(array[mid],key);       if( outcome==0 )     return(mid);       else if( outcome < low =" mid+1;"> 0 )     high = mid-1;    }     return(-1); }

ACM-ICPC International Collegiate Programming

Home Page

Wikipedia

2006 problems

2007 problems

2008

A Sample Blog

Extra Link

Function Templates

Function templates are functions that are parameterized so that they represent a family of functions; it means that we can have the same functional behavior for different data types.

They start with the keyword "template"
 template   template  inline T const& max(T const& a, T const& b) {  return a <>
The process of replacing template parameters by concrete types is called "instantiation", and mere use of a function template will trigger instantiation; it means that we don't have to instantiate it manually. Templates are compiled twice:
  1. Without instantiation
  2. At the time of instantiation (Can break the regular rules of compile/link)
When we call a function tempalate the template parameters are determined by the arguments we pass, in this case the compiler follows a procedure called "Argument deduction" All the parameters that we pass to a template must conform to the same datatype, there is no capability for type promotion for example max(4, 4.0) will fail instead we have to write max(4, 4.0) Function templates have two kinds of parameters
  1. Template parameters T, one type of template parameters are "type parameters" that are declared using "typename" keyword
  2. Call parameters
Because the types of the call parameters are constructed from the template parameters, template and call parameters are usually related. WE call this concept "function template argument deduction" Like ordinary functions, function templates can be overloaded
  inline int const& max (int const& a, int const& b) {   return a <> inline T const& max(T const& a, T const& b) {   return a <> inline T const& max(T const& a, T const& b, T const& c) {   return ::max (::max(a, b), c); }

Multitasking and Multithreading

The quotes are mostly come from the book Pro .NET 1.1 Remoting, Reflection, and Threading Threading refers to an application’s capability to handle executing more than one instruction set at a time. Multitasking refers to an operating system’s capability to run more than one application at a time. There are two types of multitasking
  1. Cooperative multitasking: An application executes until it cooperates with other applications by releasing the processor to them
  2. Preemptive multitasking: An application is allowed to execute for a short period before it is involuntarily interrupted by the operating system. The processor actually grants time to the process. This period is called time slice or a quantum. This style of sharing the processor time has a few problems
    1. Accessing the shared data (Is solved by synchronization)
    2. The cost of context switching
Process is a physical separation of memory and resources. Each process has at least one execution sequence called thread. The registers in use on the CPU define this thread, the stack used by the thread, and a container that keeps track of the thread’s current state. This container is called Thread Local Storage (TLS). A TLS for a thread, contains the registers, stack pointers, scheduled information, address spaces in memory, and information about other resources in use. The concept of spawning new threads within the same process is known as free threading. For computers that have more than one process, it is possible to set the ProcessAfinity property of the System.Diagnostics.Process class for all the threads of the process to run on one CPU. Windows knows when it needs to make a decision about thread scheduling by using interrupts. An interrupt is a mechanism that causes the normally sequential execution of CPU instructions to branch elsewhere in the computer memory without the knowledge of the execution program. When the thread comes to the interrupt, Windows uses a special function known as an interrupt handler to store the thread’s state in the TLS. To abort a thread we have to send the abortion request from another thread. A priority of 0 means that the thread is idle. Priorities between 16 and 31 means that the threads are real-time (Device drivers, file systems, input devices). As long as threads of a higher priority exist, threads in lower priority are not scheduled for execution.

Linked Lists

Linked Lists Versus Arrays
  • Arrays are fixed size
  • An array orders its items physically and needs to shift its data after we insert or remove an item
  • For arrays the entire array is stored in one block of memory
  • Array access with indexes is implemented using the fast address arithmetic
  • For fixed size arrays that are larger than 8K the virtual memory will take care of the wasted part
  • An array allocates memory for all its elements lumped together as one block of memory, but linked list allocates memory for each element separately
Pointer Allocation in C++
 //Static allocation, compiler allocation, stack int * p; //Dynamic allocation, runtime allocation, heap int* p = new int; 
How to allocate an array
 int* myArray = new int[50]; //myArray[0] *myArray; //myArray[1] *(myArray + 1); //Deleting delete [] myArray; 
More LinksEach linked list starts with a head pointer that is an ordinary local variable placed on the stack but the list nodes are allocated on the heap