Javascript code for “Add To Favorites” in browser

Whenever i open any site today, i can see “Add to Favorite” link on it. So, i think why should i not try this??

When i was search code for it, i don’t get exact…Simple code for “Add To Favorite” is window.external.AddFavorite(url, title).

But it was not working in all browser….So today i come up with multibrowser “Add To Favorite” link.

<script type="text/javascript">

function CreateBookmarkLink()
title = "Your Display Title";
url = "URL To Save in BookMark";
if (window.sidebar)
// Mozilla Firefox Bookmark
window.sidebar.addPanel(title, url, "");
else if (window.external)
// IE Favorite
window.external.AddFavorite(url, title);
else if (window.opera && window.print)
// Opera Hotlist
return true;
if (window.external)
document.write('<a href ="javascript:CreateBookmarkLink()");">Add to Favorites</a>');
else if (window.sidebar)
document.write('<a href ="javascript:CreateBookmarkLink()");">Bookmark Page</a>');
else if (window.opera && window.print)
document.write('<a href ="javascript:CreateBookmarkLink()");">Add Bookmark</a>');

Disable F1-Help key in browser and set your own help file or link or pages etc…

Today, I’m going to describe “how to put your own help file or pages on “F1″ key press?”.

Basically, if you press F1 in browser, it will open general help dialog. So i just had done with it and disable it and put my own help file on F1 key press.

How to do it? Here it is :-

// disable MSIE standard help function
document.onhelp = new Function("return false;");
window.onhelp = new Function("return false;");


// get key stroke for Firefox, Opera, Google Chrome
document.onkeypress = keyHit;

// get key stroke for MSIE, Safari
var browser=navigator.userAgent;
if (|safari/i) != -1) document.onkeydown = keyHit;

// keystroke handling
function keyHit(event) {

// get correct keycode depending on browser
var keyStruck;
if (|safari/i) != -1) keyStruck = window.event.keyCode; else keyStruck = event.keyCode;

if (keyStruck == 112) {
if ( == -1) {    // disable browser standard help function for all but MSIE (see above for MSIE)
keyAction('help');     // call routine to replace standard help function

// You can add the capture of other keystrokes here

// replacement help function
function keyAction(action) {

if (action == 'help') {
// Your new help function goes here
// I have used in conjunction with DHTML Window widget (v1.1) from Dynamic Drive to deliver a new help file

// You can add the actions for other keystrokes here

Formatting .NET Controls using Theme, Skin and CSS


-> To apply Theme and Skin, you have to create folder named “App_Themes” in your project. So to create “App_Themes” Folder, just right click on your project in solution explorer and select “ASP.NET Folder” and in that, select “App_Themes” Folder.

-> Now you have to add skin file in this folder. To do this, just right click on your project name and select “Add New Item” and select “skin” from that dialog.

-> If you will not create folder as mentioned above and direct adding skin file then it will ask you to create folder “App_Themes”. So just click yes and you will see that “App_Themes” folder is created with skin file.

-> Now give any name to skin file that makes easy to remember for you.

-> Next, open skin file and define .NET Control and write properties which you want to apply to that control.
For e.g., you want to apply default theme to all textboxes which are rendered on same page then write like this…

<asp:TextBox runat="server" font-names="Arial" font-size="medium" SkinId="textbox"></asp:TextBox>

remember to not forget to write “runat” and “SkinId” property in any control…

-> After Declaring it in skin file, now you have to apply theme to pages.

-> To do this, you just have to add Theme=”FolderName under which skin file or files are exist” in <@ page> directive in which you want to apply. After that, now in all textboxes in that page, just add SkinId=”textbox” properties.

-> By doing these steps, you will see your formatted textboxes in your page either in debug mode or by selectiing “view in browser”.

-> You can see formatted controls only in debug mode or view in browser mode. Not in design mode. So, just check that whether it is working properly or not.


-> If you apply css externally, then you can see formatted controls in design mode automatically

-> But If you apply css by creating it under Theme folder then you can’t see the formatted controls in design mode directly. How that i will tell you at the end of this section.

-> This is also external css but defined under theme folder. So just for knowledge, i have written about this.

-> To apply CSS to controls, you just have to create css file in theme folder in same way as creating Skin file.

-> Now in all ASP.NET controls, just add new property named “class”.

For e.g.,

<asp:TextBox id="txtName" runat="server" class="text"></asp:TextBox>

<asp:TextBox id="txtAddr" runat="server" class="text"></asp:TextBox>

<asp:TextBox id="txtNo" runat="server" class="Number"></asp:TextBox>

<asp:Label ID="lblName" runat="server" Text="Name :-" class="label"></asp:Label>

-> Here if you want to apply same formatting for more than one controls, then give same class name to those controls as shown above.

-> Now in css file, you just have to define style for every controls using class name or id.

For e.g., in css file using class name,




-> If you want to apply styles using classname then put “.” before classname and if you want to apply styles using id value then put “#” before id value of each controls.

-> Now to apply css to all pages, you just have to add Theme=”FolderName under which css file is exist” in <@ page ..> directive in all pages to whom you want to apply.

-> So after doing this, it will fetch styles from that css file.

-> Now as i told you earlier that you can see formatted controls using css in design mode. So to see them, You have to add StyleSheetTheme=”Name of css file” in <@ page ..> directive in all pages to whom you want to see formatted controls.

-> So after declaring it, you can see formatted controls in design mode using css.

Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack

Today, i will discuss about Response.End, Response.Redirect, and Server.Transfer methods which returns error sometime like “Thread was being aborted” or “Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack.” etc….and why they return it??

Here is reason for error :-

The Response.End method ends the page execution and shifts the execution to the Application_EndRequest event in the application’s event pipeline. The line of code that follows Response.End is not executed.

This problem occurs in the Response.Redirect and Server.Transfer methods because both methods call Response.End internally.

Solution For This Errors :-

For Response.End, call the HttpContext.Current.ApplicationInstance.CompleteRequest method instead of Response.End to bypass the code execution to the Application_EndRequest event.

For Response.Redirect, use an overload, Response.Redirect(String url, bool endResponse) that passes false for the endResponse parameter to suppress the internal call to Response.End.
For example:Response.Redirect (“nextpage.aspx”, false);

If you use this workaround, the code that follows Response.Redirect is executed.
For Server.Transfer, use the Server.Execute method instead.

Get routine backup of MSSql database using .NET application

Today, I will show you the process for “Getting Regular Backup of your application’s database”.

This code can be run in any application either in console application or in window application or in web application.

Here’s the code for Getting Routine Backup:-

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Threading;
using System.Data.SqlClient;
using System.IO;
using Microsoft.Win32;

namespace BackupFullDatabase
    class Program
        static void Main()

            //This will create value entry in if your system reboot, then it will still take back up of your application using this value.
            RegistryKey rkApp = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
            rkApp.SetValue("FullBackup", AppDomain.CurrentDomain.BaseDirectory + "BackupFullDatabase.exe");
            //write this line for console application..b'coz this will hide command prompt displaying on debug process will execute in background...
            System.Diagnostics.ProcessStartInfo prcInfo = new System.Diagnostics.ProcessStartInfo();
            prcInfo.CreateNoWindow = true;
            prcInfo.UseShellExecute = false;

            Console.WriteLine("SQL Server Backup is starting...\n");
            Console.WriteLine("Starting SQL Database Backup...\n");
            bool doDateStamp = true;

            //This will check for folder existance..if not then it will create.....
            if (!Directory.Exists("c:/Backup/"))
            string m_backupDir = "c:/Backup/";
            //These two are user defined functions...
            DoBackups(m_backupDir, doDateStamp);

            int counter = 10;
            while (counter >= 0)
                Thread.Sleep(1000); // Sleep to allow for 1 second timer ticks
                if (counter == 0)

        private static bool DoBackups(string backupDir, bool dateStamp)
            bool allBackupsSuccessful = false;

            StringBuilder sb = new StringBuilder();

            // Build the TSQL statement to run against your databases.
            // SQL is coded inline for portability, and to allow the dynamic
            // appending of datestrings to file names where configured.

            sb.AppendLine(@"DECLARE @name VARCHAR(50) -- database name  ");
            sb.AppendLine(@"DECLARE @path VARCHAR(256) -- path for backup files  ");
            sb.AppendLine(@"DECLARE @fileName VARCHAR(256) -- filename for backup ");
            sb.AppendLine(@"DECLARE @fileDate VARCHAR(20) -- used for file name ");
            sb.AppendLine(@"SET @path = '" + backupDir + "'  ");
            sb.AppendLine(@"SELECT @fileDate = CONVERT(VARCHAR(20),GETDATE(),112) ");
            sb.AppendLine(@"DECLARE db_cursor CURSOR FOR  ");
            sb.AppendLine(@"SELECT name ");
            sb.AppendLine(@"FROM master.dbo.sysdatabases ");
            sb.AppendLine(@"WHERE name NOT IN ('master','model','msdb','tempdb')  ");
            sb.AppendLine(@"OPEN db_cursor   ");
            sb.AppendLine(@"FETCH NEXT FROM db_cursor INTO @name   ");
            sb.AppendLine(@"WHILE @@FETCH_STATUS = 0   ");
            sb.AppendLine(@"BEGIN   ");

            if (dateStamp)
                sb.AppendLine(@"SET @fileName = @path + @name + '_' + @fileDate + '.bak'  ");
                sb.AppendLine(@"SET @fileName = @path + @name + '.bak'  ");
            sb.AppendLine(@"BACKUP DATABASE @name TO DISK = @fileName  ");
            sb.AppendLine(@"FETCH NEXT FROM db_cursor INTO @name   ");
            sb.AppendLine(@"END   ");
            sb.AppendLine(@"CLOSE db_cursor   ");
            sb.AppendLine(@"DEALLOCATE db_cursor; ");

            string connectionStr = @"Data Source=.\SQLEXPRESS;Initial Catalog=master;Integrated Security=true";

            SqlConnection conn = new SqlConnection(connectionStr);

            SqlCommand command = new SqlCommand(sb.ToString(), conn);

                allBackupsSuccessful = true;
            catch (Exception ex)
                Console.WriteLine("An error occurred while running the backup query: " + ex);
                catch (Exception ex)
                    Console.WriteLine("An error occurred while trying to close the database connection:" + ex);

            return allBackupsSuccessful;

        private static void DeleteOldBackups()
            String[] fileInfoArr = Directory.GetFiles("c:/Backup/");

            for (int i = 0; i < fileInfoArr.Length; i++)


        public static void Generate()
            int counter = 20;

            while (counter >= 0)
                if (counter == 0)

1. Copy and paste this code if you want to use in console application…

2. For windows application :-

do the same thing…just some minor changes there..

First of all, delete the form1 from application….and write down the code in program.cs file…

in that….copy and paste this code in class Program….delete the code available in that class before…

–> then put this line “rkApp.SetValue(“FullBackup”, Application.ExecutablePath.ToString());” in place of “rkApp.SetValue(“FullBackup”, AppDomain.CurrentDomain.BaseDirectory + “BackupFullDatabase.exe”);”

–> Remove the three line of processinfo in window application….

3. For Web Application:-

–> Create one class file. copy and paste this code start from main() in this file.

–> just create one global.asax file if not created…

in this file, write below code in Application_start() Event.


For e.g., Backup.Main();

–> So whenever application start, it will call Main Method in Backup class file. No need to create object of class file in this event…

Coding to make files to be downloaded using

Hi Friends,
Today i’m going to show you “How to code for make files to be downloaded from your web application?”.
In the time, Downloading is getting simple functionality and we can found it at every application. When i was searching for it, i didn’t get exact code to do it…
So finally i come with finalize code of “File Download”.
Here it is :-

System.IO.Stream iStream = null;
// Buffer to read 10K bytes in chunk:
byte[] buffer = new Byte[10000];

// Length of the file:
int length;

// Total bytes to read:
long dataToRead;

// Identify the file name.
string filename = System.IO.Path.GetFileName(filepath);
FileInfo myFileInfo = new FileInfo(filepath);
long fileSize = myFileInfo.Length;

    // Open the file.
    iStream = new System.IO.FileStream(filepath, System.IO.FileMode.Open,
    System.IO.FileAccess.Read, System.IO.FileShare.Read);

    // Total bytes to read:
    dataToRead = iStream.Length;

    Response.ContentType = "application/octet-stream";
    //Response.ContentType = "application/x-zip-compressed";
    Response.AddHeader("Content-Disposition", "attachment; filename=" + filename);

    // Read the bytes.
    while (dataToRead > 0)
       // Verify that the client is connected.
       if (Response.IsClientConnected)
          // Read the data in buffer.
          length = iStream.Read(buffer, 0, 10000);

          // Write the data to the current output stream.
          Response.OutputStream.Write(buffer, 0, length);

          // Flush the data to the HTML output.

          buffer = new Byte[10000];
          dataToRead = dataToRead - length;
          //prevent infinite loop if user disconnects
          dataToRead = -1;
 catch (Exception ex)
    // Trap the error, if any.
    Response.Write("Error : " + ex.Message);
    if (iStream != null)
       //Close the file.

C# Conditional Operator (?:) and Null-Coalescing Operator ( ?? )

Today i will show you the conditional operator which is very helpful for code optimization and very useful for beginners who don’t know about this.

Often times in code you want to assign one variable to another, but only if the variable is not null. If it is null, you want to populate the target variable with another ( perhaps default ) value. The code normally may look like this using the C# Conditional Operator:

string fileName = tempFileName != null ?
tempFileName : "Untitled";

If tempFileName is not null, fileName = tempFileName, else fileName = “Untitled“.

This can now be abbreviated as follows using the Null-Coalescing Operator:

string fileName = tempFileName ?? "Untitled";

The logic is the same. If tempFileName is not null, fileName = tempFileName, else fileName = “Untitled“.

The Null-Coalescing Operator comes up a lot with nullable types, particular when converting from a nullable type to its value type:

int? count = null; int amount = count ?? default(int);

Since count is null, amount will now be the default value of an integer type ( zero ).


Show/Hide Server Controls with RadioButtonlist using Javascript

Hi All,

More than one time, i had got the problem to use radiobuttonlist with javascript because i never got access to the exact element of list. so finally i get it and Today i will show you a simple way to hide or show any server side control on selected or checked the radiobuttonlist.

Suppose you have a radiobuttonlist in your aspx page and on selecting different radiobutton, you want to display different results without postback means using javascript.

So Here is the code for that…

Source Code of Your .aspx Page :-

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" ""> <html xmlns=""> <head runat="server"> <title></title> <script type="text/javascript" language="javascript"> function show(rbl, d1, d2) { var rbl = document.getElementById('rbl'); var dv1 = document.getElementById(d1); var dv2 = document.getElementById(d2); var options = rbl.getElementsByTagName("input"); for (var i = 0; i < options.length; i++) { if (options[i].checked) { if (options[i].value == "Male") { = "block"; = "none"; } else if (options[i].value == "Female") { = "none"; = "block"; } } } } </script> </head> <body> <form id="form1" runat="server"> <div id="dvMale" runat="server" style="display: none"> Male</div> <div id="dvFemale" runat="server" style="display: none"> Female</div> <div> <asp:RadioButtonList ID="rbl" runat="server" onclick="show('rbl','dvMale','dvFemale')"> <asp:ListItem Text="Male" Value="Male"></asp:ListItem> <asp:ListItem Text="Female" Value="Female"></asp:ListItem> </asp:RadioButtonList> </div> </form> </body> </html>

So now you can see that on selecting/changing radiobuttons, you can get your display without postback.

Creates a modal dialog box

Creates a modal dialog box that displays the specified HTML document.

  • A modal dialog box retains the input focus while open. The user cannot switch windows until the dialog box is closed.
  • User have not option for minimize or maximize the popup window.
  • User can close the popup window.
  • It works in all browsers like IE, Firefox and Chrome


Create Modal Dialog Box
Dialog Height:


Create Modal Dialog Box <br />
Dialog Height:&nbsp;
<select name='oHeight'>
<input onclick="window.showModalDialog(
	'', '',
	'dialogHeight:' + oHeight.options[oHeight.selectedIndex].text 
	+ 'px;')" type="button" value="Push To Create" />

Tool-tip on drop-down menu items.

In aspx page add dropdown with onmouseover property as shown below:

<asp:DropDownList ID="ddlFlashFile" runat="server" CssClass="txtfield" onmouseover="this.title=this.options[this.selectedIndex].title">

In code behind bind this dropdown and set title property for all menu items as shown below:

List<FlashFilesData> lstFlashFiles = (new FlashFilesSystem()).GetAllFlashFiles();
lstFlashFiles.Insert(0, new FlashFilesData { FileID = 0, FileTitle = "-- Select --", FileDescription = "none" });
foreach (FlashFilesData obj in lstFlashFiles)
   ListItem liNewItem = new ListItem(obj.FileTitle, obj.FileID.ToString());
   liNewItem.Attributes.Add("title", obj.FileDescription);
   liNewItem.Attributes.Add("fileName", obj.FileName);