Monday, 5 September 2011

Unique instance using Singleton pattern

For my recent project which my colleague was in charge, I faced a question on How to restrict a class from creating multiple instances.
After five minutes of R&D I came across a word "Singleton". I referred a bulky book from shelf and rolled down until this word signalled my brain "Singleton Pattern".

1) What is a singleton pattern? 
2) Why is it used for? 
3) How to implement?

1) What is singleton pattern?
A: In software engineering this is a design pattern used to restrict instantiation of a class to one object. In another point of view, we make one and only one instance of a class during runtime. The same instance will be resused throughout the life cycle untile exclusively destroyed.

2) Why is it used for?
A: Depends on the requirement.

In my application the singleton was used to keep only one instance until EOD(End Of Day). For which I used a static (C#.Net)/shared(VB.Net) method instead of giving access to constructor.
eg: If you want all the users to use the only instance of a class for all purposes(transactions in my case), this is the right choice.

3) How to Implement?
A: Remember the following points 
  1. Declare the default and all overridden constructors with private access specifier.
  2. Create a static(C#.Net)/shared(VB.Net) function which will take care of instantiation of a new object.
  3. You use only the static method to create a new instance, use of keyword 'new' will be restricted in this case.
SOURCE CODE AND DESIGN

In the windows form there are two buttons
a) Get : Calls the unique instance method.
b) Destroy : Destroy the unique instance created for a new creation.

My Singleton class

public class SingletonClass
    {
        private static SingletonClass MySingletonClass;
        
        string _szValue = "";
        //use this if you have any custom constructor
        private SingletonClass(string szValue)
        {
            _szValue = szValue;
        }

        //This is how you restrict an instance is created outside this class using keyword NEW
        private SingletonClass()
        {

        }

        public string szDate
        {
            get;
            set;
        }

        ///The function handles creation of a new instance of this class.
        ///A new instance is created only if there is no previous instances created.
        public static SingletonClass UniqueInstance(string szValue)
        {
            if (MySingletonClass == null)
            {
                MySingletonClass = new SingletonClass(szValue);
                MySingletonClass.szDate = DateTime.Now.ToString();
            }
            return MySingletonClass;
        }

        public static void DestroyInstance()
        {
            MySingletonClass = null;
        }
    }

Form1 code behind

        ///Button click event of Get.
        ///Returns date at which instance was initially created. 
        private void btnGet_Click(object sender, EventArgs e)
        {
            ///The most important point is this.
            ///Instead of declaring it using keyword new, you call the function.
            ///ie, we are avoiding SingletonClass mysingleton = new SingletonClass() 
            SingletonClass mysingleton = SingletonClass.UniqueInstance("hello");
            MessageBox.Show(mysingleton.szDate);
        }

        private void btnDestroy_Click(object sender, EventArgs e)
        {
            SingletonClass.DestroyInstance();
        }


Monday, 27 June 2011

Basic Interview question. What is a variable in programming language?

Narrating after conducting a core level technical interview for some bright .Net based experienced candidates.

Every one had quite good resume and their communication standard varied from poor to average to excellent. But towards the interview desk, hmmm, the play was extremely different. Around 70% of the applicants failed in the "knowledge of basics".

The one basic question one can come across is "What is a variable?". Be it a fresher or an experienced, without knowing the base facts how can a company trustfully assign you projects or work?

General figure, syntax: DataType variableName;

PROGRAMMER'S VIEW

Q.What is a variable.
A.
i) In simple words, it is a named memory location.
ii) Thinking wider, it is a name assigned to a memory location for the programmers to understand and use.
iii) Further wide, it is a name assigned to a memory location in a programming language for the programmers to understand no matter what the datatype is (better not to use it).

Q. Why do we use variables?
A. To store values. As simple as that.

Q. Why do we store values?
A. In a program it is the choice of a programmer whether to use a variable or not. By using variables we can use the same memory location to store different but same type of values at different instance of time (at a time only one value can be stored in a simple variable or else the answer give way to question of arrays and other stacks).

Q. What is the size of memory that a variable holds?
A. Size of memory depends on the type of data that variable can hold. (any guess about the next question)

Q. What is a 'type of data' or 'DataType'?
A. Dataype is a class that is used to hold data.
FYI, a datatype decides what amount of memory to be reserved for a variable (do not include this line while answering unless you are that confident as the questions may go further deeper ;-)).

Q. Give examples of DataType.
A. boolean, byte, char, int, decimal(System.Decimal), double(System.Double), short(System.Int16), float, Integer(System.Int32), long (System.Int64).

Q. What memory size does the variable "uint myUInt"; occupy?
A : 32 bit
FYI: Know the basics
The base of all datatype is bit, the tiny particle that you see while going deeper.
1 byte = 8 bits, maximum value = (2^8) -1 = 255, range = 0 to 255
2 bytes = 16bits, maximum value = (2^16) -1 = ?
4 bytes = 32 bits, maximum value = (2^32) -1 = ?
8 bytes = 64 bits., maximum value = (2^64) -1 = ?
Do not confuse with bit and byte.
The reason why I said this is because, always remember an Int (Integer type) is always 32bits.
So no matter it is uint or int, the size is 32bits.
summary : int = System.Int32;

Lot more about variables, like what are the various types of variables, etc etc. Shall update you with those in my next blog.

Thursday, 2 June 2011

How to call functions of unmanaged dlls from managed codes (Code included)

This was really a wonderful experience. I really struggled to get a solution to shake hand with an old generation.

For any one who is newbie, the tip is as simple as it is.

1) Know a term "Marshalling", which technically means, converting a datatype to byte streams in order to transport from one app domain (it could be from unmanaged to managed or vice versa) to another.
There is another big term called "UnMarshalling" which is of-course the reverse process for Marshalled objects
Marshalling is not restricted to variables, you can even marshal a structure as such.

2) Know how to use delegates.
A delegate is used to call a function or property without directly in touch. Delegate actually is like a broker to handle our function calls. Broker actually accepts our request, point to the right function that we are looking for, call it and give back its response in the way the actual function returns (A function returning bool type can be called only by a delegate that return type bool. signature should be same), without letting us know any thing about the actual function.
Delegates are reusable. Read more about it.

Q. Why is marshalling involved?
A. To avoid datatype mismatch while invoking. All the .Net datatype may not be there in the primitive C/C++. Byte stream is commonly known to old and new dll/app makers. (Like the language English, used around the world for communication)

Q. Why is delegate important?
A. The unmanage library methods cannot be accessed directly from .Net, because they cannot be referred to our project like any other managed dll.

So, lets get in to coding.
Suppose our unmanaged dll is DLLClient.dll.
Suppose there is a function named "vEnableLogs" inside DLLClient.dll

#All references for the inside of DLLClient => Tech Ref that was supplied along.

Step 1. Know the vEnableLogs prototype and signatures
This function accepts a string and return bool.

Step 2. Create a delegate for the said function type, ie, delegate that has one string parameter and returns bool; see below for syntax
delegate void _vEnableLogs(string logPath);


Step 3. MAIN PART. The following is how you bring the function inside unmanaged dll to the outside world.
Lets say the opening to the function..

[DllImport(@"DLLCLient.dll"
 EntryPoint = "vEnableLogs",
ExactSpelling = false
CallingConvention = CallingConvention.Cdecl)]
static extern void vEnableLogs(string logsPath);


a)DllImport
This is used to import dlls, primitive method of importing dlls in to vicinity.
b) @"DLLCLient.dll"

Name of the dll. Located in the same directory as my working dll, or else you can give an associated or relative path.
c) EntryPoint = "vEnableLogs"
Name of function inside DLLClient.dll
d) ExactSpelling = false
An available property.
e) CallingConvention = CallingConvention.Cdecl
Read more here.
f) static extern void vEnableLogs(string logsPath);
static means we are not providing the code. Code is some where else.

4) By now the ingredients are ready for mix. Do the coding
public static bool My_vEnableLogs(string logsPath)
{
    _vEnableLogs enableLogs = new _vEnableLogs(vEnableLogs);
    return enableLogs(logsPath);
}

Every external programs will call this function ("My_vEnableLogs"). Static, well that is all up to us. Delegate can be accommodated in either.

How to access unmanaged dll in ASP.Net

I was asked to design a central solution for an app that had to refer a library which was unmanaged and cannot be referred directly to our project. How do we do it.

Say, DLLClient.dll is your unmanaged dll.


Method 1
1) Create a managed dll that calls each and every function (required) of unmanaged, say Client_Wrapper_DLL.dll.
2) Now copy the DLLClient.dll to the bin folder (if there is no bin folder by default, create one by right clicking on the project, create new folder --> select "bin" from the drop down)
3) Refer this dll to your ASP.Net project. Now the Wrapper dll will appear inside your bin folder. (or you can do this step first so that the bin folder will automatically created)
4) Call the functions of Client_Wrapper_DLL, which will automatically refer the unmanaged DLLClient.dll located in bin folder, whereas the Client_Wrapper_DLL acts as a proxy.

Method 2
1) Copy the DLLClient.dll to Windows/System32.
2) Create delegates to call functions inside DLLClient. Here the proxy code lie in your ASP.Net code. 
That is the only difference.

The major difference will be where the unmanaged dll location is and how the proxy code is is created, either a separate dll or within your code behind. 

I always recommend NOT to use the System32 folder, as that is and should be dedicated for OS related files. Let us not give any confusion to OS, if in case there happens to be an overlap you get screwed.