About Me

My photo
Kozyatağı, İstanbul, Türkiye

Wednesday, December 11, 2013

An Algorithm for Restricting CPU Usage of CPU Bound Programs


For a CPU bound program which requires multi thread execution, we sometimes need certain number of processor cores to be used by our program and other cores to be left unassigned so that, other processes may utilize them.

Let's make the idea more clear:
I develop an exe application which performs long running calculations, such as running heuristic algorithms. During the calculations, I want to reserve some CPU resource for other processes so that my program will not "eat up" all the CPU resource.


Processor assignment can be achieved by setting processor affinity to threads:



C# Code:
        [DllImport("kernel32")]
        static extern int GetCurrentThreadId();

        static int unusedProcessorCount = 1;

        static void SetProcessorAffinity(int threadOrder)
        {
            int curThreadId = GetCurrentThreadId();
            int processorOrder = threadOrder % (Environment.ProcessorCount - unusedProcessorCount);
            int processorAddress = 1 << processorOrder;
            foreach (ProcessThread th in Process.GetCurrentProcess().Threads)
            {
                if (th.Id == curThreadId)
                {
                    th.ProcessorAffinity = (IntPtr)processorAddress;
                }
            }
        }



We can specify the number of cores that we want to be unassigned by setting the variable "unusedProcessorCount".

In the code above, the function that fetches current thread id needs to be imported from kernel32.dll. 

As soon as the function that thread executes is called, this function needs to call SetProcessorAffinity by passing its thread order so that the thread is assigned to the processor which comes up next.

Sunday, December 1, 2013

Retrieving All System Details by Windows PowerShell

Have you ever heard about Windows PowerShell? PowerShell is a great scripting tool for administrative tasks on computer.

So why is it "power"? Because it extends standard shell scripting with the power of .NET Framework. While accessing standard "command let"s of PowerShell, you can use any .NET Framework class. In addition to this, standard cmdlet library of PowerShell is quite enough for basic tasks that a system administrator may need.

Common Scenario: I want to display, all essential details of any computer on network. I want something quite more "advanced" than typing systeminfo on Windows command prompt.
The details I need are:             

n  Computer Name
n  Operating System,
n  Model
n  Manufacturer
n  Last Bootup Time
n  IP Address
n  Physical Memory Details: Capacity of each RAM on slots
n  Processor Details: For each  physical processor; number of cores, number of logical processors
n  Logical Disk Details: For each disk, free and total size
n  Process Details: Process name, Id, Memory Usage, Percent Load

We can achieve all, for any computer on network, by specifying computer name only.

Here is the script:
(You can run this script on Windows PowerShell ISE)


$computername = Read-Host 'Please Enter Computer Name'

$Name = Get-WmiObject win32_OperatingSystem -computer $computername | Select csName
$OperatingSystem = Get-WmiObject win32_OperatingSystem -computer $computername | Select Caption
$Model = get-wmiObject Win32_ComputerSystem  -computer $computername | select Model
$Manufacturer = get-wmiObject Win32_ComputerSystem  -computer $computername | select Manufacturer
$LastBootTime = Get-WmiObject Win32_OperatingSystem -computer $computername | select csname, @{LABEL='LastBootUpTime'; EXPRESSION={$_.ConverttoDateTime($_.LastBootupTime)}}
$PhysicalMemoryList = Get-WmiObject Win32_PhysicalMemory -computer $computername | select DeviceLocator, @{Name='Capacity_MB'; Expression={$_.Capacity / 1024 / 1024}}
$FreeMemoryMB = get-WmiObject Win32_PerfRawData_PerfOS_Memory -computer $computername | select AvailableMBytes 
$DiskList = Get-WmiObject Win32_LogicalDisk -computer $computername | select Caption, Description, @{Name="Total_Size_GB"; Expression={$_.Size/1024/1024/1024}}, @{Name="Free_Size_GB"; Expression={$_.FreeSpace/1024/1024/1024}}
$ProcessorList = Get-WmiObject Win32_Processor -computer $computername  | select Name, NumberOfCores, LoadPercentage, NumberOfLogicalProcessors
$allIpList = [System.Net.Dns]::GetHostEntry($computername) | select AddressList
$IP = ''
foreach ($item in $allIpList.AddressList)
{
 if ($item -notlike '*:*')
 {
  $IP = $item
 }
}

$ResObject = @{
ComputerName = $Name.csName
OperatingSystem = $OperatingSystem.Caption
Model = $Model.Model
Manufacturer = $Manufacturer.Manufacturer
LastBootUpTime = $LastBootTime.LastBootUpTime
FreeMemoryMB = $FreeMemoryMB.AvailableMBytes
IPAddress = $IP.IpAddressToString
#PhysicalMemoryList = $PhysicalMemoryList | Format-Table
#DiskList = $DiskList | Format-Table
#ProcessorList = $ProcessorList | Format-Table
}

$ResObject | Format-List

Write-Host 'Physical Memory Details: '
$PhysicalMemoryList | Format-Table

Write-Host 'Disk Details: '
$DiskList | Format-Table

Write-Host 'Processor Details: '
$ProcessorList | Format-Table

$answer = Read-Host "Do you want to get process details? Yes[Y]; No[N]"
if ($answer.ToUpper() -ne 'Y')
{
 Read-Host 'Script Ended'
 Exit
}

$procListDef = Get-WmiObject win32_process -computer $computername | select Name, ProcessId, @{Name='Owner'; Expression={$_.getowner() | select Domain, User}  }
$procListResource = get-WmiObject Win32_PerfFormattedData_PerfProc_Process -computer $computername | select Name, IDProcess, PercentProcessorTime, Timestamp_Sys100NS, WorkingSet

foreach ($proc in $procListDef )
{
 $ownerFullName = $proc.Owner.Domain + '\' + $proc.Owner.User;
 $res = $procListResource | Where-Object {$_.IDProcess -eq $proc.ProcessId}
 $percent = $res.PercentProcessorTime / [Environment]::ProcessorCount;
 $ws = $res.WorkingSet / 1024 / 1024
 
 $proc | Add-Member -type NoteProperty -name OwnerName -value $ownerFullName 
 $proc | Add-Member -type NoteProperty -name MemoryInMb -value $ws
 $proc | Add-Member -type NoteProperty -name PercentProcessorTime -value $percent
}

$procListDef | select Name, ProcessId, OwnerName, MemoryInMb, PercentProcessorTime | sort PercentProcessorTime -Descending | Format-Table
Read-Host 'Script Ended'

Sunday, October 6, 2013

Sql Server Delayed Query Execution: Delay until databases available


In some scenarios, the databases that our query references, may disappear for a period of time and we need to wait until these target databases are available for querying.

Continuously looking at Sql Server Management Studio Object Explorer and wait the database to be online is a quite boring activity.

Common scenario: In Data Warehouse (DWH) environment, the databases we are querying refreshes in regular period from production (live) environment. Generally, this period is daily. During the refresh period, target databases disappear and they are inaccessible until  new version is restored. This process takes several hours for enterprise databases.

This kind of wait operation can be assigned to a T-SQL query, so our query runs immediately when target databases are available (in ONLINE state).

Firstly, here is the stored proc that determines whether databases are in ONLINE state:

CREATE PROC.IS_DB_READY @IS_READY BIT OUTPUT
AS
BEGIN
 SET @IS_READY = 1

 DECLARE @DATABASE_NAME_LIST TABLE (DATABASE_NAME VARCHAR(100))

 -- Insert here the names of the databases
 -- that you're waiting to be online.
 INSERT INTO @DATABASE_NAME_LIST
 SELECT 'myDatabaseName1'

 INSERT INTO @DATABASE_NAME_LIST
 SELECT 'myDatabaseName2'

 ------------------------------------------------------------------------
 IF EXISTS (
   SELECT 1
   FROM @DATABASE_NAME_LIST L
   LEFT JOIN sys.databases D WITH (NOLOCK) ON L.DATABASE_NAME = D.NAME
   WHERE ISNULL(D.state_desc, '') <> 'ONLINE'
   )
 BEGIN
  SET @IS_READY = 0
 END
END


Now we can write the proc that delays the execution until databases are online:


CREATE PROCEDURE DELAY_UNTIL_DB_READY
AS
BEGIN
 DECLARE @IS_DB_READY BIT

 WHILE 1 = 1
 BEGIN
  EXEC IS_DB_READY @IS_DB_READY OUTPUT

  IF @IS_DB_READY = 0
   WAITFOR DELAY '00:00:10'
    -- Wait for 10 seconds.
    -- Equivalent of C# Thread.Sleep(10000);
  ELSE
   BREAK;
 END
END


Now developer only needs to execute the procedure for delaying execution until all databases are in online state.
Sample usage:
EXEC DELAY_UNTIL_DB_READY
-- Your queries to run after databases become online

Sunday, September 29, 2013

Compare IL Content of .dll and .exe Files (Assemblies)


In the programs we develop, sometimes we need to be sure if versions of the compiled code (.dll, .exe)  we wrote are equivalent of each other on various environments.

To concretize the scenario, let's consider this:
In enterprise solutions, generally there are many environments prior to production environment. In my case, these environmets are:

-- DEV: Development.
-- UAT: User Acceptance Test.
-- PREPROD: Pre-Production.
-- PROD: Production. (LIVE)

At the source control side, each of them has corresponding branch. (In my case, I have branches in TFS).
After developer is finished with development phase, he performs merge operations on branches in order to make his code tested and running on target environment.

Sometimes, developer cannot be sure if the running code is the same as he merged. So he needs to check, if the running assembly (.dll, .exe) version is the same as he coded, or some problem occured while merging the branches.

To smooth away these kind of suspicion, contents of assemblies can be compared to check if they are equal.
In a "headlong" way, if such a comparison is performed in bitwise manner, the result of the comparison will be incorrect. Because, compiler may put some code-irrelevant details into the assembly at the moment of compilation, which should not affect the result of comparison. For example, CSharp compiler injects date and time of build into the dll. These kind of details does NOT affect the code running in dll.

The comparison program should compare equality of running code in assembly, and only this.
So, the only way to check: Inspecting MSIL (Microsoft Intermediate Language), or IL in short, in the assembly, which is the output of compiler and input of JIT compiler.

We can retrieve IL content of an assembly through ildasm.exe, Microsoft IL disassembler tool which is shipped with Visual Studio.

After IL content is written to a text file, the program we write can compare to generated IL's line by line. If any line is different, then we can say these two assemblies are different.

Some points to consider:
-- The IL output of ildasm.exe contains comment lines. These lines need to be removed before comparison.
-- The compiler may inject GUID attributes to some types. So, the user may need to have an option of ignoring Guid attributes.

Steps of comparison
-- Call ildasm.exe to generate IL content and redirect the output text file
-- When .exe terminates, read text file newly created.
-- While reading the text file, line by line, remove comments by Regexy (//.*)
-- Merge lines and remove guid attributes with regex.
-- Compare two strings. If they are equal, then IL contents in asssemblies are equal.


Code:
        string GetIL_ContentOfAssembly(string assemblyPath, bool ignoreGuidAttribute)
        {
            string tmpFileNameWithoutExt = Guid.NewGuid().ToString();
            string tempFileNameIL = string.Format("TmpIL_{0}.il", tmpFileNameWithoutExt);
            StoreIL_InTextFile(assemblyPath, tempFileNameIL);
            StringBuilder sb = new StringBuilder();
            using (StreamReader sr = new StreamReader(tempFileNameIL))
            {
                string str = null;
                while ((str = sr.ReadLine()) != null)
                {
                    str = RemoveComments(str);
                    sb.AppendLine(str);
                }
            }
            string res = sb.ToString();
            if (ignoreGuidAttribute)
            {
                res = RemoveGuidAttributes(res);
            }
            return res;
        }


        string RemoveComments(string input)
        {
            return Regex.Replace(input,
                                 @"//.*",
                                 string.Empty);
        }

        string RemoveGuidAttributes(string input)
        {
            return Regex.Replace(input,
                                 @"(\.custom instance void \[mscorlib\]System\.Runtime\.InteropServices\.GuidAttribute::\.ctor\(string\) = \().[^.]*",
                                 string.Empty,
                                 RegexOptions.Multiline);
        }

        void StoreIL_InTextFile(string assemblyPath, string tempFileName)
        {
            ProcessStartInfo info = new ProcessStartInfo
            {
                FileName = ildasmPath,
                Arguments = string.Format("\"{0}\" /output:{1}", assemblyPath, tempFileName),
                CreateNoWindow = true,
            };
            Process proc = new Process();
            proc.StartInfo = info;
            proc.Start();
            proc.WaitForExit();
        }

The ildasmPath is read from .config file in this example, which is set to: C:\Program Files\Microsoft SDKs\Windows\v6.0A\Bin\ildasm.exe

You can dowlonad the solution here

Sunday, September 22, 2013

Rule Expression User Input Validation

If you are developing a business rule engine; your application needs to have an admin page that rules are defined through.

For example, imagine we are creating campaign rules:
"If the sum of the amounts of customers transactions within last 24 hours exceeds 10.000 or count exceeds 10 then send him an SMS"

In the rule definition pane, admin user inputs an expression like: "(R1 || R2) && R3"
Rule expressions are generally written in a free text format by the user.  Because user may insert parentheses, group rules and combine them.

The input of user has to be validated before saving it. Because syntax of such an expression above may be incorrect, may have missing parentheses, etc.

The easiest and effortless way of performing this validation is, using JavaScript eval() function:

function IsValidRuleText() {
    var txt = $('#txtInput').val();
    if (txt.length == 0) {
        return false;
    }
    var replaced = txt.replace(/R\d+/gi, "true");
    try {
        if (eval(replaced) == true) {
            // Trivial Comparison. Just for test if throws error.
        }
    } catch (err) {
        return false;
    }
    return true;
}

All the numbered [R] expressions are determined with regex. Then regex matches are replaced with "true" string. Now, final string contains "true" words and punctuation characters ((, ), &&, || ). If the "eval()" function successfully evaluates the replaced expression, then the expression is valid. If it throws error, then the expression has syntax errors.

Counting Records Effectively: Reducing Redundant Counting

Sometimes, we need to query database for retrieving count of records that satistfies some condition.
If the count, which is returned from query, is used for comparing to a constant; there is no need to count all of the records.

Suppose that, you have a table in Sql Server as follows:

CREATE TABLE [Users]
(
   [Id]             [BIGINT],
   [Name]           [VARCHAR](100),
   [RegistrationDate] [DATETIME]
) 


And your application code needs to know if "the Count of users whose registration day is >= 2013-01-01, is more than 100 "

 The first query coming to mind is:

SELECT COUNT(*)
FROM   Users U
WHERE  U.RegistrationDate >= '20130101' 


Suppose, you have millions of users. The query above makes you check all, just for comparing to 100, which is a redundant activity.

Now, I am changing it to:

DECLARE @N INT = 100

SELECT COUNT(*)
FROM   (SELECT TOP(@N + 1) 1 AS CNT
        FROM   Users U
        WHERE  U.RegistrationDate >= '20130101')

X 


Now, Counting terminates at server side as soon as 101 records encountered.

The main idea here is that, if I know that the value is going to be compared to 100, so I do NOT need to count if I reach 101 records. Because all the numbers greater than 101 will not affect the result of comparison.

Friday, April 5, 2013

Thread Local Storage in .NET


In a class, static fields are the most error-prone parts of the application. They need to be handled gracefully since they represent a shared resource.
One and only one instance is created for a static field. That’s why, any change on a static field directly affects all code blocks accessing to it.

Inherently, sometimes classes may need some fields to act like a static variable just for a certain execution context. Actually, here I mean “Executing Thread” while saying “Execution Context”. In other saying, some code may need to protect a static field and create its own copy in its local storage. Thus, any change caused by a thread will not affect the static value that is used by another thread.

Let’s make it clear by a real-life sample:
Suppose, you have many pages in your UI tier. Any changes that is performed on a page by a user, is sent to your Logic tier to be processed. This change is sent to your logic tier as “Message” objects.
Here we use “Command Pattern” which is one of GoF Design Patterns. Please refer to Command Pattern at: http://www.dofactory.com/Patterns/PatternCommand.aspx)

When the message is received by logic tier, the User that causes the change must be kept in a static field. Because all the remaining functions that will perform and finalize change message will need the User for logging, approval mechanisms, etc.
Similarly, Database handle must be created. Because many codes that run after receiving message are going to need Database connection.
You cannot declare these fields as totally static because it will cause to get incorrect values that is updated by another context. (For example, when the User A and User B perform update in UI tier at the same time, the update that is caused by User A may be logged as if it is updated by User B)

The main necessity here is that; User and Database Handle objects need to be static, but only for the thread that is executing message.
In .NET, there is an extremely convenient and easy-to-use solution to handle this problem. The answer is : ThreadStatic attribute.

C# Code:
class CustomerDetailsUpdateMessage
    {
        [ThreadStatic]
        public static string UserName;

        [ThreadStatic]
        public static IDbHandle DbHandle;

        // Update Inner Details.
    }

Here, when the CustomerDetailsUpdateMessage is received by logic tier, the thread that is executing the message will create its own copy of static UserName and DbHandle fields. So that any other message executing concurrently will not cause any update on the value that accessed by current thread.

Thursday, March 28, 2013

.NET Multithreading and Synchronization


Sometimes we write codes that perform a certain set of functions for many different independent values in identical way.  These set of operations may take remarkably amount of time.
For example, suppose that the program needs to calculate the salaries of all employees and write the results to database. Here is the simplest implementation:

Code:
 void RunSingleThread(List<long> employeeIdList)
        {
            foreach (var employeeId in employeeIdList)
            {
                CalculateSalaryAndWriteToDb(employeeId);
            }
        }


Since every employee is independent from each other, such a task can be performed for many employees in parallel way. Here we can utilize multithreading to shorten the time. We need to implement some steps to achieve it:

n  Decide how many items will run in parallel. As a best practice, this number should be the processor count of the machine.

Divide the list of items into separated lists. Each of these lists need to have number of parallel items at maximum.

n  In a loop, run all items of executing list in parallel and synchronize them.

n  When all items of executing list completes, skip to next list in the loop.

Here is the C# Code:
        void CalculateSalaryAndWriteToDb(long employeeId, ManualResetEvent mre)
        {
            // Make calculations that takes time.
            // Write To Database.
            mre.Set();
        }

        void RunMultiThread(List<long> employeeIdList)
        {
            int parallelItemCount = Environment.ProcessorCount;
            List<List<long>> groupedItems = GroupItems<long>(employeeIdList, parallelItemCount);
            foreach (List<long> group in groupedItems)
            {
                List<ManualResetEvent> mreList = new List<ManualResetEvent>();
                foreach (var employeeId in group)
                {
                    ManualResetEvent mre = new ManualResetEvent(false);
                    mreList.Add(mre);
                    ThreadPool.QueueUserWorkItem(o => CalculateSalaryAndWriteToDb(employeeId , mre));
                }
                WaitHandle.WaitAll(mreList.ToArray());
            }
        }

        List<List<T>> GroupItems<T>(List<T> allItems, int groupMaxCount)
        {
            List<List<T>> res = new List<List<T>>();
            int count = 0;
            List<T> temp = new List<T>();
            foreach (var item in allItems)
            {
                count++;
                temp.Add(item);
                if (count % groupMaxCount == 0)
                {
                    res.Add(temp.ToList());
                    temp.Clear();
                }
            }
            if (temp.Any())
            {
                res.Add(temp);
            }
            return res;
        }

Note that, WaitHandle.WaitAll function cannot synchronize more than 64 synchronization objects. System.NotSupportedException is thrown by .NET Framework.

Monday, March 25, 2013

Deep Copying Methods for .NET Objects


When we need to make a copy of an instance of a class, we have two different options that end up with different behaviors.

          Shallow Copy:
     Creates a new instance of class and assign values of each field from source object. This can be applied by “MemberwiseClone” method of object class.
For reference type fields, this operation causes “copying reference pointer” of field in source object. After copying, source field and destination field will be pointing to same referenced object in memory.
Code:
 class TestData
    {
        public int Id { get; set; }
        public string Name { get; set; }
        List<int> iList;

        public TestData Clone()
        {
            TestData res = (TestData)this.MemberwiseClone();
            return res;
        }
    }

Deep Copy:
Creates a new instance of object in a totally “memory separated” manner. This operation should create copy of reference types in a way that referenced instance creates a copy of itself. When the creation is complete, there must be no reference in common with source and destination object.

If all the fields of the class are value types or string type, shallow and deep copying will end up with the same result.

In .NET,  there is no direct framework help for deep copying. Deep copying is generally implemented by “Serialization-Deserialization” technique. This technique is quite subtle and easily implemented. To be honest, I was impressed when I saw it for the first time. However it has its own drawbacks, such as:

n  All the reference types that are part of copying must be marked as serializable.
n  Serialization and deserialization are relatively slow methods.

Here is the code for “Serialization-Deserialization” method.
C# Code:
 public static object DeepCopyWithSerialization(object source)
        {
            BinaryFormatter formatter = new BinaryFormatter();
            using (MemoryStream ms = new MemoryStream())
            {
                formatter.Serialize(ms, source);
                ms.Position = 0;
                object res = formatter.Deserialize(ms);
                return res;
            }

        }

I want to suggest another method which is implemented by using System.Reflection library. It is quite faster than serialization-deserialization method.
Main idea of this method is recursively creating copy of reference types until value type or string type is encountered. Here we make an exception for string class because all the strings that have the same value point to same memory area in .NET.
For initial copy of object, we need to use “MemberwiseClone” method of object class. Unfortunately, this method is protected. So we have to invoke this method by reflection over NonPublic binding flag.

C# Code:
static class DeepCopyHelper
    {
        static MethodInfo miMemberwiseClone;
        static Type stringType;
        static DeepCopyHelper()
        {
            miMemberwiseClone = typeof(object).GetMethod("MemberwiseClone", BindingFlags.Instance | BindingFlags.NonPublic);
            stringType = typeof(string);
        }


        public static object DeepCopyWithReflection(object objSource)
        {
            object objDest = miMemberwiseClone.Invoke(objSource, null);
            FieldInfo[] fiArr = GetFields(objSource);
            foreach (FieldInfo fi in fiArr)
            {
                object readValue = fi.GetValue(objSource);
                if (readValue != null)
                {
                    Type typeSource = readValue.GetType();
                    if (typeSource.IsClass && !typeSource.Equals(stringType))
                    {
                        readValue = DeepCopyWithReflection(readValue);
                    }
                }
                fi.SetValue(objDest, readValue);
            }
            return objDest;
        }

        static FieldInfo[] GetFields(object obj)
        {
            Type t = obj.GetType();
            FieldInfo[] fiArr = t.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
            return fiArr;
        }

    }

Sunday, March 17, 2013

Printing "Hello World" Without Using Semicolon (;)


This is an old question which has been asked C beginners. Actually, C code for “printing Hello World without using semicolon” is substantially easier than C# code. Here it is:
C Code:
#include <stdio.h>

void main(void)
{
 if (printf("Hello World"))
 {
 }
}

The main advantage here is that printf function returns a value, it is not void. However, Console.WriteLine function of C#, which is equivalent to printf of C, does NOT return a value. It is void.
So the question becomes, “How can I invoke WriteLine method of Console class so that the invocation returns a value?”.

The answer is “reflection”.  .NET refleciton library is quite robust for handling runtime metadata retrieveing, dynamic method invocation. Here, we need to use “MethodInfo” class, which represents a funciton of a class. MethodInfo has an “Invoke” function, which returns object!

Here is the code:

C# Code:
namespace nameSpaceTest
{
    class Program
    {
        static void Main(string[] args)
        {
            if (
                    typeof(System.Console).
                    GetMethod(
                            "WriteLine", new SystemType[] { typeof(string) })
                    .Invoke(
                        null,
                        new string[] { "Hello World!" })
                     == null
                )
            {

            }
        }
    }
}

Sunday, March 10, 2013

Efficient Way of Determining Whether a Collection Contains Element / Is Non-Empty


Determining “whether a collection is non-empty” is considered as one of the most basic and simple algorithms and generally coded as:


return collection.TakeCount() > 0;

               
For collections that can grow dynamically i.e. List, Dictionary, etc. such a code can be very costly in some circumstances.

If you’re using property of ICollection class, there is no problem. You can safely continue use them for framework collection classes since it keeps the count pre-calculated.

If you are using function of IEnumarable interface,  take a little notice. Because implementation of function over the .NET Framework collection classes calculate the count by iterating through all elements in the collection.

For collections that contain thousands or millions of element, that cost is highly redundant for such a simple “Is Non-Empty?” operation.

The code below determines “if the collection is non-empty” without counting and very quickly:

C# Code:
        static bool ContainsElement(IEnumerable coll)
        {
            if (coll == null)
            {
                return false;
            }

            foreach (var item in coll)
            {
                return true;
            }
            return false;
        }

A shortcut for IEnumerable<T> classes can be:

C# Code:
       static bool ContainsElement<T>(IEnumerable<T> coll)
        {
            return coll != null && coll.Any();
        }

Saturday, March 9, 2013

.NET Dictionary with Class Types as Key Type


In .NET, Dictionary<Tkey, Tvalue> class provides a hashed collection which improves the performance of read operations.

In most cases, type of the key element is a primitive type like int, string, long, etc. However in some scenarios, type of the key element needs to be a custom class that we implement.

In such cases, the programmer is responsible for generating “smooth” hash code and compare equality. So here, do you think programmer needs to write a “hash code generator algorithm” and dwell upon minimizing collision of generated indices?


Here is a neat implementation:
In the class, we already know the members which provide equality and we also know that each of them has GetHashCode() method.  By invoking the GetHashCode() method on each of them and by joining them, we can solve the problem of generating hash code complexity.

The operation that I mentioned as “joining hash codes” is generally implemented as applying bitwise Exclusive OR (XOR) against hash codes because it provides even distribution of generated indices.


C# Code:
class Item
    {
        public int Id { get; set; }
        public string Name { get; set; }

        public override bool Equals(object obj)
        {
            Item other = (Item)obj;
            return this.Id == other.Id &&
                   this.Name == other.Name;
        }

        public override int GetHashCode()
        {
            return Id.GetHashCode() ^ Name.GetHashCode();
        }
    }

For all the instances of Item class who has equal values for both Id and Name properties, the equal hash codes will be generated and they will be treated as same "key" by .NET dictionary.