ASP.NET (35) SQL (25) JAVASCRIPT (24) HTML (14) STYLE SHEET (6) ASP (4) SCRIPT (1)

Search me out HERE!!

Take backup of Single Table in SQL Server and MySql

Using below query, you can take backup of table in SQL Server:
SELECT * INTO [NewTableName] FROM [BackupTable]

Using below query, you can take backup of table in MySql:
CREATE TABLE [NewTableName] SELECT * FROM [BackupTable]

Getting selected value from RadioButtonList in Javascript


Consider below ASP.Net RadioButtonList control:
<asp:RadioButtonList ID="rbList" runat="Server">
   <asp:ListItem Text="Kapil" Value="1" Selected="True">
   <asp:ListItem Text="Baheti" Value="2">
</asp:RadioButtonList>

You can now get selected radio button value using below javascript:
function GetRadioButtonValue()
{
  var id = <%= rbList.ClientID %>;
  var radio = document.getElementsByName(id);
  for (var i = 0; i < radio.length; i++)
     {
        if (radio[i].checked)
           alert(radio[i].value);
     }
}

Insert multiple rows together in table in SQL Server

You can insert multiple rows together in table in SQL Server using below 3 methods:

CREATE TABLE Test (ID INT, Value VARCHAR(100));

1. INSERT INTO Test (ID, Value) VALUES (1, 'One');
    INSERT INTO Test (ID, Value) VALUES (2, 'Two');
    INSERT INTO Test (ID, Value) VALUES (3, 'Three');

2. INSERT INTO Test (ID, Value)
    SELECT 1, 'One'
    UNION ALL
    SELECT 2, 'Two'
    UNION ALL
    SELECT 3, 'Three';

3. INSERT INTO Test (ID, Value)
    VALUES (1, 'One'), (2, 'Two'), (3, 'Three');

White text in simple text file using ASP.Net with C#

Use below code to write text in simple .txt file using ASP.Net with C#:

System.IO.StreamWriter sw = new System.IO.StreamWriter(Server.MapPath("C:\\test.txt"));
sw.WriteLine("Kapil Baheti");
sw.Close();

Above code will write "Kapil Baheti" in test.txt file. Also if file is not present at destination then it will be created automatically. 

Fix "Validation (): Element xxxxx is not supported" problem in visual studio

We face common issue in visual studio "Validation (): Element xxxxx is not supported" for ASP controls.
To solve this issue follow below steps:

1. Close down Visual Studio 2008 or Visual Studio 2010.

2. Now make sure to show hidden files, folders, and drives. 
    To do so go to Folder Options -> then select the View tab.  

3. Now you need to go toh below path:
   My Computer >> [C:] >> Users >> [username] >> AppData >> Roaming >> Microsoft >> VisualStudio >> 9.0 / 10.0 (For VS 2010)  
   Or
   Users >> Classic .NET AppPool >> AppData >> Roaming >> Microsoft >> VisualStudio >> 9.0 / 10.0 (For VS 2010)  

4. Now delete all items in ReflectedSchemes folder. 

5. Restart visual studio and your problem will be solved.

Jquery - For Each function

.each( function(index, Element) ) :
This is JQuery function used to iterate through each matched element. This function is generally used to iterate through similar elements to apply common functionality.

Check below simple example to understand this function:
This is simple HTML unordered list on page


<ul>
    <li>Kapil</li>
    <li>Baheti</li>
</ul>

Now you can iterate through each <li> using below jquery function:

<script>

$('li').each(function(index) {
    alert(index + ': ' + $(this).text());
});
</script>


Output will be
0: Kapil
1: Baheti

Get list of all files from directory in C#, ASP.Net

Using below code you can list out all files or files with respective extension for given directory in C#:

DirectoryInfo di = new DirectoryInfo("c:/demos");
FileInfo[] rgAllFiles = di.GetFiles();  //Get list of all files.
FileInfo[] rgFiles = di.GetFiles("*.aspx");  //Get list of only .aspx files.

// You can use each file using below iteration
foreach(FileInfo fi in rgAllFiles)
{
  Response.Write(fi.Name);       

Get file name from path using Javascript

Using below javascript function you can get file name from path:

function GetFileName()
{
   var fullPath = 'http://kapilgbaheti.blogspot.in/2012/08/get-file-name-from-path.html';
   var filename = fullPath.replace(/^.*[\\\/]/, '');
   alert(filename);
}

You output will be : get-file-name-from-path.html

Get Screen Width and Screen Height using Javascript

Below is code to get Screen Width and Height using Javascript;

function getScreenInfo()
{
    var w = screen.width;
    var h = screen.height;
    alert("Screen Width :" + w + ", Screen Height:" + h);
}

Note: You cannot get screen width/height in ASP.net server side code, you need to manage it using Javascript.

SQL SERVER: Generate Comma Separated List with SELECT statement

Below example shows, how to get comma separated value from SQL server.

-- Create table
CREATE TABLE #test(field1 VARCHAR(5), field2 VARCHAR(5))


--Lets insert some data in this table:
INSERT INTO #test
SELECT '001','AAA'  UNION ALL
SELECT '001','BBB'   UNION ALL
SELECT '002','CCC'  UNION ALL
SELECT '003','DDD'  UNION ALL
SELECT '004','EEE'    UNION ALL
SELECT '004','FFF'    UNION ALL
SELECT '004','GGG'
 
SELECT field1,
SUBSTRING(
(
  SELECT ( ', ' + field2)
  FROM #test t2
  WHERE t1.Field1 = t2.Field1
  ORDER BY t1.Field1, t2.Field1
  FOR XML PATH('')
), 3, 1000)
FROM #test t1
GROUP BY field1

Output will be:
field1   field2
001     AAA,BBB
002     CCC
003     DDD
004     EEE,FFF,GGG

How to split comma separated string into SQL server.

Below function can be used to split comma seperated string, output will be in fom of table.

-- SELECT * FROM dbo.fn_Split ('1,2,3',',')

CREATE FUNCTION [dbo].[fn_Split]
(
@String nvarchar (4000),
@Delimiter nvarchar (10)
)
RETURNS @ValueTable table (ID [int] IDENTITY (1, 1) NOT NULL,[Value] nvarchar(4000))


BEGIN


DECLARE @NextString nvarchar(4000)
DECLARE @Pos int
DECLARE @NextPos int
DECLARE @CommaCheck nvarchar(1)


--Initialize
SET @NextString = ''
SET @CommaCheck = right(@String,1)


--Check for trailing Comma, if not exists, INSERT
--if (@CommaCheck <> @Delimiter )
SET @String = @String + @Delimiter


--Get position of first Comma
SET @Pos = charindex(@Delimiter,@String)
SET @NextPos = 1


--Loop while there is still a comma in the String of levels
WHILE (@pos <> 0)
BEGIN
  SET  @NextString = substring(@String,1,@Pos - 1)
  INSERT INTO @ValueTable ( [Value]) Values (@NextString)
  SET  @String = substring(@String,@pos +1,len(@String))
  SET  @NextPos = @Pos
  SET  @pos = charindex(@Delimiter,@String)
END


RETURN

END

Get number of days in month from given date in SQL server

Below is example of SQL query which will give number of days in month for given date:

DECLARE @dtDate AS DATETIME = GETDATE()   --This will select current date.
SELECT DAY(DATEADD(MONTH, 1, @dtDate) - DAY(DATEADD(MONTH, 1, @dtDate))) 

Search / find keyword in your entire database(Procedure, Function) in SQL Server

You can use below procedure to search any keyword in your entire database. In output you will get list of procedures and functions in which given keyword is found.

CREATE PROC SP_SEARCH_CODE
(
  @SearchStr VARCHAR(100),
  @RowsReturned INT = NULL OUT
)


AS
BEGIN


SET NOCOUNT ON


SELECT DISTINCT USER_NAME(o.uid) + '.' + OBJECT_NAME(c.id) AS 'Object name',


CASE
WHEN OBJECTPROPERTY(c.id, 'IsReplProc') = 1 THEN 'Replication stored procedure'
WHEN OBJECTPROPERTY(c.id, 'IsExtendedProc') = 1 THEN 'Extended stored procedure'
WHEN OBJECTPROPERTY(c.id, 'IsProcedure') = 1 THEN 'Stored Procedure'
WHEN OBJECTPROPERTY(c.id, 'IsTrigger') = 1 THEN 'Trigger'
WHEN OBJECTPROPERTY(c.id, 'IsTableFunction') = 1 THEN 'Table-valued function'
WHEN OBJECTPROPERTY(c.id, 'IsScalarFunction') = 1 THEN 'Scalar-valued function'
WHEN OBJECTPROPERTY(c.id, 'IsInlineFunction') = 1 THEN 'Inline function'
WHEN OBJECTPROPERTY(c.id, 'IsView') = 1 THEN 'VIEW'
END AS 'Object type',


'EXEC sp_helptext ''' + USER_NAME(o.uid) + '.' + OBJECT_NAME(c.id) + '''' AS 'Run this command to see the object text'
FROM syscomments c
INNER JOIN sysobjects o ON c.id = o.id
WHERE
c.text LIKE '%' + @SearchStr + '%' AND encrypted = 0 AND
(
OBJECTPROPERTY(c.id, 'IsReplProc') = 1 OR
OBJECTPROPERTY(c.id, 'IsExtendedProc') = 1 OR
OBJECTPROPERTY(c.id, 'IsProcedure') = 1 OR
OBJECTPROPERTY(c.id, 'IsTrigger') = 1 OR
OBJECTPROPERTY(c.id, 'IsTableFunction') = 1 OR
OBJECTPROPERTY(c.id, 'IsScalarFunction') = 1 OR
OBJECTPROPERTY(c.id, 'IsInlineFunction') = 1 OR
OBJECTPROPERTY(c.id, 'IsView') = 1
)
ORDER BY 'Object type', 'Object name'


SET @RowsReturned = @@ROWCOUNT


END

Disable Copy Paste Cut options in textbox using javascript in ASP.NET

Below is example to disable COPY, PASTE and CUT option in textbox:

<asp:TextBox ID="TextBox1"runat="server"oncopy="return false" oncut="return false" onpaste="return false" ></asp:TextBox> 

How to convert lowercase to uppercase in SQL Server

Below query is example of converting lowercase into uppercase using SQL query:

SELECT UPPER(ColumnName) FROM TableName

How to request READ RECEIPT in email in ASP.Net

Many email clients such as outlook has a feature that allows you to request a receipt when your email is read by the recipient(s).
It can be achieved in asp.net generated emails using additional header called Disposition-Notification-To
Here is simple code:

MailMessage email = new MailMessage(fromAddress, toAddress);
email.Headers.Add("Disposition-Notification-To", receiptToEmailAddress); //Use email address on which you want receive the receipt

Create PROCEDURE in SQL Server

-- Below is code to create new procedure in SQl server.

CREATE PROCEDURE ProcedureName
    -- Add the parameters for the stored procedure her
    @Param1 Datatype_For_Param1 = ,
    @Param2 Datatype_For_Param2 =
AS
BEGIN
--Here you can write your SQL statement.
END

Get MONTH name from Month number in ASP.NET

You can use below function to get MONTH name from MONTH number in ASP.NET:

DIM intMonth AS INT = 1;   'i.e. for January
MonthName(intMonth);  'Output will be January

Declare CURSOR in SQL SERVER / Syntax for implementing CURSOR

Below is example showing simple use of CURSOR:

-- This cursor will print all Employee name from Employee table

DECLARE cur CURSOR  --Declare Cursor
FOR SELECT EmpName FROM tbl_Employee

OPEN cur
FETCH NEXT FROM cur INTO @EmpName;
 

WHILE @@FETCH_STATUS = 0
BEGIN
    PRINT 'Employee Name:' + @EmpName;

    FETCH NEXT FROM cur INTO @EmpName
END

CLOSE cur;  -- Close Cursor
DEALLOCATE cur;  -- Deallocate

DELETE identical or same or duplicate entries from table in SQL SERVER

You can use below query to delete identical or same or duplicate entries from table:

1) Delete from table:

DELETE T FROM (
SELECT ROW_NUMBER() OVER (ORDER BY Id) AS ID
FROM tbl_Test
WHERE Id='1' ) T
WHERE ID > 1

2) Delete from table having join with other tables

DELETE tbl_Test FROM (
SELECT ROW_NUMBER() OVER (ORDER BY T.Id) AS ID ,T.Id
FROM tbl_Test T
INNER JOIN tbl_Join J on J.Id = T.Id
WHERE T.Id='1' ) R
WHERE R.ID > 1

Difference between jQuery object and DOM element(Javascript Object)

Below given is relation between JQuery object and DOM element (i.e. Javascript object), Using this you can convert JQuery object into javascript object and apply formulas of javascript on it.

Consider Below Div
<div id="foo"></div>

Now below 3 alert will give same Javascript object (On which javascipt function can be performed)
alert($("#divTest")[0]);  //Jquery
alert($("#divTest").get(0));  //Jquery
alert(document.getElementById("divTest"));  //Javascript

Scroll two div/table together (Horizontal and Vertical)

Below is code to scroll 2 div/table together:


< div id="div1" style="width:400px !important; height: 150px !important; overflow: auto; border: 1px solid Black;" onscroll="scrollDiv('div1', 'div2', 1)" >
    < table border="0" cellpadding="0" cellspacing="0" width="500px" >
        < tr >
            < td align="center" >

< br / >ASP.Net< br / >< br / >SQL Server< br / >< br / >JavaScript< br / >< br / >JQuery< br / >< br / >AJAX< br / >< br / >HTML< br / >< br / >CSS< br / >< br / >

            < /td >
            < td align="center" >

< br / >HTML< br / >< br / >PHP< br / >< br / >WCP< br / >< br / >SilverLight< br / >< br / >Jhoomla< br / >< br / >ASP< br / >< br / >StyleSheet< br / >< br / >

            < /td >
        < /tr >
    < /table >
< /div >

< div id="div2" style="width:400px !important; height: 150px !important; overflow: auto; border: 1px solid Black;" onscroll="scrollDiv('div1', 'div2', 2)" >
    < table border="0" cellpadding="0" cellspacing="0" width="500px" >
        < tr >
            < td align="center" >

< br / >ASP.Net< br / >< br / >SQL Server< br / >< br / >JavaScript< br / >< br / >JQuery< br / >< br / >AJAX< br / >< br / >HTML< br / >< br / >CSS< br / >< br / >

            < /td >
            < td align="center" >

 < br / >HTML< br / >< br / >PHP< br / >< br / >WCP< br / >< br / >SilverLight< br / >< br / >Jhoomla< br / >< br / >ASP< br / >< br / >StyleSheet< br / >< br / >

            < /td >
        < /tr >
    < /table >
< /div >
           
< script type="text/javascript" >
    function scrollDiv(divA, divB, divNo) {
        var div1 = $('#' + divA);
        var div2 = $('#' + divB);
        if (!div1 || !div2) return;
        var control = null;
        if (divNo == 1) control = div1;
        else if (divNo == 2) control = div2;
        if (control == null) return;
        else {
            div1.scrollLeft(control.scrollLeft());
            div2.scrollLeft(control.scrollLeft());
            div1.scrollTop(control.scrollTop());
            div2.scrollTop(control.scrollTop());
        }
    }
< /script >

List out last modified procedures and functions in SQL

Use below query to find out last modified stored procedures, functions, views and tables from Sql Server.

SELECT name, create_date, modify_date,type
FROM sys.objects
WHERE type IN ('FN','V','P','U','TF')
AND DATEDIFF(D,modify_date, GETDATE()) < 6
ORDER BY modify_date


Here are different types used in IN clause in WHERE condition:

  • FN – Scalar valued function
  • V – View
  • P – Stored Procedure
  • U – Table
  • TF – Table valued function
DATEDIFF(D,modify_date, GETDATE()) < 6 – It will show the objects modified in last 6 days

Find and Replace in Visual Studio using regular expression

One of the nice feature in all version of visual studio that I would love to use is Find and Replace using regular expression. This feature is very useful while you need to perform any repeating pattern based task. and offcourse it saves a lot time.
Lets take a simple example to understand it. We have list of countries and its code in a excel file or table. We want to create a dropdownlist from it so text field contains Country name and Value field contains Code in it.

The step by step procedure:


Step 1: Select the both columns from excel file an copy it in text file in visual studio. Don’t forget to put cursor at the start.


Step 2: Now click Ctrl+h to open the find replace dialog.  Checkmark the last checkbox 'Use' and select ‘Regular Expression’ from the dropdown. Now we will need to define the regular expression in ‘Find What:’ and ‘Replace with:’ textboxes. You can see them in following screenshot (again i will explain how to define it? and how does it work? in my next post)



Step 3: Click on ‘Replace All’ button on the dialog. and Here is the result we need.

This feature reduces your manual work.