Archive for the ‘Uncategorized’ Category

How to get session or other custom values into ELMAH

November 10th, 2008 by Sameer | No Comments | Filed in Uncategorized

In “Timing is Everything” I mentioned how I successfully managed to convince management to install ELMAH.  I wanted to add some comments as to how to easily get some values into ELMAH that you might have in your SESSION.

The easy way, with no code changes, is simply store those values in a COOKIE.

HttpCookie c = new HttpCookie("CUSTOMVAL");
c.Value = (string) Session["CUSTOMVAL"];
Response.Cookies.Add(c);

Viola! It will be in the ELMAH Error page!

Setup ASP.NET 1.1 on VISTA

October 7th, 2008 by Sameer | 2 Comments | Filed in Uncategorized

As strange as it sounds, yes, you might need to setup ASP.NET 1.1 and VISUAL STUDIO 2003 to work on VISTA.

Here’s how to do it. I read maybe ten other pages and tried tons of different things but this is the definite guide on how to make ASP.NET/VS2003 work on Vista.

Thanks dude!

A few comments about developing on Vista. I am running a lenovo T61 (Vista 32bit) with 2GB ram with VS, IIS7, SQL Server 2008 with Full Text catalog, and the whole works, so when memory was getting full (i.e. had Outlook open, Excel open, as well as all that other stuff) it was actually TOTALLY FREEZING for literally 5 minutes a time (even the clock was frozen).

I managed to remedy this problem by buying and using a ReadyBoost compatible USB disk and I don’t have this problem any more. Try it out. I think it’s a pretty creative and useful feature that they put in Vista!

Learn Faster

October 3rd, 2008 by Sameer | 1 Comment | Filed in Uncategorized, Visual SourceSafe, Work Related

Change of atmosphere is actually a much faster way to learn, as I recently found out due to a job change.  A lot of time spent in the same environment working with the same people and learning stagnates.  If you really want to learn something different, be bold, take a risk, and change jobs.  Another factor is type of company – changing company types can increase learning speed by working in a different environment.  Technical skills are not the only skills that matter, so keep that in mind.  By looking at how different companies work together and achieve goals is a learning experience in itself.  I was concerned that moving from a team with many talented developers to moving to a team of one developer (me) my learning would stagnate.  However, this is not the case.  I feel like I’ve learned so much in the last few days just by being in a different environment.  Take risks!  Be bold!

Factors to note

- Background of those you are working with
- People who you are working with (non technical)
- Location of new job/environment
- Number of work hours
- SMALL or LARGE COMPANY
- Technology used (is it old, is it new… )

You can find a lot of these things out by asking in the interview.  There are implications for each one of the factors above.  For example, large companies are more resistant to change.  They are usually late followers in adopting new technologies.  However, some people feel that in large companies they have job security…  So it all depends.

I think Justin of CodeThinked (a nice .NET blog that I subscribe to) sums it up pretty well why he changed jobs.

Keep in mind we humans are fussy beings.  We don’t like change (most of us, anyway).  You might find a lot of things uncomfortable in your new position.. It will take a while to adjust to the new area, new coworkers, new boss, and so on.   But hey, life is about taking risks, right?  Can’t be complacent all the time.

System.Collections.Generic.Dictionary.Insert

August 21st, 2007 by Sameer | No Comments | Filed in Uncategorized

Code for System.Collections.Generic.Dictionary<TKey,TValue>.Insert(TKey, TValue, Boolean)

Try compare this to System.Collections.Hashtable.Insert .  They are similar in many ways.

 

private void Insert(TKey key, TValue value, bool add)
{
    int index;
    if (key == null)
    {
        ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
    }
    if (this.buckets == null)
    {
        this.Initialize(0);
    }
    int num = this.comparer.GetHashCode(key) & 0x7fffffff;
    for (int i = this.buckets[num % this.buckets.Length]; i >= 0; i = this.entries[i].next)
    {
        if ((this.entries[i].hashCode == num) && this.comparer.Equals(this.entries[i].key, key))
        {
            if (add)
            {
                ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_AddingDuplicate);
            }
            this.entries[i].value = value;
            this.version++;
            return;
        }
    }
    if (this.freeCount > 0)
    {
        index = this.freeList;
        this.freeList = this.entries[index].next;
        this.freeCount--;
    }
    else
    {
        if (this.count == this.entries.Length)
        {
            this.Resize();
        }
        index = this.count;
        this.count++;
    }
    int num4 = num % this.buckets.Length;
    this.entries[index].hashCode = num;
    this.entries[index].next = this.buckets[num4];
    this.entries[index].key = key;
    this.entries[index].value = value;
    this.buckets[num4] = index;
    this.version++;
}

System.Collections.Hashtable.Insert

August 21st, 2007 by Sameer | No Comments | Filed in Uncategorized

Here is the source code for System.Collections.Hashtable.Insert(Object, Object, Boolean)

 

[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
private void Insert(object key, object nvalue, bool add)
{
    uint seed;
    uint incr;
    if (key == null)
    {
        throw new ArgumentNullException("key", Environment.GetResourceString("ArgumentNull_Key"));
    }
    if (this.count >= this.loadsize)
    {
        this.expand();
    }
    else if ((this.occupancy > this.loadsize) && (this.count > 100))
    {
        this.rehash();
    }
    uint num3 = this.InitHash(key, this.buckets.Length, out seed, out incr);
    int num4 = 0;
    int index = -1;
    int num6 = (int) (seed % this.buckets.Length);
Label_0071:
    if (((index == -1) && (this.buckets[num6].key == this.buckets)) && (this.buckets[num6].hash_coll < 0))
    {
        index = num6;
    }
    if ((this.buckets[num6].key == null) || ((this.buckets[num6].key == this.buckets) && ((this.buckets[num6].hash_coll & 0x80000000) == 0)))
    {
        if (index != -1)
        {
            num6 = index;
        }
        Thread.BeginCriticalRegion();
        this.isWriterInProgress = true;
        this.buckets[num6].val = nvalue;
        this.buckets[num6].key = key;
        this.buckets[num6].hash_coll |= (int) num3;
        this.count++;
        this.UpdateVersion();
        this.isWriterInProgress = false;
        Thread.EndCriticalRegion();
    }
    else if (((this.buckets[num6].hash_coll & 0x7fffffff) == num3) && this.KeyEquals(this.buckets[num6].key, key))
    {
        if (add)
        {
            throw new ArgumentException(Environment.GetResourceString("Argument_AddingDuplicate__", new object[] { this.buckets[num6].key, key }));
        }
        Thread.BeginCriticalRegion();
        this.isWriterInProgress = true;
        this.buckets[num6].val = nvalue;
        this.UpdateVersion();
        this.isWriterInProgress = false;
        Thread.EndCriticalRegion();
    }
    else
    {
        if ((index == -1) && (this.buckets[num6].hash_coll >= 0))
        {
            this.buckets[num6].hash_coll |= -2147483648;
            this.occupancy++;
        }
        num6 = (int) ((num6 + incr) % ((ulong) this.buckets.Length));
        if (++num4 < this.buckets.Length)
        {
            goto Label_0071;
        }
        if (index == -1)
        {
            throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_HashInsertFailed"));
        }
        Thread.BeginCriticalRegion();
        this.isWriterInProgress = true;
        this.buckets[index].val = nvalue;
        this.buckets[index].key = key;
        this.buckets[index].hash_coll |= (int) num3;
        this.count++;
        this.UpdateVersion();
        this.isWriterInProgress = false;
        Thread.EndCriticalRegion();
    }
}

.NET Data Structures, Algorithms and Patterns Implementation

August 14th, 2007 by Sameer | No Comments | Filed in Uncategorized

Here are some common data structures implemented in .NET C# that you can download for free and even contribute to the project if you like (open source).  Actual links to the source code for each of the below algorithms to be added in the near future.  Learning these Computer Science algorithms and patterns will allow you to more effectively write your code.  For example, if your data is already sorted, then it would make sense to use an algorithm such as Binary Search, that depends on a sorted list.  Also, these below implentations are not included in the original .NET 2.0 CLR, so if you are looking for a generalized Priority Queue or Red Black Tree you will need to download the below code.  Keep in mind it is not perfect, and it is NOT for everyone, but it is a good starting point.  Wikipedia has details on most of the below algorithms such as Merge Sort which will explain in which cases it would be good to use and which cases it would not be so good.

Actual links to the source code for each of the below algorithms to be added in the near future.  This page is still being improved.

Association<TKey, TValue>
VisitableHashTable<TKey, TValue>

Bubble Sort
Summary: Repeatedly swap elements until the order is correct.  Works fast if the list is almost sorted.  Doesn’t work so well if you have small elements near the bottom of the list.

Dijkstra’s Single Source Shortest Path algorithm
Summary: Graph "greedy" algorithm that solves the single-source shortest path problem for a directed graph with non negative edge weights.

Bag<T>

VisitableLinkedList<T>

Bucket Sort
Summary: Bucket sort is not a comparison sort, uses buckets, and in some cases can run in linear time


Prim’s Minimal Spanning Tree Algorithm
Summary: A graph algorithm that finds a minimum spanning tree.

BinaryTree<T>
Summary: A tree that each node has at most 2 children.  This implementation is a generic tree of type T.  For example you can create a Binary Tree of integers, or a Binary Tree of strings, or whatever you like.

VisitableList<T>

Cocktail Sort , Shaker Sort
Summary: Also known as bidirectional bubble sort, is both a stable sorting algorithm and a comparison sort.

BinarySearchTree<TKey, TValue>

VisitableQueue<T>

Comb Sort
Summary: An improved bubble sort that rivals the speed of Quick Sort

Deque<T>

VisitableStack<T>

Gnome Sort
Summary: A sort similar to insertion sort but uses a series of swaps to get the right order of elements.  Runs in O(n2) time.

Fibonacci number generation.
Summary: Fibonacci numbers represent a pattern of reproduction numbers found in nature, such as how the population of rabbits will grow over time.  Here are a few values:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, …

GeneralTree<T> 
Summary: An implementation of a tree in .NET

Heap Sort
Summary: Usually slower than quicksort, a ‘selection sort’ algorithm that works worst case O(n log n).  As well its in-place but not a ‘stable sort’.

Euclid’s Algorithm  (also known as Euclidean algorithm)
Summary: An algorithm to find the GCD (greatest common divisor) of two numbers.  For example on 16, 18, the GCD is 2.

Graph<T> 
Summary: An implementation of a graph in .NET

Insertion Sort
Summary: Very simple but also very slow sort.

Heap<T>
Summary: A heap is a specialized tree type data structure. (more details to be added).

Merge Sort
Summary: A classic divide and conquer algorithm that works by breaking up the data into two parts and sorting each one recursively.  It runs in O(n log n) time.

Matrix 

Odd-Even Transport Sort 

Pascal Set
Summary: You can perform operations on set such as Set Union, Set Difference, Set Intersection, etc.

Quick Sort 
Summary: A popular sorting algorithm that works in O(n log n) time on average. 

Priority Queue<T> 

Selection Sort
Summary: An in place sorting algorithm (meaning it does not require extra storage space) that performs in O(n
2) time, meaning it is not usually practical for large lists, but is known for its simplicity.
SkipList<TKey, TValue> 

Sorted List<T> 

Shell Sort
Summary: An improvement over insertion sort.  Runs in O(n log 2 n)

Red Black Tree<T>
Summary: Self balancing binary search tree (i.e. even if you insert too much it will automatically reorganize itself into a binary search tree).  It can amazingly search, insert, and delete in O(log n) time, meaning if you have 1000 elements, it will take roughly 3 operations to complete!

ReadOnlyPropertyCollection <T, TProperty>

Object Matrix<T>   

Hash List<TKey, TValue> 

Complex Number
Summary: The complex number (also known as imaginary number) i has the value Square Root of -1.  You can do math on complex numbers using this class.

Circular Queue
Summary: A queue that loops around

Splay Tree
Summary: Another self balancing search tree.  Runs in O(log n) amortized time.

Kruskal’s Algorithm
Summary: A graph algorithm that finds a minimum spanning tree for a connected weighted graph.

Hypotenuse

Tons of stuff to the Matrix and ObjectMatrix classes.

Vectors

Topological Sort for the Graph data structure.
Summary: Sorts your graph topologically (i.e. a linear ordering of its nodes).

Radix Sort
Summary: Integer sorting algorithm that works on individual digits.


Download it here (ZIP format, binaries, Version 1.3 Alpha)

(Released under the Microsoft Permissive License)
Originally posted here, and the new page is here that includes the source code incase you want to play around with it and possibly submit a better implementation you might have thought up!

Our .NET articles

June 13th, 2007 by Sameer | No Comments | Filed in Uncategorized

Looking for the rest of our .NET C# articles?  Look no further – Our articles are here

SqlHelper Source Code (MS Data Access Block)

June 8th, 2007 by Sameer | No Comments | Filed in Uncategorized

SqlHelper is part of the Data Access Blocks Released by Microsoft.

The Application Blocks created by Microsoft are "best practices" for each of the different blocks they have implemented.  The Data Access Block is meant to give you best practices to connect to Sql Server.

You can download the Application Data Access Blocks v2 here (installation + source code from Microsoft)

You can view the Source Code for SqlHelper here (online HTML format)

Here is the compiled ApplicationBlocks DLL and XML file incase you do not have permission to install or you only want the DLL+XML Documentation

In order to use it, either put the source code (.cs files) in your App_Code subfolder, or put the .dll in your Bin subfolder.

By using this intermediate layer between the database and your source code, you also have the option or ability to make system wide changes to the way your SQL connections are handled, which can come in handy in the future.

For example, you can add a line to your SqlHelper source to insert a record into a ‘history table’ of some sorts after every insert or delete operation.  If you are directly calling SqlCommand to insert, you will not have the ability to do that.

Enjoy :)