Sunday, June 23, 2013

.NET Developer Interview Question: What is IDisposable?

Garbage collector as a part of CLR has the responsibility of managing memory allocation to native .NET objects which are called managed objects. C#, VB.NET and other .NET languages which are garbage collected languages does not provide a way for developers to finalize a managed object in their application directly. However not all resources you use in your program is a managed one. Examples of unmanaged objects are window handles, open files, streams and database connections. While CLR's garbage collector automatically releases the memory allocated to managed objects (when they are not needed any longer), it will not be possible to know when garbage collection will occur with unmanaged objects and developers need to take the matter into their own hands. 

When calling a class that implements the IDisposable interface, use the try/finally pattern to make sure that unmanaged resources are disposed, even if an exception interrupts your application. you can use the using statement (Using in Visual Basic) instead of the try/finally pattern.

IDisposable interface is defined as follows:
public interface IDisposable
{
   void Dispose();
}

When writing a class for IDisposable interface, make the dispose method of the class public so that other classes can call the methods:
public class MyClass : IDisposable
{
   public void Dispose()
   {
     //Handle your finalization process here ...
   }
}

Wednesday, June 19, 2013

Implement Java Map in Javascript

//Map is an Object Literal 
var map = {};

//Key Needs To be a String
var key = "";

// Value can be any String, Number or an Object itself
var value;

//------- Method I --------------

// Assign a value to a key 
map[key] = value;

// Return value by a key 
var returnedValue = map[key];

//-------- Method II ----------

// Return value by a key
var returnedValue = map.key;

// Assign a value to a key
map.key = value;

.NET Developer Interview Question: What is Deferred Execution?

According to MSDN definition, "Deferred execution means that the evaluation of an expression is delayed until its realized value is actually required". The main benefit of using deferred execution is that it can greatly improve performance when you have to manipulate large data collections, especially in programs that contain a series of chained queries or manipulations.


In .NET and Microsoft technologies, C# is supporting deferred execution via using yield keyword (LINQ extensively uses deferred execution as one way of executing its queries).


C# Example:
public class Program
{
    static void Main()
    {
       foreach (int value in ComputePower(2, 30))
       {
          Console.Write(value);
       }
    }

    public static IEnumerable ComputePower(int number, int exponent)
    {
       int exponentNum = 0;
       int numberResult = 1;
  
       // Continue loop until the exponent count is reached.
       while (exponentNum < exponent)
       {
          numberResult *= number;
          exponentNum++;
     
          yield return numberResult;
       }
    }
}

In the above example, the computation of the 2 power 30 will be deffered to where the for-each looped value is used, which will boost up the performance of this chunk of code.


 LINQ Example:
class Program
{
    static void Main(string[] args)
    {
        string[] stringArray = { "abc", "def", "ghi" };

        var q = from str in stringArray.ConvertCollectionToUpperCase()
                select str;

        foreach (string str in q)
            Console.WriteLine("Main: str {0}", str);
    }
    
    public static IEnumerable 
                   ConvertCollectionToUpperCase(this IEnumerable source)
    {
        foreach (string str in source)
        {
            Console.WriteLine("ToUpper: source {0}", str);
            yield return str.ToUpper();
        }
    }
}

In the above example, the same happens with the LINQ queries. Once you use the value of str in the for-each loop, result of ConvertCollectionToUpperCase will be executed. 

Tuesday, June 18, 2013

Load JSON Files Synchronously with jQuery

In jQuery, the getJSON operator can load any JSON file, however this operation is done asynchronously. Meaning that, in cases where you need to wait until your data file is loaded, using getJSON method is useless. Here is one way you can achieve your goal of loading JSON files synchronously:

function loadJsonFileSynch()
{
        $.ajax({
            url: 'path/to/json/file.json',
            async: false,
            dataType: 'json',
            success: function (response) {
                $.each(response, function(key, val) {
                    // Do processing here
                });
            }
        });
}