Monday, November 12, 2012

Hello Friends... First of all wishing u all a very happy and prosperous DEEPAWALI ... 
Sorry for not being in touch for a long time as I'm having very tight schedule in office.
OK m not bothering anymore let's come to the point, some times we need to get values from a textbox separated by certain delimiters like "krishan; manish; rahul, dinesh" in this string names are separated by ';' and ',' characters. What we need to get - all names stored in an array or in a dropdown/combobox.

Another example could be getting distinct mobile numbers from a textbox separated by delimiters.
To achieve the same we can use Linq and some predefined string functions.

Step 1: Create a character array of delimiters

Step 2: Separate textBox text using Split() function of string class and hold them in string array

Step 3: Filter the string array using LINQ to get only those number having length=10

Step 4: Remove duplicate numbers using LINQ's Distinct() function

Step 5: Now insert the valid numbers in combobox
Final: Full code...

Cheers ... Download Source Code From Here

Saturday, October 13, 2012

In my earlier post I demonstrate how you can insert smiley images in richtextbox when a user types the corresponding emotion code.

Now let me show how you can easily do the same in with simple javascript code.
  • First of all download some smiley images and paste them in your website's root folder
  • Put a div element inside your aspx page with contentEditable property set to true and onkeyup="replacewithimg(this);"

  • In head section of your aspx page add the following javascript


  • txt & img are two Arrays which holds the emotion text and emotion image element source code respectively side by side

  • replacewithimg is a function which accept div as a parameter in which the client is typing. This function is called when user press and release a key. In this function I created a for loop which checks whether any emotion text is there in div or not, if it is there then the javascript's replace() function will replace it with corresponding img tag which is stored in img array and after replacing the text set div's innerHTML to var innHTML which contains the updated innerHTML.

[Note: regular.gif, tongue.gif and Sad.gif are the names of my smiley images, Please update them if you have different names]

Download Demo Website

Friday, October 12, 2012

In this tutorial m going to demonstrate how you can add the functionality in RichTextBox to automatically insert smiley faces for emotions symbols typed in the RichTextBox like for :-) =
I know you have seen such functionality in chat clients like g-talk, Facebook  yahoo messenger etc.

Believe me it's quite simple and interesting as compared to other complicated demos available on web.

OK let me start the step-by-step guide...

Step 1: Download some smiley faces [Download]

Step 2: Create a new windows form application project in visual studio

Step 3: Add a RichTextBox control to existing Form1

Step 4: Copy all the images which you have downloaded using "Step 1" and navigate to >> visual studio select Project>>SmileyDemo Properties...

There select Resources and paste all copied images on the right side pane.
[Note : SmileyDemo is the name of your project]

Step 6: Now open Code View of Form1 (Juss right click on form and select View Code)

Step 7: Now I'm going to create a Hashtable to hold the smiley symbol [like ":-)"] and smiley image side by side (a key-value relation) and don't forget to include using System.Collections;

Step 8: Create a function to add all elements to your Hashtable, keep symbols as keys and images as values in Hashtable.
Step 9: Now I'm going to create a function to check whether any of the symbol(which we have defined in Hashtable) is there in RichTextBox control or not. If yes then we have to replace that with the corresponding Image available in Hashtable.

[Note : IndexOf function will search our symbol(basically a string) in RichTextBox's Text and return the index number where it found.

Next we need to select the symbol using RichTextBox's Select() function with starting position of selection & lenght of characters which will be selected.
ClipBoard.SetImage() function will copy the desired image
"(Image)emotions[emote]" is nothing but to get the image object corresponding to "emote" key from our Hashtable emotions and we need to typecast it to Image format.
Now what - we have some selected text in our RichTextBox, all we need to do is juss call the Paste() function of RichTextBox which will paste the copied image at the right place.]

Step 10: Now on Form1's load event call the function which we have created in "Step 8"

Step 11: Double click on RichTextBox to generate TextChanged event handler of our RichTextBox control and call the function which we have created in "Step 9".

That's it...Compile and run and see the magic 

Download Demo

Download Source Code

Wednesday, October 10, 2012

This is what I faced a small problem when using GridView.
I have a LinkButton element in the gridview and my goal is when user clicks on the button, I need to raise the grid view command event and in that event, I need to get the row values. But, the questions is how to get the current row in the grid view command event?  Below is the solution for it.
GridViewRow row = ((LinkButton)e.CommandSource).NamingContainer as GridViewRow;
Note: LinkButton class I used in the above code is assuming that the command event raised when clicked on the LinkButton control. If your requirement is not linkbutton then please place the corresponding control name.Most of the times and most of the developers never use the property available to each and every object named NamingContainer. But, there are lot of advantages with this property. Especially when we write and render controls to page dynamically then this property will help a lot. And there are many properties which will help us to solve so many problems. Use the intellisense and try to know most of the properties available for a .NET control. Hope this will help you and you got what you need.

Monday, October 8, 2012

This the question asked by so many people around me and I also faced issues couple of times of my early stages of learning.This is simple but how to get value and names as a collection and bind to drop down list is a bit difficult. 

Below is the simple logic to read all enums and create a list item and bind to drop down list. 
[Note: There are many ways to get this done, but I believe below is the best way]
Let's say I have a DropDownList in my aspx page, and an enumeration (List of User types for example). I need to bind enum values to my dropdownlist.
Here is the solution
Note : In ToString("d")  d is a format parameter which return an integer when used with enum type;
In ToString("f")  f is also a format parameter which return flag when used with enum type

Hope it help someone ..... :-)

Download Demo website

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", ";'yellow';'hand';");
                    e.Row.Attributes.Add("onmouseout", ";");                                

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))
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);

 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 : 

       insert @temp
       select @dtfrm;
       set @dtfrm=DATEADD(day,1,@dtfrm);

  • 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;)
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">

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 ! 

Saturday, August 18, 2012

Hello friends following is a list of some important things you must know while developing an web application:

Call Javascript Function From Code Behind

Page.ClientScript.RegisterStartupScript(this.GetType(), "sometext""JavaScriptFunctionName();", true);

RunTime JavaScript
void Confirm(string msg)
        Response.Write("Your Javascript code");

Subtract two Date Objects

string time = "2012-05-01 00:00:00";
TimeSpan ts = DateTime.Now.Date.Subtract(DateTime.Parse(time).Date);

Call javascript function from code behind UpdatePanel

ScriptManager.RegisterClientScriptBlock(UpdatePanel1, UpdatePanel1.GetType(), "Success", "FunctionName();", true);

Hide/Suppress blank section in Crystal Report

  • First of all goto Section Expert And Select The Section Which You Want To Suppress Like:

  • A popup window will open now write "isnull({FieldName})" in formula editor like :

Crystal Report Numeric Field To String Formula

·         Replace (cstr({FieldName},0,''),',' ,'')

   Problem: Error in File CrystalReport.rpt:Access to report file denied. Another program may be using it
·         Solution: Remove The Line Below From Your Web.Config File
o    <identity impersonate="true"/>

Wednesday, August 15, 2012

I developed it using dotnet(C#) and it has a nice look n feel & a very attractive user friendly interface.
To send free sms from this application you need two things
First is - an active internet connection
Second is - YouMint user id & password (if you don't have juss signup here)
Now you are ready to send free sms directly from your desktop . . .

Advantage : -

  • No adds as in youmint website
  • Instant delivery (within 5 seconds)
  • Send sms Quickly
  • Auto-sms functionality (juss click on Auto sms button to send sms after every 12 seconds to irritate your friends ;-)
  • Sms history (You can delete)
  • Group Sms (Comma separate)
  • Contact Management (Save contacts with names)
  • Import Numbers from Excel (Just copy from excel file and paste in textbox. All mobile numbers will automatically comma separate)

If anyone wants the YouMint api code feel free to contact me : Krishan Gahlot

Below is a simple case scenario to test your query writing skills. Please put your answer in comments section...
I need to store news/article information. The news can also have comments and tags. News can be submitted/posted by multiple users.

According to the above scenario, I have created 5 tables and inserted some data into them :-
Use the following queries to built the database and related table:

create database demo
use demo

CREATE TABLE comments(
id int identity,
news_id bigint NOT NULL,
[user_id] bigint NOT NULL,
detail varchar(max) NOT NULL,
status bit NOT NULL default 1,
comment_date bigint NOT NULL,

INSERT INTO comments(news_id, [user_id],detail, status, comment_date) VALUES(1, 2, 'nice post :)', 1, 1273431296)

INSERT INTO comments(news_id, [user_id],detail, status, comment_date) VALUES( 2, 2, 'hahaha', 1, 1273431420)

INSERT INTO comments(news_id, [user_id],detail, status, comment_date) VALUES( 3, 2, '3123123', 1, 1273431452)

INSERT INTO comments(news_id, [user_id],detail, status, comment_date) VALUES( 1, 2, 'thank You', 1, 1273431475)

INSERT INTO comments(news_id, [user_id],detail, status, comment_date) VALUES( 2, 1, 'congratulations!', 1, 1273431500)


id bigint identity NOT NULL,
[user_id] bigint NOT NULL,
title varchar(max) NOT NULL,
detail varchar(max) NOT NULL,
visit int NOT NULL default '0',
status bit NOT NULL default '1',
created_date bigint NOT NULL,

INSERT INTO news ([user_id], title, detail, visit, status, created_date) VALUES(1, 'Extra Content', 'fasdfasdf', 2, 1, 1273431296)

INSERT INTO news ([user_id], title, detail, visit, status, created_date) VALUES(1, 'My My Question', 'this is jpt question.. :D', 16, 1, 1273431389)

INSERT INTO news ([user_id], title, detail, visit, status, created_date) VALUES(2, 'Am I ram?', 'I am !!', 3, 1, 1273431420)


id bigint identity NOT NULL ,
name varchar(255) NOT NULL,
slug varchar(255) NOT NULL,

INSERT INTO tags (name, slug) VALUES('sagarmatha', 'sagarmatha')
INSERT INTO tags (name, slug) VALUES('nepal', 'nepal')
INSERT INTO tags (name, slug) VALUES('gautam buddha', 'gautam-buddha')
INSERT INTO tags (name, slug) VALUES('testing', 'testing')
INSERT INTO tags (name, slug) VALUES('tags', 'tags')
INSERT INTO tags (name, slug) VALUES('tasty apple', 'tasty-apple')
INSERT INTO tags (name, slug) VALUES('banana', 'banana')


CREATE TABLE tags_news (
id bigint identity NOT NULL,
news_id bigint NOT NULL,
tags_id bigint NOT NULL,

INSERT INTO tags_news (news_id, tags_id) VALUES(1, 1)
INSERT INTO tags_news (news_id, tags_id) VALUES(1, 2)
INSERT INTO tags_news (news_id, tags_id) VALUES(1, 3)
INSERT INTO tags_news (news_id, tags_id) VALUES(2, 4)
INSERT INTO tags_news (news_id, tags_id) VALUES(2, 5)
INSERT INTO tags_news (news_id, tags_id) VALUES(2, 6)
INSERT INTO tags_news (news_id, tags_id) VALUES(3, 6)
INSERT INTO tags_news (news_id, tags_id) VALUES(3, 7)


id bigint identity NOT NULL,
[user_id] bigint NOT NULL,
firstname varchar(100) NOT NULL,
lastname varchar(100) NOT NULL,

INSERT INTO users ([user_id], firstname, lastname) VALUES(1, 'Mukesh', 'Chapagain')

INSERT INTO users ([user_id], firstname, lastname) VALUES(2, 'Christopher', 'Gayle')

INSERT INTO users ([user_id], firstname, lastname) VALUES(3, 'Brian', 'Lara')

-- Questions...

  8. SELECT NEWS BY TAG NAME (HERE, tag = ‘nepal’)

Hope this scenario helped you all...........

Are you a web developer or a newbie in web who wants to experiment your newly created website or a prototype and test it locally. If yes then Internet Information Service (IIS) comes to the rescue. Just like Apache, IIS would host the website for you on your computer for free without any hassle which you can access from anywhere on the internet. Follow the steps below to host your own website...

Step 1: First you have to publish your website, for that click on Build on the top menu and then click on Publish Web Site.

Step 2: Following window would open up, just click on the browse button adjacent to the address text box and set the location as given in the following screenshots.

Step 3: If there are no errors in the code and publishing is successful then output box would show something like this.

Step 4: Now your website is published, you now need to setup a web server to host it, here we’d be using Microsoft’s Internet Information Service (IIS).

Step 5: Open IIS manager and  on the left side-bar expand the tree and right-click on the Sites and then click on Add Website….

Step 6: Now give your website a name and enter the path where you published it.

Step 7: If successful the website would appear in the tree on left side-bar as shown below
Step 8: Now make sure to stop the Default Web Site or any other website which is on the same port, here our ’Hello World’ web app is at port 80.
There are two ways of doing it, either right-click on Default Web Site and via Manage Web Site submenu click on Stop, or select Default Web Site and click on Stop in the right side-bar, as shows in the screenshot.
Step 9: Now click on Edit Permissions… as the access to your website would be prohibited on default. For that first make sure Hello World website is selected from the side-bar and then click on Edit Permissions on the right side-bar.

Step 10: Go to Security tab and click on Edit button

Step 11: Now click on Add to allow more users to access this website

Step 12: Now Click on Advanced
Step 13:Now click on Find Now button and search and select Everyone and press the OK button as here in this tutorial we’d be giving access to everyone who tries to access this webpage.

Step 14: Make sure Hello World website is selected on the left side-bar and click on Start in the right side bar as shown below.
(If successfully started then the Start button would be greyed and disabled)
Step 15: Now click on Browse *.80 (http) buttons on the right side-bar.

If everything goes well you’d be seeing your website running. And now your website has been successfully hosted on your computer, and that your computer is working as a web server for your website.

To view it anytime on the computer where you have hosted it just login to http://localhost/ (Or if you have internet connectivity then just login to http://yourIPAddress/).
That's it...cheers.........