Thursday, December 24, 2009

Hide console window in console application

As you all know when you execute an console application it will load command prompt and shows out put. There are amny situation in which you do not want this console window to be dislayed to user while your application runing. You can do that by calling some unmanaged functions. I have used following method to do that which is posted by Brendan Grant on MSDN
using System.Runtime.InteropServices;
[DllImport("user32.dll")]
public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

[DllImport("user32.dll")]
static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
IntPtr hWnd = FindWindow(null, title);
 if (hWnd != IntPtr.Zero)
 {
       if (!visible)
          //Hide the window                    
          ShowWindow(hWnd, 0); // 0 = SW_HIDE               
       else
          //Show window again                   
          ShowWindow(hWnd, 1); //1 = SW_SHOWNORMA          
}

Raise event from user control to main page / Event delegation from user control to aspx page in ASP.NET,C#

"What is delegate?" we all have faced this question in one or more interview. :) and the most common answer is "Function pointer". Here I am showing a simple example of delegate. I have one user control and one aspx page. The user control contains one button. When user click on this button I will call a method on main page using delegate. Here is my user control,

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="WebUserControl.ascx.cs" Inherits="Dalegate_WebUserControl" %>
<
asp:Button ID="btnTest" runat="server" Text="I am Inside User Control" OnClick="btnTest_Click" />
public
partial class Dalegate_WebUserControl : System.Web.UI.UserControl
{
    // Delegate declaration
    public delegate void OnButtonClick(string strValue);

    // Event declaration
    public event OnButtonClick btnHandler;
   
    // Page load
    protected void Page_Load(object sender, EventArgs e)
    {
      
    }
    protected void btnTest_Click(object sender, EventArgs e)
    {
           // Check if event is null
           if (btnHandler != null)
               btnHandler(string.Empty);

           // Write some text to output
           Response.Write("User Control's Button Click <BR/>");
    }
}

WebUserControl.ascx.cs

          Above code first check whether btnHandler is not null and than raise the event by passing argument. You can pass any number of argument in event. You need to change public delegate void OnButtonClick(string strValue) and btnHandler(string.Empty) lines for changing number of arguments. Now take a look at aspx page,

<%@
Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="Dalegate_Default" %>
<%@
Register Src="WebUserControl.ascx" TagName="WebUserControl" TagPrefix="uc1" %>
<!
DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<
html xmlns="http://www.w3.org/1999/xhtml" >
<
head runat="server">
    <title>Untitled Page</title>
</
head>
<
body>
    <form id="form1" runat="server">
    <div>
        <asp:Label ID="lblText" Text="I am On Main Page : "
                   runat
="server"></asp:Label>
        <asp:DropDownList ID="ddlTemp" runat="server">
            <asp:ListItem>Chirag</asp:ListItem>
            <asp:ListItem>Dipak</asp:ListItem>
            <asp:ListItem>Shailesh</asp:ListItem>
        </asp:DropDownList>
        <br />
        <br />
        <uc1:WebUserControl ID="WebUserControl1"
           runat="server" />   
    </div>
    </form>
</
body>
</
html>

Default.aspx

        Default.aspx has one drop down list and a user control as shown in above code. Lets look at cs file,

public
partial class Dalegate_Default : System.Web.UI.Page
{
      protected void Page_Load(object sender, EventArgs e)
      {
             // Declare and Define Event of User Control. When User
             // Clicks on button (which is inside UserControl)
             // below event is raised as I have called raised that
             // event on Button Click
             WebUserControl1.btnHandler += new
             Dalegate_WebUserControl
.OnButtonClick
            
(WebUserControl1_btnHandler);
       
      }

      void WebUserControl1_btnHandler(string strValue)
      {
             Response.Write("Main Page Event<BR/>Selected
                  Value: "
+ ddlTemp.SelectedItem.Text + "<BR/>");
      }   
}

Default.aspx.cs

            Now when you run the application and clicks on button you can see that when user click on button the user control raise the click event and calls the WebUserControl1_btnHandler(string strValue) method on main page.

Source: chiragrdarji

Repositioning a Background Bitmap

Normally, you only options for displaying a background bitmap are tiled, centered, or stretch to fit (with the Plus Pack).
You can edit the registry and have a third option which is to place the bitmap anywhere on your screen by specifying the X and Y coordinates.
  1. Start Regedit
  2. Go to HKEY_CURRENT_USER / Control Panel / Desktop
  3. Create new Strings called WallpaperOriginX and WallpaperOriginY
  4. Give them values to position them around your desktop
  5. The bitmap must be smaller than your desktop size

Expanding All Subfolders in Explorer

To quickly have Explorer expand all subfolders for a selected drive or folder, simply press the asterisk (*) key on the numeric keypad.

Opening a Command Prompt to a Particular Directory from Explorer

If you want to open a command prompt to a directory that is selected in the Explorer:
  • Start Regedit
  • Go to HKEY_CLASSES_ROOT \ Directory \ shell
  • Create a new key called Command
  • Give it the value of the name you want to appear in the Explorer. Something like Open DOS Box
  • Under this create a new key called command
  • Give it a value of " cmd.exe cd %1 " (no quotes)
  • Now when you are in the Explorer, right click on a folder, select Open DOS Box, and a command prompt will open to the selected directory.

String/Number format

Strings

There really isn't any formatting within a strong, beyond it's alignment. Alignment works for any argument being printed in a String.Format call.
Sample Generates
String.Format("->{1,10}<-", "Hello"); ->     Hello<-
 String.Format("->{1,-10}<-", "Hello"); ->Hello     <-

Numbers

Basic number formatting specifiers:
Specifier Type Format  Output (Passed Double 1.42) Output (Passed Int -12400)
c Currency {0:c} $1.42 -$12,400
d Decimal (Whole number) {0:d} System.FormatException -12400
e Scientific {0:e} 1.420000e+000 -1.240000e+004
f Fixed point {0:f} 1.42 -12400.00
g General {0:g} 1.42 -12400
n Number with commas for thousands {0:n} 1.42 -12,400
r Round trippable {0:r} 1.42 System.FormatException
x Hexadecimal {0:x4} System.FormatException cf90

Custom number formatting:

Specifier Type Example   Output (Passed Double 1500.42) Note
0 Zero placeholder {0:00.0000} 1500.4200 Pads with zeroes.
# Digit placeholder {0:(#).##} (1500).42  
. Decimal point {0:0.0} 1500.4  
, Thousand separator {0:0,0} 1,500 Must be between two zeroes.
,. Number scaling {0:0,.} 2 Comma adjacent to Period scales by 1000.
% Percent {0:0%} 150042% Multiplies by 100, adds % sign.
e Exponent placeholder {0:00e+0} 15e+2 Many exponent formats available.
; Group separator see below    

The group separator is especially useful for formatting currency values which require that negative values be enclosed in parentheses.  This currency formatting example at the bottom of this document makes it obvious:

Dates

Note that date formatting is especially dependant on the system's regional settings; the example strings here are from my local locale.

Specifier Type Example (Passed System.DateTime.Now)
d Short date 10/12/2002
D Long date December 10, 2002
t Short time 10:11 PM
T Long time 10:11:29 PM
f Full date & time December 10, 2002 10:11 PM
F Full date & time (long) December 10, 2002 10:11:29 PM
g Default date & time 10/12/2002 10:11 PM
G Default date & time (long) 10/12/2002 10:11:29 PM
M Month day pattern December 10
r RFC1123 date string Tue, 10 Dec 2002 22:11:29 GMT
s Sortable date string 2002-12-10T22:11:29
u Universal sortable, local time 2002-12-10 22:13:50Z
U Universal sortable, GMT December 11, 2002 3:13:50 AM
Y Year month pattern December, 2002

The 'U' specifier seems broken; that string certainly isn't sortable.

Custom date formatting:

Specifier Type Example   Example Output
dd Day {0:dd} 10
ddd Day name {0:ddd} Tue
dddd Full day name {0:dddd} Tuesday
f, ff, ... Second fractions {0:fff} 932
gg, ... Era {0:gg} A.D.
hh 2 digit hour {0:hh} 10
HH 2 digit hour, 24hr format {0:HH} 22
mm Minute 00-59 {0:mm} 38
MM Month 01-12 {0:MM} 12
MMM Month abbreviation {0:MMM} Dec
MMMM Full month name {0:MMMM} December
ss Seconds 00-59 {0:ss} 46
tt AM or PM {0:tt} PM
yy Year, 2 digits {0:yy} 02
yyyy Year {0:yyyy} 2002
zz Timezone offset, 2 digits {0:zz} -05
zzz Full timezone offset {0:zzz} -05:00
: Separator {0:hh:mm:ss} 10:43:20
/ Separator {0:dd/mm/yyyy} 10/12/2002

Enumerations

Specifier Type
g Default (Flag names if available, otherwise decimal)
f Flags always
d Integer always
x Eight digit hex.

Some Useful Examples

String.Format("{0:$#,##0.00;($#,##0.00);Zero}", value);

This will output "$1,240.00" if passed 1243.50.  It will output the same format but in parentheses if the number is negative, and will output the string "Zero" if the number is zero.

String.Format("{0:(###) ###-####}", 18005551212);

This will output "(800) 555-1212".

Add new item to dropdownlist

Add new options to the exisitng dropdown lsit
function addOption(object,text,value) {
    var defaultSelected = false;
    var selected = false;
    var optionName = new Option(text, value, defaultSelected, selected)
    object.options[object.length] = optionName;
    object.options[object.length-1].selected = false;
}

Wednesday, December 23, 2009

Reqular Expression in javascript

Decimal : \d{1,5}(\.\d{1,2})? Integer :\d{2} Money : /^\d+\.\d{2}$/; Age = /^(1[0-2]\d\d{1,2})$/;

Friday, December 18, 2009

Generate Insert Statement SQL

SET NOCOUNT ON
GO

PRINT 'Using Master database'
USE master
GO

PRINT 'Checking for the existence of this procedure'
IF (SELECT OBJECT_ID('sp_generate_inserts','P')) IS NOT NULL --means, the procedure already exists
 BEGIN
  PRINT 'Procedure already exists. So, dropping it'
  DROP PROC sp_generate_inserts
 END
GO

CREATE PROC sp_generate_inserts
(
 @table_name varchar(776),    
 -- The table/view for which the INSERT statements will be generated using the existing data
 @target_table varchar(776) = NULL,  
 -- Use this parameter to specify a different table name into which the data will be inserted
 @include_column_list bit = 1,  
 -- Use this parameter to include/ommit column list in the generated INSERT statement
 @from varchar(800) = NULL,   
 -- Use this parameter to filter the rows based on a filter condition (using WHERE)
 @include_timestamp bit = 0,   
 -- Specify 1 for this parameter, if you want to include the TIMESTAMP/ROWVERSION column's data in the INSERT statement
 @debug_mode bit = 0,   
 -- If @debug_mode is set to 1, the SQL statements constructed by this procedure will be printed for later examination
 @owner varchar(64) = NULL,  
 -- Use this parameter if you are not the owner of the table
 @ommit_images bit = 0,   
 -- Use this parameter to generate INSERT statements by omitting the 'image' columns
 @ommit_identity bit = 0,  
 -- Use this parameter to ommit the identity columns
 @top int = NULL,   
 -- Use this parameter to generate INSERT statements only for the TOP n rows
 @cols_to_include varchar(8000) = NULL, 
 -- List of columns to be included in the INSERT statement
 @cols_to_exclude varchar(8000) = NULL, 
 -- List of columns to be excluded from the INSERT statement
 @disable_constraints bit = 0,  
 -- When 1, disables foreign key constraints and enables them after the INSERT statements
 @ommit_computed_cols bit = 0  
 -- When 1, computed columns will not be included in the INSERT statement
 
)
AS
BEGIN

--Example 1: To generate INSERT statements for table 'titles':
--  
--  EXEC sp_generate_inserts 'titles'
--
--Example 2:  To ommit the column list in the INSERT statement: (Column list is included by default)
--  IMPORTANT: If you have too many columns, you are advised to ommit column list, as shown below,
--  to avoid erroneous results
--  
--  EXEC sp_generate_inserts 'titles', @include_column_list = 0
--
--Example 3: To generate INSERT statements for 'titlesCopy' table from 'titles' table:
--
--  EXEC sp_generate_inserts 'titles', 'titlesCopy'
--
--Example 4: To generate INSERT statements for 'titles' table for only those titles 
--  which contain the word 'Computer' in them:
--  NOTE: Do not complicate the FROM or WHERE clause here. It's assumed that you are good with T-SQL if you are using this parameter
--
--  EXEC sp_generate_inserts 'titles', @from = "from titles where title like '%Computer%'"
--
--Example 5:  To specify that you want to include TIMESTAMP column's data as well in the INSERT statement:
--  (By default TIMESTAMP column's data is not scripted)
--
--  EXEC sp_generate_inserts 'titles', @include_timestamp = 1
--
--Example 6: To print the debug information:
--  
--  EXEC sp_generate_inserts 'titles', @debug_mode = 1
--
--Example 7:  If you are not the owner of the table, use @owner parameter to specify the owner name
--  To use this option, you must have SELECT permissions on that table
--
--  EXEC sp_generate_inserts Nickstable, @owner = 'Nick'
--
--Example 8:  To generate INSERT statements for the rest of the columns excluding images
--  When using this otion, DO NOT set @include_column_list parameter to 0.
--
--  EXEC sp_generate_inserts imgtable, @ommit_images = 1
--
--Example 9:  To generate INSERT statements excluding (ommiting) IDENTITY columns:
--  (By default IDENTITY columns are included in the INSERT statement)
--
--  EXEC sp_generate_inserts mytable, @ommit_identity = 1
--
--Example 10:  To generate INSERT statements for the TOP 10 rows in the table:
--  
--  EXEC sp_generate_inserts mytable, @top = 10
--
--Example 11:  To generate INSERT statements with only those columns you want:
--  
--  EXEC sp_generate_inserts titles, @cols_to_include = "'title','title_id','au_id'"
--
--Example 12:  To generate INSERT statements by omitting certain columns:
--  
--  EXEC sp_generate_inserts titles, @cols_to_exclude = "'title','title_id','au_id'"
--
--Example 13: To avoid checking the foreign key constraints while loading data with INSERT statements:
--  
--  EXEC sp_generate_inserts titles, @disable_constraints = 1
--
--Example 14:  To exclude computed columns from the INSERT statement:
--  EXEC sp_generate_inserts MyTable, @ommit_computed_cols = 1


SET NOCOUNT ON

--Making sure user only uses either @cols_to_include or @cols_to_exclude
IF ((@cols_to_include IS NOT NULL) AND (@cols_to_exclude IS NOT NULL))
 BEGIN
  RAISERROR('Use either @cols_to_include or @cols_to_exclude. Do not use both the parameters at once',16,1)
  RETURN -1 --Failure. Reason: Both @cols_to_include and @cols_to_exclude parameters are specified
 END

--Making sure the @cols_to_include and @cols_to_exclude parameters are receiving values in proper format
IF ((@cols_to_include IS NOT NULL) AND (PATINDEX('''%''',@cols_to_include) = 0))
 BEGIN
  RAISERROR('Invalid use of @cols_to_include property',16,1)
  PRINT 'Specify column names surrounded by single quotes and separated by commas'
  PRINT 'Eg: EXEC sp_generate_inserts titles, @cols_to_include = "''title_id'',''title''"'
  RETURN -1 --Failure. Reason: Invalid use of @cols_to_include property
 END

IF ((@cols_to_exclude IS NOT NULL) AND (PATINDEX('''%''',@cols_to_exclude) = 0))
 BEGIN
  RAISERROR('Invalid use of @cols_to_exclude property',16,1)
  PRINT 'Specify column names surrounded by single quotes and separated by commas'
  PRINT 'Eg: EXEC sp_generate_inserts titles, @cols_to_exclude = "''title_id'',''title''"'
  RETURN -1 --Failure. Reason: Invalid use of @cols_to_exclude property
 END


--Checking to see if the database name is specified along wih the table name
--Your database context should be local to the table for which you want to generate INSERT statements
--specifying the database name is not allowed
IF (PARSENAME(@table_name,3)) IS NOT NULL
 BEGIN
  RAISERROR('Do not specify the database name. Be in the required database and just specify the table name.',16,1)
  RETURN -1 --Failure. Reason: Database name is specified along with the table name, which is not allowed
 END

--Checking for the existence of 'user table' or 'view'
--This procedure is not written to work on system tables
--To script the data in system tables, just create a view on the system tables and script the view instead

IF @owner IS NULL
 BEGIN
  IF ((OBJECT_ID(@table_name,'U') IS NULL) AND (OBJECT_ID(@table_name,'V') IS NULL)) 
   BEGIN
    RAISERROR('User table or view not found.',16,1)
    PRINT 'You may see this error, if you are not the owner of this table or view. In that case use @owner parameter to specify the owner name.'
    PRINT 'Make sure you have SELECT permission on that table or view.'
    RETURN -1 --Failure. Reason: There is no user table or view with this name
   END
 END
ELSE
 BEGIN
  IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = @table_name AND (TABLE_TYPE = 'BASE TABLE' OR TABLE_TYPE = 'VIEW') AND TABLE_SCHEMA = @owner)
   BEGIN
    RAISERROR('User table or view not found.',16,1)
    PRINT 'You may see this error, if you are not the owner of this table. In that case use @owner parameter to specify the owner name.'
    PRINT 'Make sure you have SELECT permission on that table or view.'
    RETURN -1 --Failure. Reason: There is no user table or view with this name  
   END
 END

--Variable declarations
DECLARE  @Column_ID int,   
  @Column_List varchar(8000), 
  @Column_Name varchar(128), 
  @Start_Insert varchar(786), 
  @Data_Type varchar(128), 
  @Actual_Values varchar(8000), --This is the string that will be finally executed to generate INSERT statements
  @IDN varchar(128)  --Will contain the IDENTITY column's name in the table

--Variable Initialization
SET @IDN = ''
SET @Column_ID = 0
SET @Column_Name = ''
SET @Column_List = ''
SET @Actual_Values = ''

IF @owner IS NULL 
 BEGIN
  SET @Start_Insert = 'INSERT INTO ' + '[' + RTRIM(COALESCE(@target_table,@table_name)) + ']' 
 END
ELSE
 BEGIN
  SET @Start_Insert = 'INSERT ' + '[' + LTRIM(RTRIM(@owner)) + '].' + '[' + RTRIM(COALESCE(@target_table,@table_name)) + ']'   
 END


--To get the first column's ID

SELECT @Column_ID = MIN(ORDINAL_POSITION)  
FROM INFORMATION_SCHEMA.COLUMNS (NOLOCK) 
WHERE  TABLE_NAME = @table_name AND
(@owner IS NULL OR TABLE_SCHEMA = @owner)



--Loop through all the columns of the table, to get the column names and their data types
WHILE @Column_ID IS NOT NULL
 BEGIN
  SELECT  @Column_Name = QUOTENAME(COLUMN_NAME), 
  @Data_Type = DATA_TYPE 
  FROM  INFORMATION_SCHEMA.COLUMNS (NOLOCK) 
  WHERE  ORDINAL_POSITION = @Column_ID AND 
  TABLE_NAME = @table_name AND
  (@owner IS NULL OR TABLE_SCHEMA = @owner)

  IF @cols_to_include IS NOT NULL --Selecting only user specified columns
  BEGIN
   IF CHARINDEX( '''' + SUBSTRING(@Column_Name,2,LEN(@Column_Name)-2) + '''',@cols_to_include) = 0 
   BEGIN
    GOTO SKIP_LOOP
   END
  END

  IF @cols_to_exclude IS NOT NULL --Selecting only user specified columns
  BEGIN
   IF CHARINDEX( '''' + SUBSTRING(@Column_Name,2,LEN(@Column_Name)-2) + '''',@cols_to_exclude) <> 0 
   BEGIN
    GOTO SKIP_LOOP
   END
  END

  --Making sure to output SET IDENTITY_INSERT ON/OFF in case the table has an IDENTITY column
  IF (SELECT COLUMNPROPERTY( OBJECT_ID(QUOTENAME(COALESCE(@owner,USER_NAME())) + '.' + @table_name),SUBSTRING(@Column_Name,2,LEN(@Column_Name) - 2),'IsIdentity')) = 1 
  BEGIN
   IF @ommit_identity = 0 --Determing whether to include or exclude the IDENTITY column
    SET @IDN = @Column_Name
   ELSE
    GOTO SKIP_LOOP   
  END
  
  --Making sure whether to output computed columns or not
  IF @ommit_computed_cols = 1
  BEGIN
   IF (SELECT COLUMNPROPERTY( OBJECT_ID(QUOTENAME(COALESCE(@owner,USER_NAME())) + '.' + @table_name),SUBSTRING(@Column_Name,2,LEN(@Column_Name) - 2),'IsComputed')) = 1 
   BEGIN
    GOTO SKIP_LOOP     
   END
  END
  
  --Tables with columns of IMAGE data type are not supported for obvious reasons
  IF(@Data_Type in ('image'))
   BEGIN
    IF (@ommit_images = 0)
     BEGIN
      RAISERROR('Tables with image columns are not supported.',16,1)
      PRINT 'Use @ommit_images = 1 parameter to generate INSERTs for the rest of the columns.'
      PRINT 'DO NOT ommit Column List in the INSERT statements. If you ommit column list using @include_column_list=0, the generated INSERTs will fail.'
      RETURN -1 --Failure. Reason: There is a column with image data type
     END
    ELSE
     BEGIN
     GOTO SKIP_LOOP
     END
   END

  --Determining the data type of the column and depending on the data type, the VALUES part of
  --the INSERT statement is generated. Care is taken to handle columns with NULL values. Also
  --making sure, not to lose any data from flot, real, money, smallmomey, datetime columns
  SET @Actual_Values = @Actual_Values  +
  CASE 
   WHEN @Data_Type IN ('char','varchar','nchar','nvarchar') 
    THEN 
     'COALESCE('''''''' + REPLACE(RTRIM(' + @Column_Name + '),'''''''','''''''''''')+'''''''',''NULL'')'
   WHEN @Data_Type IN ('datetime','smalldatetime') 
    THEN 
     'COALESCE('''''''' + RTRIM(CONVERT(char,' + @Column_Name + ',109))+'''''''',''NULL'')'
   WHEN @Data_Type IN ('uniqueidentifier') 
    THEN  
     'COALESCE('''''''' + REPLACE(CONVERT(char(255),RTRIM(' + @Column_Name + ')),'''''''','''''''''''')+'''''''',''NULL'')'
   WHEN @Data_Type IN ('text','ntext') 
    THEN  
     'COALESCE('''''''' + REPLACE(CONVERT(char(8000),' + @Column_Name + '),'''''''','''''''''''')+'''''''',''NULL'')'     
   WHEN @Data_Type IN ('binary','varbinary') 
    THEN  
     'COALESCE(RTRIM(CONVERT(char,' + 'CONVERT(int,' + @Column_Name + '))),''NULL'')'  
   WHEN @Data_Type IN ('timestamp','rowversion') 
    THEN  
     CASE 
      WHEN @include_timestamp = 0 
       THEN 
        '''DEFAULT''' 
       ELSE 
        'COALESCE(RTRIM(CONVERT(char,' + 'CONVERT(int,' + @Column_Name + '))),''NULL'')'  
     END
   WHEN @Data_Type IN ('float','real','money','smallmoney')
    THEN
     'COALESCE(LTRIM(RTRIM(' + 'CONVERT(char, ' +  @Column_Name  + ',2)' + ')),''NULL'')' 
   ELSE 
    'COALESCE(LTRIM(RTRIM(' + 'CONVERT(char, ' +  @Column_Name  + ')' + ')),''NULL'')' 
  END   + '+' +  ''',''' + ' + '
  
  --Generating the column list for the INSERT statement
  SET @Column_List = @Column_List +  @Column_Name + ',' 

  SKIP_LOOP: --The label used in GOTO

  SELECT  @Column_ID = MIN(ORDINAL_POSITION) 
  FROM  INFORMATION_SCHEMA.COLUMNS (NOLOCK) 
  WHERE  TABLE_NAME = @table_name AND 
  ORDINAL_POSITION > @Column_ID AND
  (@owner IS NULL OR TABLE_SCHEMA = @owner)


 --Loop ends here!
 END

--To get rid of the extra characters that got concatenated during the last run through the loop
SET @Column_List = LEFT(@Column_List,len(@Column_List) - 1)
SET @Actual_Values = LEFT(@Actual_Values,len(@Actual_Values) - 6)

IF LTRIM(@Column_List) = '' 
 BEGIN
  RAISERROR('No columns to select. There should at least be one column to generate the output',16,1)
  RETURN -1 --Failure. Reason: Looks like all the columns are ommitted using the @cols_to_exclude parameter
 END

--Forming the final string that will be executed, to output the INSERT statements
IF (@include_column_list <> 0)
 BEGIN
  SET @Actual_Values = 
   'SELECT ' +  
   CASE WHEN @top IS NULL OR @top < 0 THEN '' ELSE ' TOP ' + LTRIM(STR(@top)) + ' ' END + 
   '''' + RTRIM(@Start_Insert) + 
   ' ''+' + '''(' + RTRIM(@Column_List) +  '''+' + ''')''' + 
   ' +''VALUES(''+ ' +  @Actual_Values  + '+'')''' + ' ' + 
   COALESCE(@from,' FROM ' + CASE WHEN @owner IS NULL THEN '' ELSE '[' + LTRIM(RTRIM(@owner)) + '].' END + '[' + rtrim(@table_name) + ']' + '(NOLOCK)')
 END
ELSE IF (@include_column_list = 0)
 BEGIN
  SET @Actual_Values = 
   'SELECT ' + 
   CASE WHEN @top IS NULL OR @top < 0 THEN '' ELSE ' TOP ' + LTRIM(STR(@top)) + ' ' END + 
   '''' + RTRIM(@Start_Insert) + 
   ' '' +''VALUES(''+ ' +  @Actual_Values + '+'')''' + ' ' + 
   COALESCE(@from,' FROM ' + CASE WHEN @owner IS NULL THEN '' ELSE '[' + LTRIM(RTRIM(@owner)) + '].' END + '[' + rtrim(@table_name) + ']' + '(NOLOCK)')
 END 

--Determining whether to ouput any debug information
IF @debug_mode =1
 BEGIN
  PRINT '/*****START OF DEBUG INFORMATION*****'
  PRINT 'Beginning of the INSERT statement:'
  PRINT @Start_Insert
  PRINT ''
  PRINT 'The column list:'
  PRINT @Column_List
  PRINT ''
  PRINT 'The SELECT statement executed to generate the INSERTs'
  PRINT @Actual_Values
  PRINT ''
  PRINT '*****END OF DEBUG INFORMATION*****/'
  PRINT ''
 END
  
PRINT '--INSERTs generated by ''sp_generate_inserts'' stored procedure written by Vyas'
PRINT '--Build number: 22'
PRINT '--Problems/Suggestions? Contact Vyas @ vyaskn@hotmail.com'
PRINT '--http://vyaskn.tripod.com'
PRINT ''
PRINT 'SET NOCOUNT ON'
PRINT ''


--Determining whether to print IDENTITY_INSERT or not
IF (@IDN <> '')
 BEGIN
  PRINT 'SET IDENTITY_INSERT ' + QUOTENAME(COALESCE(@owner,USER_NAME())) + '.' + QUOTENAME(@table_name) + ' ON'
  PRINT 'GO'
  PRINT ''
 END


IF @disable_constraints = 1 AND (OBJECT_ID(QUOTENAME(COALESCE(@owner,USER_NAME())) + '.' + @table_name, 'U') IS NOT NULL)
 BEGIN
  IF @owner IS NULL
   BEGIN
    SELECT  'ALTER TABLE ' + QUOTENAME(COALESCE(@target_table, @table_name)) + ' NOCHECK CONSTRAINT ALL' AS '--Code to disable constraints temporarily'
   END
  ELSE
   BEGIN
    SELECT  'ALTER TABLE ' + QUOTENAME(@owner) + '.' + QUOTENAME(COALESCE(@target_table, @table_name)) + ' NOCHECK CONSTRAINT ALL' AS '--Code to disable constraints temporarily'
   END

  PRINT 'GO'
 END

PRINT ''
PRINT 'PRINT ''Inserting values into ' + '[' + RTRIM(COALESCE(@target_table,@table_name)) + ']' + ''''


--All the hard work pays off here!!! You'll get your INSERT statements, when the next line executes!
EXEC (@Actual_Values)

PRINT 'PRINT ''Done'''
PRINT ''


IF @disable_constraints = 1 AND (OBJECT_ID(QUOTENAME(COALESCE(@owner,USER_NAME())) + '.' + @table_name, 'U') IS NOT NULL)
 BEGIN
  IF @owner IS NULL
   BEGIN
    SELECT  'ALTER TABLE ' + QUOTENAME(COALESCE(@target_table, @table_name)) + ' CHECK CONSTRAINT ALL'  AS '--Code to enable the previously disabled constraints'
   END
  ELSE
   BEGIN
    SELECT  'ALTER TABLE ' + QUOTENAME(@owner) + '.' + QUOTENAME(COALESCE(@target_table, @table_name)) + ' CHECK CONSTRAINT ALL' AS '--Code to enable the previously disabled constraints'
   END

  PRINT 'GO'
 END

PRINT ''
IF (@IDN <> '')
 BEGIN
  PRINT 'SET IDENTITY_INSERT ' + QUOTENAME(COALESCE(@owner,USER_NAME())) + '.' + QUOTENAME(@table_name) + ' OFF'
  PRINT 'GO'
 END

PRINT 'SET NOCOUNT OFF'


SET NOCOUNT OFF
RETURN 0 --Success. We are done!
END

GO

PRINT 'Created the procedure'
GO


--Mark procedure as system object
EXEC sys.sp_MS_marksystemobject sp_generate_inserts
GO

PRINT 'Granting EXECUTE permission on sp_generate_inserts to all users'
GRANT EXEC ON sp_generate_inserts TO public

SET NOCOUNT OFF
GO

PRINT 'Done'

Friday, December 11, 2009

Sys types

"Type" columns of SysObjects table represent the different objects available in database (like Table,Trigger,Stored Procedures etc.). Below list explains the different values of "Type" columns.
C = CHECK constraint 
D = Default or DEFAULT constraint
F = FOREIGN KEY constraint 
FN = Scalar function
IF = Inlined table-function
K = PRIMARY KEY or UNIQUE constraint 
L = Log
P = Stored procedure
R = Rule
RF = Replication filter stored procedure
S = System table 
TF = Table function
TR = Trigger
U = User table
V = View
X = Extended stored procedure

How to Encrypt web.config

The most sensitive information stored in web.config file can be the connection string. You do not want to disclose the information related to your database to all the users where the application is deployed. Every time it is not possible to have a private machine for your sites, you may need to deploy the site in shared host environment. To encrypt the connection string in above situation is advisable.

ASP.NET 2.0 provides in built functionality to encrypt few sections of web.config file. The task can be completed using Aspnet_regiis.exe.

Encryption:

For File System Application
aspnet_regiis.exe -pef "connectionStrings" C:\Projects\DemoApplication

For IIS based Application
aspnet_regiis.exe -pe "connectionStrings" -app "/DemoApplication"

Decryption:
 
For File System Application,
aspnet_regiis.exe -pdf "connectionStrings" C:\Projects\DemoApplication

For IIS based Application
aspnet_regiis.exe -pd "connectionStrings" -app "/DemoApplication"


Tooltip

First, add the following CSS to those pages that use the rich tooltips:
.skmTooltipHost
{
 cursor: help;
 border-bottom: dotted 1px brown;
}

.skmTooltipContainer
{
    padding-left: 10px;
    padding-right: 10px;
    padding-top: 3px;
    padding-bottom: 3px;
    display: none;
    position: absolute;
    background-color: #ff9;
    border: solid 1px #333;
    z-index: 999;
}

Next, add the following function to your page
<script type="text/javascript">
  $(document).ready(function() {
     $(".skmTooltipHost").hover(
       function() {
       $(this).append('<div class="skmTooltipContainer">' + $(this).attr('tooltip') + '</div>');
  
       $(this).find('.skmTooltipContainer').css("left", $(this).position().left + 20);
       $(this).find('.skmTooltipContainer').css("top", $(this).position().top + $(this).height());
        $(".skmTooltipContainer").fadeIn(500);
      },
 
       function() {
        $(".skmTooltipContainer").fadeTo(500, 1.0, function() { $(this).remove(); });
       }
     );
  });
</script>
Finally copy the lines
<p>
   This example shows how to use jQuery and a touch of CSS to display rich 
   <span class="skmTooltipHost" tooltip="Dictionary.com defines &lt;a href=&quot;http://dictionary.reference.com/browse/tooltip&quot;&gt;tooltip&lt;/a&gt; as, &quot;a small rectangular pop-up window that displays a brief description of a toolbar button when a computer mouse lands on that button.&quot;">tooltips</span> 
   when hovering over an HTML element.
  </p>

Webservice: Access Denied

When you try to call a Web service application and Anonymous access authentication is turned off, you may receive the following error message.

The request failed with HTTP status 401: Access Denied.


//Create an instance of the CredentialCache class.
CredentialCache cache = new CredentialCache();

// Add a NetworkCredential instance to CredentialCache.
// Negotiate for NTLM or Kerberos authentication.
cache.Add( new Uri(myProxy.Url), "Negotiate", new NetworkCredential("UserName", "Password", "Domain")); 

//Assign CredentialCache to the Web service Client Proxy(myProxy) Credetials property.
myProxy.Credentials = cache;

Suppose if you want supply your windows credential use the bellow code:
//Assigning DefaultCredentials to the Credentials property
//of the Web service client proxy (myProxy).
myProxy.Credentials= System.Net.CredentialCache.DefaultCredentials;

Reference: http://support.microsoft.com/kb/811318

Wednesday, December 9, 2009

Set Time out

  function f1() {
    alert(1);
    setTimeout(f2, 5000);
    function f2() {
      alert(2);
      setTimeout(f3, 5000);
      function f3() {
        alert(3);
      }
    }
  }
  f1();   

Tuesday, December 8, 2009

Rich Text Box

<style>
  .RTBtransparent { display: none; z-index: -10; filter: alpha(opacity=30); width: 0px; position: absolute; height: 0px; background-color: #000000; opacity: 0.3; }
  .RTBbutton { border-right: #f4f4f3 1px solid; border-top: #f4f4f3 1px solid; border-left: #f4f4f3 1px solid; border-bottom: #f4f4f3 1px solid; }
  .RTBbuttonDown { border-right: #000000 1px solid; border-top: #000000 1px solid; border-left: #000000 1px solid; border-bottom: #000000 1px solid; background-color: #ffffcc; }
  .RTBbuttonOver { border-right: #000000 1px solid; border-top: #000000 1px solid; border-left: #000000 1px solid; border-bottom: #000000 1px solid; background-color: #ffffcc; }
  .RTBInnerTable { border-right: #c0c0c0 1px solid; border-top: #c0c0c0 1px solid; border-left: #c0c0c0 1px solid; border-bottom: #c0c0c0 1px solid; background-color: #f4f4f3; }
  .RTBDDL { border-right: #000000 1px solid; border-top: #000000 1px solid; font-size: 11px; border-left: #000000 1px solid; border-bottom: #000000 1px solid; font-family: Arial, Helvetica, sans-serif; background-color: #f4f4f3; }
  .RTBframe { border-right: #cccccc 1px solid; border-top: #cccccc 1px solid; margin-top: -1px; display: inline; margin-bottom: -1px; border-left: #cccccc 1px solid; border-bottom: #cccccc 1px solid; }
  .RTB_TD { font-size: 11px; font-family: Arial, Helvetica, sans-serif; }
</style>
<script type="text/javascript" type="text/javascript">
  var isHTMLMode = false; var RTB_Frame = ""; var isIE = true; var isDebug = true;
  document.write("<div id='divTrans' class='RTBtransparent'></div>");
  function GetFrame(childId) {
    RTB_Frame = document.frames[childId.concat('_editor')];
  }
  function HideAllResponsibility(imgID) {
    if (imgID.parentNode.parentNode.nextSibling.style.display == 'none') {
      imgID.parentNode.parentNode.nextSibling.style.display = '';
      imgID.src = 'Images/minus.gif';
    }
    else {
      imgID.parentNode.parentNode.nextSibling.style.display = 'none';
      imgID.src = 'Images/plus.gif';
    }
  }
  function Maximise(MaximisechildId, ImgID) {
    try {
      var divTrans = document.getElementById('divTrans');
      var img1 = document.getElementById(MaximisechildId);
      RTBtbl = img1.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode;
      RTBtb2 = img1.parentNode.parentNode.parentNode.parentNode.parentNode;
      var x10 = parseInt(img1.style.height.replace('px', ''));
      if (RTBtb2.height < x10) {
        img1.style.height = RTBtb2.height + 'px';
        img1.style.width = RTBtb2.width + 'px';
        RTBtbl.style.position = 'relative';
        RTBtbl.style.top = 0;
        RTBtbl.style.left = 0;
        RTBtbl.style.zIndex = 0;
        divTrans.style.display = 'none';
        divTrans.style.width = 0;
        divTrans.style.height = 0;
        divTrans.style.zIndex = 0;
        ImgID.alt = 'Maximise';
      }
      else {
        var ScrollTop = document.body.scrollTop;
        if (ScrollTop == 0) {
          if (window.pageYOffset)
            ScrollTop = window.pageYOffset;
          else
            ScrollTop = (document.body.parentElement) ? document.body.parentElement.scrollTop : 0;
        }
        var ScrollLeft = document.body.scrollLeft;
        if (ScrollLeft == 0) {
          if (window.pageXOffset)
            ScrollLeft = window.pageYOffset;
          else
            ScrollLeft = (document.body.parentElement) ? document.body.parentElement.scrollLeft : 0;
        }

        RTBtbl.style.position = 'absolute';
        RTBtbl.style.top = ScrollTop + 5;
        RTBtbl.style.left = 10;
        img1.style.height = (window.screen.availHeight - 215) + 'px';
        img1.style.width = (window.screen.availWidth - 50) + 'px';
        RTBtbl.style.zIndex = 100;
        divTrans.style.display = '';
        divTrans.style.width = ((window.screen.availWidth + ScrollLeft) - 21) + 'px';
        divTrans.style.height = ((window.screen.availHeight + ScrollTop) + 500) + 'px';
        divTrans.style.zIndex = 90;
        ImgID.alt = 'Minimise';
      }
      var editdoc = img1.contentWindow.document;
      var editorRange = editdoc.body.createTextRange();
      var curRange = editdoc.selection.createRange();

      if (curRange.length == null && !editorRange.inRange(curRange)) {
        editorRange.collapse();
        editorRange.select();
        curRange = editorRange;
      }
    } catch (e) { if (isDebug) { alert(e.description); } }
  }
  function Over_Class(thisID) {
    if (thisID.className == 'RTBbutton') {
      thisID.className = 'RTBbuttonOver';
    }
  }
  function Out_Class(thisID) {
    if (thisID.className == 'RTBbuttonOver') {
      thisID.className = 'RTBbutton';
    }
  }
  function Select_Class(thisID) {
    if (thisID.className == 'RTBbuttonDown') {
      thisID.className = 'RTBbutton';
    } else {
      thisID.className = 'RTBbuttonDown';
    }
  }
  function EditorMode(mode, childId, x) {
    if (document.readyState != 'complete') {
      setTimeout(function() { EditorMode(mode, childId) }, 25);
      return;
    }
    GetFrame(childId);
    showLoading();
    editor_obj = document.all[childId.concat('_editor')];
    var TextEdit = '<textarea ID="' + childId + '_editor" style="width:' + editor_obj.style.width + '; height:' + editor_obj.style.height + '; margin-top: -1px; margin-bottom: -1px;"></textarea>';
    var RichEdit = '<iframe ID="' + childId + '_editor" class="frame" style="width:' + editor_obj.style.width + '; height:' + editor_obj.style.height + ';margin-top: -1px; margin-bottom: -1px;border: 1px solid #CCCCCC;"></iframe>';

    switch (mode) {
      case 'HTML':
        isHTMLMode = true;
        var editdoc = editor_obj.contentWindow.document;
        var contents = editdoc.body.createTextRange().htmlText;
        editor_obj.outerHTML = TextEdit;
        editor_obj = document.all[childId + "_editor"];
        editor_obj.value = contents;
        editor_updateToolbar(childId, "disable");
        editor_focus(editor_obj);
        break;
      default:
        isHTMLMode = false;
        var editdoc = editor_obj.value;
        var html = "";
        html += '<' + 'html><' + 'head></' + 'head><' + 'body contenteditable="true" topmargin=1 leftmargin=1>'
                  + editor_obj.value
                  + '</' + 'body><' + '/html>\n';

        editor_obj.outerHTML = RichEdit;
        editor_obj = document.all[childId + "_editor"];
        var editdoc = document.all[childId.concat('_editor')].contentWindow.document;
        editdoc.open();
        editdoc.write(html);
        editdoc.close();
        editor_updateToolbar(childId, "enable");
        editor_focus(editor_obj);
        break;
    }
    HideLoading();
  }
  function editor_updateToolbar(childId, action) {
    if (isHTMLMode) {
      document.getElementById(childId.concat("_toolbar1")).style.display = 'none';
      document.getElementById(childId.concat("_toolbar2")).style.display = 'none';
    } else {
      document.getElementById(childId.concat("_toolbar1")).style.display = '';
      document.getElementById(childId.concat("_toolbar2")).style.display = '';
    }
  }
  function editor_focus(editor_obj) {
    try {
      if (editor_obj.tagName.toLowerCase() == 'textarea') {
        var myfunc = function() { editor_obj.focus(); };
        setTimeout(myfunc, 100);
      }
      else {
        var editdoc = editor_obj.contentWindow.document;
        var editorRange = editdoc.body.createTextRange();
        var curRange = editdoc.selection.createRange();

        if (curRange.length == null && !editorRange.inRange(curRange)) {
          editorRange.collapse();
          editorRange.select();
          curRange = editorRange;
        }
      }
    } catch (e) { if (isDebug) { alert(e.description); } }
  }
  function setDesignMode(childId) {
    GetFrame(childId)
    try {
      RTB_Frame.document.designMode = 'on';
      editor_obj = document.all[childId.concat('_editor')];
      var HTMLText = childId.concat('_HTMLText');
      var html = "";
      html += '<' + 'html><' + 'head></' + 'head><' + 'body contenteditable="true" topmargin=1 leftmargin=1 style="font-family:Arial; font-size:12px">'
                  + document.getElementById(HTMLText).value
                  + '</' + 'body></' + 'html>\n';
      var editdoc = document.all[childId.concat('_editor')].contentWindow.document;
      editdoc.open();
      editdoc.write(html);
      editdoc.close();
    } catch (e) { if (isDebug) { alert(e.description); } }
  }

  function textCommand(command, childId, opt) {
    if (isHTMLMode) {
      alert("Formatting happens only in Normal mode");
      return;
    }
    GetFrame(childId);
    RTB_Frame.focus();

    try {
      switch (command) {
        case "EditTable":
          EditTable();
          break;
        case "InsertTableWindow":
          InsertTableWindow();
          break;
        case "DeleteTableColumn":
          DeleteTableColumn();
          break;
        case "DeleteTableRow":
          DeleteTableRow();
          break; case "EditTable":
          EditTable();
          break;
        case "InsertTableRowBefore":
          InsertTableRowBefore();
          break;
        case "InsertTableColumnBefore":
          InsertTableColumnBefore();
          break;
        case "InsertImage":
          InsertImage();
          break;
        case "InsertTable":
          InsertTable(3, 3, 100, '%', 'left', 3, 0, 1);
          break;
        case "InserTime":
          var doc = RTB_Frame.document;
          var span = doc.createElement("span");
          span.innerHTML = " ravikuamr ";
          InsertElement(span);
          break;
        case "InserDate":
          var doc = RTB_Frame.document;
          var span = doc.createElement("span");
          span.innerHTML = " ravikuamr ";
          InsertElement(span);
          break;
        case "link":
          RTB_Frame.document.execCommand('createlink', 1);
          // CreateLink();
          break;
        case "formatBlock":
          formatBlock(opt);
          break;
        default:
          RTB_Frame.document.execCommand(command, "", opt);
          RTB_Frame.focus();
          break;
      }
    } catch (e) { if (isDebug) { alert(e.description); } }
  }
  function formatBlock(FBValue) {
    var fb = this.GetNearest(FBValue);
    if (fb) {
    } else {
      var sel = this.GetSelection();
      range = sel.createRange();
    }
    if (fb == null) {
      RTB_Frame.document.execCommand('RemoveFormat');
      var header = RTB_Frame.document.createElement(FBValue);
      header.innerHTML = range.text;
      range.pasteHTML(header.outerHTML);
    }
  }
  function WordCount(childId) {
    /*    var countTextBox = childId + '_lblCharacters';
    GetFrame(childId);
    try {
    var textEntered = RTB_Frame.document.body.innerText;
    document.getElementById(countTextBox).innerText = textEntered.length;
    } catch (e) { }*/
  }

  function fillTxtId(childId) {
    var x = childId.id;
    childID = x.replace('_editor', '');
    WordCount(childID);
    var HTMLText = childID.concat('_HTMLText');
    GetFrame(childID);
    try {
      document.getElementById(HTMLText).value = RTB_Frame.document.body.innerHTML;
    } catch (e) { }
  }
  function InsertTableColumnBefore() {
    this.InsertTableColumn(false);
  }
  function InsertTableColumnAfter() {
    this.InsertTableColumn(true);
  }
  function InsertTableColumn(after) {
    var td = this.GetNearest("td");
    if (!td) {
      return;
    }
    var rows = td.parentNode.parentNode.rows;
    var index = td.cellIndex;
    for (var i = rows.length; --i >= 0; ) {
      var tr = rows[i];
      var otd = RTB_Frame.document.createElement("td");
      otd.innerHTML = (isIE) ? "" : "<br />";

      //if last column and insert column after is select append child
      if (index == tr.cells.length - 1 && after) {
        tr.appendChild(otd);
      } else {
        var ref = tr.cells[index + ((after) ? 1 : 0)]; // 0 
        tr.insertBefore(otd, ref);
      }
    }
  }
  function InsertTableRowBefore() {
    this.InsertTableRow(false);
  }
  function InsertTableRowAfter() {
    this.InsertTableRow(true);
  }
  function InsertTableRow(after) {
    var tr = this.GetNearest("tr");
    if (!tr) return;
    var otr = tr.cloneNode(true);
    if (otr.hasChildNodes()) { for (i = 0; i < otr.childNodes.length; i++) { otr.childNodes[i].innerHTML = ''; } }
    tr.parentNode.insertBefore(otr, ((after) ? tr.nextSibling : tr));
  }
  function DeleteTableColumn() {
    var td = this.GetNearest("td");
    if (!td) {
      return;
    }
    var index = td.cellIndex;
    if (td.parentNode.cells.length == 1) {
      return;
    }
    this.SelectNextNode(td);
    var rows = td.parentNode.parentNode.rows;
    for (var i = rows.length; --i >= 0; ) {
      var tr = rows[i];
      tr.removeChild(tr.cells[index]);
    }
  }
  function DeleteTableRow() {
    var tr = this.GetNearest("tr");
    if (!tr) {
      return;
    }
    var par = tr.parentNode;
    if (par.rows.length == 1) {
      return;
    }
    this.SelectNextNode(tr);
    par.removeChild(tr);
  }
  function InsertElement(el) {
    var sel = this.GetSelection();
    var range = this.CreateRange(sel);

    if (isIE) {
      range.pasteHTML(el.outerHTML);
    } else {
      this.InsertNodeAtSelection(el);
    }
  }
  function GetNearest(tagName) {
    var ancestors = this.GetAllAncestors();
    var ret = null;
    tagName = ("" + tagName).toLowerCase();
    for (var i = 0; i < ancestors.length; i++) {
      var el = ancestors[i];
      if (el) {
        if (el.tagName.toLowerCase() == tagName) {
          ret = el;
          break;
        }
      }
    }
    return ret;
  }
  function GetAllAncestors() {
    var p = this.GetParentElement();
    var a = [];
    while (p && (p.nodeType == 1) && (p.tagName.toLowerCase() != 'body')) {
      a.push(p);
      p = p.parentNode;
    }
    a.push(RTB_Frame.document.body);
    return a;
  }
  function GetParentElement() {
    var sel = this.GetSelection();
    var range = this.CreateRange(sel);
    if (isIE) {
      switch (sel.type) {
        case "Text":
        case "None":
          return range.parentElement();
        case "Control":
          return range.item(0);
        default:
          return RTB_Frame.document.body;
      }
    } else try {
      var p = range.commonAncestorContainer;
      if (!range.collapsed && range.startContainer == range.endContainer &&
      range.startOffset - range.endOffset <= 1 && range.startContainer.hasChildNodes())
        p = range.startContainer.childNodes[range.startOffset];

      while (p.nodeType == 3) {
        p = p.parentNode;
      }
      return p;
    } catch (e) {
      return null;
    }
  }
  function GetSelection() {
    if (isIE) {
      return RTB_Frame.document.selection;
    } else {
      return RTB_Frame.getSelection();
    }
  }
  function CreateRange(sel) {
    if (isIE) {
      return sel.createRange();
    } else {
      if (typeof sel != "undefined") {
        try {
          return sel.getRangeAt(0);
        } catch (e) {
          return RTB_Frame.document.createRange();
        }
      } else {
        return RTB_Frame.document.createRange();
      }
    }
  }
  function CreateLink() {
    var link = this.GetNearest('a');
    var url = '';
    if (link) {
      var url = link.getAttribute('temp_href');
      if (!url) url = link.getAttribute('href');
    } else {
      var sel = this.GetSelection();
      var text = '';
      if (isIE) {
        text = sel.createRange().text;
      } else {
        text = new String(sel);
      }

      if (text == '') {
        alert('Please select some text');
        return;
      }
    }
    url = prompt('Enter a URL:', (url != '') ? url : 'http://');

    if (url != null) {
      if (!link) {
        var tempUrl = 'http://tempuri.org/tempuri.html';
        RTB_Frame.document.execCommand('createlink', null, tempUrl);
        var links = RTB_Frame.document.getElementsByTagName('a');
        for (var i = 0; i < links.length; i++) {
          if (links[i].href == tempUrl) {
            link = links[i];
            break;
          }
        }
      }
      link.href = url;
      link.setAttribute('temp_href', url);
    }
  }
  function GetSelection() {
    return RTB_Frame.document.selection;
  }
  function InsertTable(cols, rows, width, widthUnit, align, cellpadding, cellspacing, border) {
    RTB_Frame.focus();
    var sel = this.GetSelection();
    var range = this.CreateRange(sel);

    var doc = RTB_Frame.document;
    var table = doc.createElement("table");
    table.style.width = width + widthUnit;
    //table.align = align;
    table.border = border;
    table.cellSpacing = cellspacing;
    table.cellPadding = cellpadding;
    table.setAttribute('bordercolorlight', '#000000');
    table.setAttribute('bordercolordark', '#FFFFFF');

    var tbody = doc.createElement("tbody");
    table.appendChild(tbody);

    for (var i = 0; i < rows; ++i) {
      var tr = doc.createElement("tr");
      tbody.appendChild(tr);
      for (var j = 0; j < cols; ++j) {
        var td = doc.createElement("td");
        tr.appendChild(td);
        if (!isIE) td.appendChild(doc.createElement("br"));
      }
    }

    if (isIE) {
      range.pasteHTML(doc.createElement("br").outerHTML);
      range.pasteHTML(table.outerHTML);
      range.pasteHTML(doc.createElement("br").outerHTML);

    } else {
      this.InsertNodeAtSelection(table);
    }
    return true;
  }

  function SelectNextNode(el) {
    var node = el.nextSibling;
    while (node && node.nodeType != 1) {
      node = node.nextSibling;
    }
    if (!node) {
      node = el.previousSibling;
      while (node && node.nodeType != 1) {
        node = node.previousSibling;
      }
    }
    if (!node) {
      node = el.parentNode;
    }
    this.SelectNodeContents(node);
  }
  function SelectNodeContents(node, pos) {
    var range;
    var collapsed = (typeof pos != "undefined");
    if (isIE) {
      range = RTB_Frame.document.body.createTextRange();
      range.moveToElementText(node);
      (collapsed) && range.collapse(pos);
      range.select();
    } else {
      var sel = this.GetSelection();
      range = RTB_Frame.document.createRange();
      range.selectNodeContents(node);
      (collapsed) && range.collapse(pos);
      sel.removeAllRanges();
      sel.addRange(range);
    }
  }
  function InsertTableWindow() {
    this.LaunchTableWindow(false);
  }
  function EditTable() {
    this.LaunchTableWindow(true);
  }
  function LaunchTableWindow(editing) {

    var tableWin = window.open("", "tableWin", "width=400,height=200");
    if (tableWin) {
      tableWin.focus();
    } else {
      alert("Please turn off your PopUp blocking software");
      return;
    }

    tableWin.document.body.innerHTML = '';
    tableWin.document.open();
    tableWin.document.write(FTB_TablePopUpHtml);
    tableWin.document.close();

    launchParameters = new Object();
    launchParameters['ftb'] = this;
    launchParameters['table'] = (editing) ? this.GetNearest("table") : null;
    tableWin.launchParameters = launchParameters;
    tableWin.load();
  }

  var FTB_TablePopUpHtml = new String("ravi");
</script>
Bold Italic Underline Left Align Center Align Right Align Justify Ordered List Unordered List SubScript SuperScript De-Indent In-Indent Insert Line Clear Format
Link InsertTable InsertTableColumnBefore InsertTableRowBefore DeleteTableColumn DeleteTableRow  
Maximise

JS: Padding

<script type="text/javascript" type="text/javascript">
  var STR_PAD_LEFT = 1;
  var STR_PAD_RIGHT = 2;
  var STR_PAD_BOTH = 3;

  function pad(str, len, pad, dir) {
    if (typeof (len) == "undefined") { var len = 0; }
    if (typeof (pad) == "undefined") { var pad = ' '; }
    if (typeof (dir) == "undefined") { var dir = STR_PAD_RIGHT; }

    if (len + 1 >= str.length) {
      switch (dir) {
        case STR_PAD_LEFT:
          str = Array(len + 1 - str.length).join(pad) + str;
          break;
          
        case STR_PAD_BOTH:
          var right = Math.ceil((padlen = len - str.length) / 2);
          var left = padlen - right;
          str = Array(left + 1).join(pad) + str + Array(right + 1).join(pad);
          break;

        default:
          str = str + Array(len + 1 - str.length).join(pad);
          break;
      } // switch
    }
    return str;
  }
  alert(pad('ravi', 20, ' d ', STR_PAD_RIGHT));
</script>

Javascript: Cookies

<script type="text/javascript" type="javascript">
   function CookieHandler() {

     this.setCookie = function(name, value, seconds) {
       if (typeof (seconds) != 'undefined') {
         var date = new Date();
         date.setTime(date.getTime() + (seconds * 1000));
         var expires = "; expires=" + date.toGMTString();
       }
       else {
         var expires = "";
       }
       document.cookie = name + "=" + value + expires + "; path=/";
     }

     this.getCookie = function(name) {
       name = name + "=";
       var carray = document.cookie.split(';');

       for (var i = 0; i < carray.length; i++) {
         var c = carray[i];
         while (c.charAt(0) == ' ') c = c.substring(1, c.length);
         if (c.indexOf(name) == 0) return c.substring(name.length, c.length);
       }
       return null;
     }

     this.deleteCookie = function(name) {
       this.setCookie(name, "", -1);
     }
   }
   var Cookies = new CookieHandler();
   var counter = Cookies.getCookie('counter'); // get cookie 'name'
   if (typeof (counter) == 'undefined') counter = 0;
   Cookies.setCookie('counter', ++counter, 365 * 60 * 60); // set cookie 'counter' for 1 year
</script>

Clear Fix

Without clearfix

With clearfix

Email Validation

<script type="text/javascript" type="javascript">
function validEmail(email){      
 var emailReg = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
 return emailReg.test(email); 
}
</script>

Java script trimming

<script type="text/javascript" type="javascript">
function StringTrim(s) {
    var m = s.match(/^\s*(\S+(\s+\S+)*)\s*$/);
    return (m == null) ? "" : m[1];
}
</script>

Scrollable HTML table

Name Surename Age
John Smith 30
John Smith 31
John Smith 32
John Smith 33
John Smith 34
John Smith 35
John Smith 36
John Smith 37
Name Surename Age

Show / Hide

Progress Bar 1



Show / Hide