Saturday, September 29, 2012


In this tutorial I'm going to demonstrate step by step how you can create a custom control in csharp with extended features.
Lets say you want to set border color of a Textbox in your c# windows forms application. The default Textbox control does not provide us the functionality to set its border color , also the Textbox control does not have Paint event so we are not able to draw any border around textbox.
So what we can do is-

  • create a custom control
  • add a textbox in it
  • use custom control's paint event to draw border with any color
So here are the steps to achieve the above goal:

Step 1: First of all open visual studio and create a new project. Do the selection as shown in below snap.



Step 2: Now you get a custom control screen. Resize the control to (153, 22).


Step 3: Right click on Control and select View Code
Step 4: In code file create object of Textbox class and set Multiline to true & BorderStyle to None. Also set font and backcolor of Textbox object equals to custom control & then add the textbox object to custom control as shown below.
Step 5: Create an enum named as BorderSides to give more readable options to user so that the user can select on which side he/she wants to set border (we can also use int 0,1,2,3 and use if else but that is not as easy to understand as enum). Through enum we can assign meaningful names to integers.
Step 6: Now we need to create a public property to get and set textbox's text.
Step 7: Create two public variables to get Border color & Side on which user need to apply border(by default I took All sides) + one private variable for border size



Step 8: Now goto design view & select control >> generate two events(Paint & SizeChanged) of custom control as shown below
Step 9: In CustomTextBox_SizeChanged Set size, location, font and backcolor of textbox according to custom control's size, location, font and backcolor respectively. Note i keep width & height of textbox lil small as compared to custom control just to hold some space to display border.
Step 10: In CustomTextBox_Paint I've used the ControlPaint.DrawBorder to draw border around custom control as shown below. Use enum which we have created earlier to get user choice and set the border accordingly

Step 11: Now from visual studio's menu list Select Built>Built CustomTextBox. After successfull built your custom textbox control dll file will be created in >>Bin>Debug folder

To open project folder from IDE:



Now we have successfully created our custom TextboxControl, To use this control you need to add to it to Toolbox as:
  • Create a new windows form application project
  • Select Toolbox>Right click inside Toolbox and select Choose items
  • Browse the dll file which we have created earlier
  • OK





Now your new control is in your Toolbox's list of all controls, just drag n drop it on  win form to start using it.
Use the Public property Text to set text and public variables-> BorderColor & SetBorderSide to set the border color and side on which the border will be apply respectively


Tuesday, September 25, 2012


To Change GridView's Row color on mouseover :
Just put the following code snippet in GridView's RowDataBound event :

                if (e.Row.RowType == DataControlRowType.DataRow)
                {
                    e.Row.Attributes.Add("onmouseover", "this.originalstyle=this.style.backgroundColor;this.style.backgroundColor='yellow';this.style.cursor='hand';");
                    e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=this.originalstyle;");                                
                }



Download Demo Website from here

Cheers :-)

Friday, September 21, 2012

Almost all of us used char, varchar and nvarchar datatype while designing a database table in sql but only few among us knows the exact difference between these three. That's why let me differentiate these three important datatypes and I hope it will help you all.


Char DataType: 
Char datatype which is used to store fixed length of characters. Suppose if we declared char(50) it will allocates memory for 50 characters. Once we declare char(50) and insert only 10 characters of word then only 10 characters of memory will be used and other 40 characters of memory will be wasted.

varchar DataType: 
Varchar means variable characters and it is used to store non-unicode characters. It will allocate the memory based on number of characters inserted. Suppose if we declared varchar(50) it will allocates memory of 0 characters at the time of declaration. Once we declare varchar(50) and insert only 10 characters of word it will allocate memory for only 10 characters.

nvarchar DataType:
nvarchar datatype same as varchar datatype but only difference nvarchar is used to store Unicode characters and it allows you to store multiple languages in database. nvarchar datatype will take twice as much space to store extended set of characters as required by other languages.



Thursday, September 20, 2012

In this post I'm going to demonstrate how you can get first and last date of any month / given date.

Lets say we have a date '2012-02-15'.

Now I want first('2012-02-01') and last('2012-02-29') date for the same directly using sql query!
So here it starts:
Declare three variables :
Declare @dt datetime,@mindate datetime,@maxdate datetime;

Now Set value of @dt(Our initial date) :
set @dt='2012-02-15'

As we all know that 01 is always the first day of every month so the start-date must be :
set @mindate=convert(varchar,DATEPART(year,@dt))+'-'+convert(varchar,DATEPART(MONTH,@dt))+'-01';

*[Note: I have converted the datepart function's value to varchar because datepart always returns int and we want concatenation not addition :-) ]*

To get the last-date we gona do a small trick, add 1 month in @mindate and then subtract 1 day from the result !
set @maxdate=dateadd(day,-1,DATEADD(month,1,@mindate)) ;

So finally here is the result :
select @mindate as StartDate,@maxdate as EndDate

Output will be :

StartDate EndDate
2012-02-01 2012-02-29


You can also create a table valued function for same as:


create function GetMinMaxDays(@dt datetime)
returns @temp table(StartDate varchar(10),EndDate varchar(10))
as
begin
declare @mindate datetime,@maxdate datetime;
set @mindate=convert(varchar,DATEPART(year,@dt))+'-'+convert(varchar,DATEPART(MONTH,@dt))+'-01';
set @maxdate=dateadd(day,-1,DATEADD(month,1,@mindate));
insert @temp
select convert(varchar(10),@mindate,105),convert(varchar(10),@maxdate,105);
return;
end


*[Note: 
convert(varchar(10),@mindate,105)
 will convert datetime value to yyyy-MM-dd format string]*

Call above function as:
select * from GetMinMaxDays('2012-09-10')

Output will be :

StartDate EndDate
01-09-2012 30-09-2012

Tuesday, September 18, 2012

In this simple example I want to demonstrate how you can use while loop, temporary table and declare & use variables in sql server itself.  


  • First of all declare two variables of type datetime & set values of these variable as shown below:


    declare @dtfrm datetime,@dtto datetime;
    set @dtfrm='2012-01-15';
    set @dtto='2012-02-10';


  • Now declare a temporary table as :


    declare @temp table(DateColumn date);


  • Now I started a while loop from start date and continue to run it until start date is equal to end date : 

    while(@dtfrm<=@dtto)
    begin
       insert @temp
       select @dtfrm;
       set @dtfrm=DATEADD(day,1,@dtfrm);
    end

  • Finally select all dates from temporary table as :

    select * from @temp

Friday, September 14, 2012

Have you ever wonder how keylogger is working or ever try to create your own keylogger using C# ?
Yes ! - No ! doesn't matter heheheeee :-) as m still going to tell how you can create a small application using visual studio ide & c# which is nothing but a keylogger.
First of all you need to know what is a keylogger?
Ans. : A keylogger is a software program that records the real time activity of a computer user including the keyboard keys they press.


To create a keylogger you may follow these :

  1. Create a windows application which runs hidden in background.
  2. Application captures keystrokes pressed by victim and save them into a log file.


Problem 1 : How to run a window application in background?
Solution  : Create a windows application using vs and set properties of the Form -> ShowIcon and ShowInTaskbar to false and Opacity=0. 
(Note : Application is still visible through  
Taskmanager->Processes heheheheeee)



Problem 2 : How to get pressed keystrokes?
Solution  : We can get key-strokes easily if we have focus on our own application but when victim has focus on some other application then how can we get keystrokes pressed by victim? :-( 
In this situation we need to use API 
(Application programming interface) provided by Microsoft itself to make the job done. Microsoft provides an unmanaged API called Win32 which has a dll file called User32.dll. The  

User32.dll library allows managing the entire user interface. It has a function called GetAsyncKeyState which we need to call to get the pressed key asynchronously.


Problem 3 : How to call functions from an unmanaged dll ?
Solution  : In C# we use DllImport attribute for calling method from unmanaged code.
Syntax:- (Don't forget to include using System.Runtime.InteropServices;)
[DllImport("User32.dll")]
private static extern short GetAsyncKeyState(System.Windows.Forms.Keys vKey);

We also need to declare the method before we can use it because User32.dll is created using c++. 
The DllImport attribute specifies the dll location that contains the implementation of an extern method, that's why I  
declare the method as extern. I also declared it static so that it belongs to the type itself rather than to a specific object. Any method implemented with the help of DllImport must have  
the extern modifier.



(Note : extern is used to indicate that method is implemented externally)



The GetAsyncKeyState function determines whether a key is up or down at the time the function is called and whether the key was pressed after a previous call to GetAsyncKeyState.

Final step :
Now add a timer control to a window form and set Interval property to 10 or 20 and in the Tick event of the timer iterate through all the Keys and find which one is pressed, by using  
GetAsyncKeyState method.

How to iterate ?(I think you know)
But if don't then :-

foreach(System.Int32 i in Enum.GetValues(typeof(Keys)))
{
if(GetAsyncKeyState(i) == -32767)
{
//To get key name use-> Enum.GetName(typeof(Keys), i) function
// Now you have the pressed key. Do whatever you want !
}
}

 :-) cheers...

Download sample application & source code

Tuesday, September 11, 2012

Some time we need to restrict user from navigating using Back and Forward buttons provided by browsers for some security or any other reason. If anyone is in same situation then here is a simple solution...
Just put the following piece of java-script directly into the starting of page's body section

<script type="Text/JavaScript">
        javascript:window.history.forward(1);
</script>

If you want to display your own custom icon instead of IE logo into aspx pages then here is the solution :

Step 1 : Put your custom icon(.ico file) into a folder say "Images"
Step 2 : Now add <link rel="SHORTCUT ICON" href="Images/iconName.ico" /> in head section of the page.
Cheers it's done !