Latest Posts

Recent Posts

Saturday, May 20, 2017

Dynamic/Runtime Polymorphism / Object Slicing C#.net



Few days back  One of my fried asked me to help him in hiring C# resources. I asked about the requirement. He told me , he is looking for people having experience of 3 to 5 yrs in C# development. 

I prepare a list of basic questions mostly on my favorite topic Object oriented programing (OOP's). Initially the interview was smooth. It seem like all the resources have very good understanding of C#. After few interviews I started to do some tongue twisting with OOPS word like instead of asking function overloading/overriding I started asking Dynamic/Run time Polymorphism or Static/Compile time Polymorphism and people were stuck. 

I given them below two class 
====================================================================
public class ParentClass
    {
        public String add(int i, int j)
        {
            return "In Parent class";       
        }

        public String hideParent(int i, int j)
        {
            return "In Parent class";
        }
    }
===================================================================
    public class ChildClass : ParentClass
    {
        public new String  add(int i, int j)
        {
            return "In Child";
        }

        public new String hideParent(int i, int j)
        {
            return "In Child Class With New Keyword";
        }

        public new String onlyInChild(int i, int j)
        {
            return "In Child Class whiout overriding";
        }
    }

==============================================================

And the Questions were what will be the out put in below scenarios

//1. #########################################################################

ParentClass objParentClassWithParentObject = new ParentClass();
Console.WriteLine("Parent class with parent Object :  " + objParentClassWithParentObject.add(3, 5));
//2. #########################################################################
ChildClass objChildClassWithChild = new ChildClass();
Console.WriteLine("Child class with Child Object :  " + objChildClassWithChild.add(3, 5));

//3. #########################################################################

ParentClass objParentClassWithChildObject = new ChildClass();
Console.WriteLine("Parent class with Child Object :  " + objParentClassWithChildObject.add(3, 5));

//4. #########################################################################

//ParentClass objParentClassWithChildObjectNew = new ChildClass();
//Console.WriteLine("Parent class with Child Object :  " + objParentClassWithChildObjectNew .onlyInChild(3, 5));

//5. #########################################################################

//ChildClass objChildClassWithParent = (ChildClass) new ParentClass();
//Console.WriteLine("Child class with Parent Object :  " + objChildClassWithParent.add(3, 5));
 //6. #########################################################################

ParentClass objParentClassWithChildObjectAndNew = new ChildClass();
Console.WriteLine("Parent class with Child Object and New Definition :  " + objParentClassWithChildObjectAndNew.hideParent(3, 5));

//7. #########################################################################

ParentClass objParentClassWithChildObjectAndNew = new ChildClass();
Console.WriteLine("Child class with Child Object and New Definition :  " + objChildClassWithChildObjectAndNew.hideParent(3, 5));

1st and 2nd scenario are very straight forward. We are creating parent object and initializing it with parent class so the result will be  " Parent class with parent Object : In Parent Class"

The child object is created with child class and initialize child class object so the output will be " Child class with Child Object :  In Child "

In 3rd scenario we are creating parent class object and initializing it with child class . Here concept of object slicing will take place.


The child class holds all the behavior and property of parent class so the parent class will get initialized and behavior and property of child class will get discarded . With this call parent class function will get called.

The output will be "Parent class with Child Object :  In Parent Class"

In 4th scenario the concept of object slicing will work but when we try to access the function which is defined in child class only it will give compile time error  "Class doesn't contain definition for the function .....".

In 5th scenario we are trying to initialize child class object with parent class object by  type casting it into child class. It will give error at run time.

In 6th scenario we are creating parent class object and initializing it with child class. The only difference is here the new key word used in function definition in child class .When we use new keyword in child class it gives new definition to the function. But as we are initializing the parent class object the output will be  "Parent class with Child Object :  In Parent Class"


7th scenario it pretty straight forward , we are creating child object and initiliazing it with child class. It donst matter new key word is used or not it will call the child class method. The output will be "Child class with Child Object and New Definition : In Child Class With New Keyword."
 I have tried to cover all scenario, if you have any query or problem feel free to contact me via comment.

Thursday, February 23, 2017

How sessions work in PHP

Recently I was helping one of my client in hiring PHP developer . I was surprise to know that 80 % of candidate don't know about how PHP session works.

People were aware about the functions like session_start , $_SESSION etc but not  aware about how it works over the HTTP. Most of the candidate stuck when they were told that HTTP is connection less protocol and on every request a new connection is created . 

https://www.tutorialspoint.com/php/php_sessions.htm

In PHP Session management is a way to make data accessible across the various pages.

A session creates a file in a temporary directory on the server where registered session variables and their values are stored. This data will be available to all pages on the site during that visit.
The location of the temporary file is determined by a setting in the php.ini file called session.save_path. Before using any session variable make sure you have setup this path.
When a session is started following things happen −
  • PHP first creates a unique identifier for that particular session which is a random string of 32 hexadecimal numbers such as 3c7foj34c3jj973hjkop2fc937e3443.
  • A cookie called PHPSESSID is automatically sent to the user's computer to store unique session identification string.
  • A file is automatically created on the server in the designated temporary directory and bears the name of the unique identifier prefixed by sess_ ie sess_3c7foj34c3jj973hjkop2fc937e3443.
When a PHP script wants to retrieve the value from a session variable, PHP automatically gets the unique session identifier string from the PHPSESSID cookie and then looks in its temporary directory for the file bearing that name and a validation can be done by comparing both values.
A session ends when the user loses the browser or after leaving the site, the server will terminate the session after a predetermined period of time, commonly 30 minutes duration.

Starting a PHP Session

A PHP session is easily started by making a call to the session_start() function.This function first checks if a session is already started and if none is started then it starts one. It is recommended to put the call to session_start() at the beginning of the page.
Session variables are stored in associative array called $_SESSION[]. These variables can be accessed during lifetime of a session.


Changing the name of PHPSESSID 

We can change the name by calling session_name before any call to session_start or session_register .

session_name('mySessionName');
session_start();

 Other method is to set the name in php.ini . The variable session.name specifies the name of the session which is used as cookie name. It should only contain alphanumeric characters. Defaults to PHPSESSID

For further reference please visit to below link

http://se.php.net/manual/en/session.configuration.php#ini.session.name
 

Wednesday, February 8, 2017

change the root password for MySQL in XAMPP




  1. Start the Apache Server and MySQL instances from the XAMPP control panel.
  2. After the server started, open any web browser and give http://localhost:8085/phpmyadmin/ (if you are running XAMPP on 8085 port). This will open the phpMyAdmin interface. Using this interface we can manager the MySQL server from the web browser.
  3. In the phpMyAdmin window, select SQL tab from the right panel. This will open the SQL tab where we can run the SQL queries.
  4. Now type the following query in the textarea and click Go
    UPDATE mysql.user SET Password=PASSWORD('rootPass') WHERE User='root'; FLUSH PRIVILEGES;
  5. Now you will see a message saying that the query has been executed successfully.
  6. If you refresh the page, you will be getting a error message. This is because the phpMyAdmin configuration file is not aware of our newly set root passoword. To do this we have to modify the phpMyAdmin config file.
  7. Open the file [XAMPP Installation Path] / phpmyadmin / config.inc.php in your favorite text editor.
  8. Search for the string $cfg\['Servers'\]\[$i\]['password'] = ''; and change it to like this, $cfg\['Servers'\]\[$i\]['password'] = 'rootPass'; Here the ‘password’ is what we set to the root user using the SQL query.
  9. Now all set to go. Save the config.inc.php file and restart the XAMPP server.

Monday, February 6, 2017

Designing Multi level, Multi Server, Multi Database System

I am providing consultancy in field of system design for quite some time . Recently one of my
acquaintance approach me to help him in designing a system for handling huge data gathering  and processing process.

I asked him what he meant by huge data gathering and processing. He explained me about the system He is looking forward to build a system to provide one stop solution for analyzing the data from various channels/sources. 

He has large customer base and all customer has multiple channels/sources to provide data. The size of data is varies in the rage of 3 to 5 million rows. Also the number of columns are not fix. 

As the number of columns were not fixed for unprocessed data, I asked him, "what about the number of column after processing the data". His answer was it is going to be fixed. 
on further discussion about data, We zeroed to MongoDB for storing unprocessed data and MySql for storing processed data. The primary reason behind using MongoDB for storing the unprocessed data  were
  1. The data size was huge
  2. The number of columns are not fixed i.e. schema of tables were not fixed.
  3. It is supported by strong developer community.
The processed data is structured so we decided to use MySql. MySql is also free database and well supported by developer community. 

After deciding the database we further discussed about the sources/channels of data. We zeroed that it is good strategy to bind the sources and scripts needed for gathering and processing of data. It will be further passed on to the client at the time of registration i.e. at the time of client registration the client will be mapped to sources/channels and it will automatically bind the scripts required for processing and gathering of data for the client. The advantage of using this strategy was
  1. The source/channel , script and client can work independently. If required the scripts can be added and deleted at client level.
  2. The logical change in source/channel script will not effect the current working of client
To make system more robust we save the details of client database on client level. It will help us at the time of gathering and processing process to save and manipulate the data.


Till now the structure was like

We discussed much about the data management, now we moved to data processing part. It is the point were a system can make or break. 
We started discussing about the advantages and dis-advantages of using a single server for executing scripts for gathering and processing data of all client.
Dis-Advantages
  1. Risk of mixing client data
  2. If once process fails then all next process in queue will fail 
  3. As data amount is huge so it may be slow down the server
  4. client specific customization is difficult  
Advantages  
  1. Low cost
  2. easy to maintain
We come to conclusion that it is not good idea to use single server for gathering/processing of data for all client. 
We decide to use independent server for each client. The respective server of client will take care of data gathering and processing.   

On respective client server we will set the cron job. This Cron job executes a php script file which has the client Id value. With the help of client id , server gets the detail of scripts to be executed and the DB server detail. It also gets the other detail if required for the data channel/Source from the central MongoDB.
After getting the scripts it puts it into a designated folder with respective values. On the designated folder we will creat "INCRONTAB". As soon as the files are saved into folder the incrontab will come into action. It will start executing the files parlally.

The status of execution process are maintained for the respective client on central MongoDB server with various status FLAG like running, completed , error etc.

 The final architecture of system looks like as below image



The above solution will work well on combination of Linux/Unix server. To achieve same on windows server we need to use windows services. windows services provides the same working as we do with CRON. 
The only disadvantage of this architecture is that running cost for client is going to be HIGH.  

This architecture can be further optimized by using Job scheduler Queue. By Using Job scheduler the system can handle any exception occurred during data gathering or processing.



 

Monday, January 30, 2017

FTP Vs HTTP


The FTP and HTTP is widely used protocol. I was surprised when i asked about the difference between both and 90% of people failed to answer it. Most of the people told me that FTP is file transfer protocol and HTTP is Hypertext transfer protocol.

To make people aware it, i thought i should write about it.

1.  All protocol are assigned specific port number. To communicate with the protocol we need to request on specific port of server so the first difference between FTP and HTTP is their protocol they work on. FTP works on 20, 21 port number and HTTP works on 80, 8080.

2.  The HTTP is used to transfer data from browser to server and vice-versa. FTP is used to transfer  data from one computer to another computer.

3. The most important difference is that  FTP is connection oriented and HTTP is connection less. Once FTP connection is established it will persist till the time it is not disconnected while in HTTP on every request a new connection is created , data is processed and  response is send back.

   
Feature FTP HTTP
TCP Port Number 20 and 21 80 and 8080
Function of protocol Used to transfer files from remote computer after connection is established. Used to transfer web pages from remote server after internet connection is established.
Connection It is connection oriented It is connection less
RFC reference documents RFC959, RFC765, RFC1738 RFC2616, RFC7230 and RFC7231

Friday, January 27, 2017

Abstract and virtual function and class in C#





i always find abstract and virtual as confusing. so i decided to do all test and write my experience of the same.I have consider all the angles, where a smart interviewer can trap you.
Most of the time the first question an interviewer ask is whats difference between abstract and virtual method in C#.

The simplest difference is that , body is needed for virtual function where it is declare, where as its just opposite in case of abstract function.

Lets examine this example

The first class is abstract class which contains a abstract method inabs()
if we give body to this method then it will give compile time error saying "cannot declare a body Function is marked as abstract".

Making a function abstract compels the inheriting class to define the abstract function.



 
    public abstract class abstractparent {     
        public abstract void inabs();      
        public void noabsparent()      
        {       
            Console.WriteLine("In Class Contaning abstract methode");      
        } 
    } 
    public class abstractchild : abstractparent {     
        public void noabschild()     
        {        
            Console.WriteLine("In Child class of Abstract Parent");     
        }     
        public override void inabs()     
        {        
            Console.WriteLine("In Child class functin definition of abstract");     
        } 
    }



Also when we are declaring a abstract function in a class its necessary to use ABSTRACT keyword with class and function both.
A non abstract class can't contain the abstract method.if we defined a abstract method in non abstract class and try to compile it then it will give compile time error stating "A non abstract class has abstract function".you can check it by altering the above classes.

In virtual function we must have to specify the body of the virtual function.if we not specify the body then it will give compile time error stating "must declare a body because it is not marked as abstract, extern or partial".




#region virtual_function
    class virtual_parent
    {
        public virtual void vir_parent()
        {
            Console.WriteLine("IN vir_parent function of parent class which is defiend in parent class");
        }   
        public void non_vir_parent()
        {
            Console.WriteLine("IN non_vir_parent function of parent class which is defiend in parent class");
        }
    }
    class virtual_child:virtual_parent
    {
        new public void non_vir_parent()
        {
            Console.WriteLine("IN non_vir_parent function of CHILD class which is defiend in CHILD class");
        }
        public override void  vir_parent()
        {
            Console.WriteLine("IN vir_parent function of CHILD class which is defiend in CHILD class");
           //base.vir_parent();
        }
    }
    #endregion


Some tricky question interviewer may ask you.

1)Can we declare and defined a normal(not abstract, virtual,extern or partial) function in derived class which is already present in base class.
Yes we can do this in dotnet.
By using new keyword we can re-declare and redefine a normal function in drived class. for detail please refer the above code.

2)If above is true then how you will call the base class function by using child class object.

this we can do by explicitly type casting the base class object in to parent class

Use this code to see the result
virtual_child obj_virtual_child = new virtual_child();
((virtual_parent)obj_virtual_child).non_vir_parent();

I hope i have covered all the expect of the virtual and abstract.please let me know if any body have any query.
please also let me know if any body have problem in any concept of dotnet.
You can reach me at rajhan143-hostway@yahoo.co.in

Tuesday, July 7, 2015

Indexes on sql Server table


I have discussed with many interviewer and interviewee about the SQL Server tricky interview Questions. Most of them told me that Indexes and Triggers are most important area. Today we will discuss more about the Indexes and Triggers. To make it simple i will post question first and then explain the answer.

1. What is clustered and Non Clustered Index?

The leaf nodes of a clustered index contain the data pages i.e. in simple terms the clustered index stores the information how physically information is stored.It is same as the index page of a book.

A nonclustered index is a special type of index in which the logical order of the index does not match the physical stored order of the rows on disk. 
In simple terms we can say that the non clustered Index stores the logical ordering of data.
  
2. How many Cluster Index you can create on a table?

One Clustered Index is allowed per table

3. Can we create Clustered Index on Null value column? 
Yes we can create Clustered Index on a non-unique and nullable column. If the clustered index is not a unique index, SQL Server makes any duplicate keys unique by adding an internally generated value called a unique identifier.

4. How many Null value can a clustered Index column can take?


Only one NULL value is allowed in Clustered Index column as it is considered as a unique value.

5. Can we create Clustered Index on Non primary key column? 

 yes. We can create Clustered Index on Non primary key.

6. How many NON-Clustered Index you can create on a table?

SQL Server allows maximum up to 249 NON-CLUSTERED indexes that can be created in single table. This has been increased to 999 in SQL Server 2008 R2 version for both 32-bit and 64-bit server.

7. Can we drop Cluster Index on Primary Key. If yes then how it will work ?

Yes We can drop a Clustered Index on Primary key column and create it on another column.

8. Can we create a table without Clustered Index.

Yes we can.The table is called as Heap.Data is stored in the heap without specifying an order. To find a row we must now RID.  

9. Can we create Non-Clustered index on a table which donst have Clustered Index.

Yes we can create Non clustered index on a table which don't have clustered index