Friday, April 22, 2005

Different way to Populate Dialog Box and Get Value of Dialog Box in ASP.NET

Different way to call dialog box from code behind in ASP.NET


  1. btnOpen.Attributes.Add("onclick", "alert('GOT IT?');")

  1. btnDelete.Attributes.Add("onclick", "if(confirm('Are you sure to delete?')){}else{return false}")

Suppose, you want to open an another web page as a dialog box, then what will you do? Here is the same coding with little difference.

  1. btnOpenNewWindow.Attributes.Add("onclick", "window.open ('child.aspx')")


If you want to open page in new window with some condition


  1. btnOpenNewWindow.Attributes.Add("onclick",

"window.showModalDialog('child.aspx', null,'status:no;

dialogWidth:370px;dialogHeight:220px;

dialogHide:true;help:no;scroll:no');")


You can write this code in ASPX page also


  1. <input type="submit" name="btnOpen1" value="Open 1" id="btnOpen1" onclick="alert('GOT IT?');" style="width:64px;Z-INDEX: 101; LEFT: 8px; POSITION: absolute; TOP: 8px" />

  1. <input type="submit" name="btnDelete" value="Delete" id="btnDelete" onclick="if(confirm('Are you sure to delete?')){}else{return false}" style="width:64px;Z-INDEX: 102; LEFT: 8px; POSITION: absolute; TOP: 48px" />

  1. <input type="submit" name="btnOpen2" value="Open 2" id="btnOpen2" onclick="window.open('child.aspx')" style="width:64px;Z-INDEX: 103; LEFT: 8px; POSITION: absolute; TOP: 88px" />

  1. <input type="submit" name="btnOpen3" value="Open 3" id="btnOpen3" onclick="window.showModalDialog('child.aspx',null,'status:no;dialogWidth:370px;

dialogHeight:220px;dialogHide:true;help:no;scroll:no');

" style="width:64px;Z-INDEX: 104; LEFT: 8px; POSITION: absolute; TOP: 128px" />


Returning value from the dialog box


OK! What about returning any value from the dialog box? Suppose you have opened a dialog box for some purpose and you want that it returns some value to the parent web form.

For returning any thing to the parent window from the child dialog box, javascript provides one attribute of the window object, that is window.returnValue to understand its working.


Let's create a small web project with two web forms named :

parent.aspx

child.aspx

Parent web form will have one textbox and a button. Look at the following code of the parent web form.

parent.aspx


<body MS_POSITIONING="GridLayout">

<form id="Form1" method="post" runat="server">

<asp:TextBox id="txtValue" style="Z-INDEX: 101; LEFT: 16px; POSITION: absolute; TOP: 24px" runat="server"></asp:TextBox>

<asp:Button id="btnOpen" style="Z-INDEX: 102; LEFT: 176px; POSITION: absolute; TOP: 24px" runat="server" Text="Open..."></asp:Button>

</form>

</body>

parent.aspx.vb

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

btnOpen.Attributes.Add("onclick", "var strReturn; strReturn=window.showModalDialog('child2.aspx',null,'status:no;dialogWidth:370px;dialogHeight:220px;

dialogHide:true;help:no;scroll:no');

if (strReturn != null) document.getElementById('txtValue').value=strReturn;")

End Sub

And, child web form which will have a textbox and two buttons.


Look at the following code of the child page.

child2.aspx


<body MS_POSITIONING="GridLayout">

<form id="Form1" method="post" runat="server">

<asp:TextBox id="txtValue"

style="Z-INDEX: 101; LEFT: 16px; POSITION: absolute; TOP: 24px" runat="server"></asp:TextBox>

<asp:Button id="btnOK"

style="Z-INDEX: 103; LEFT: 48px; POSITION: absolute; TOP: 56px" runat="server" Text="Ok" Width="56px"></asp:Button>

<asp:Button id="btnCancel"

style="Z-INDEX: 102; LEFT: 112px; POSITION: absolute; TOP: 56px" runat="server" Text="Cancel"></asp:Button>

</form>

</body>


child2.aspx.vb


Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

btnOK.Attributes.Add("onclick", "window.returnValue = document.getElementById('txtValue').value; window.close();")

btnCancel.Attributes.Add("onclick", "window.close();")

End Sub


the purpose of this small module is, that when user click on the button of the parent form, it will open child.apsx file in the dialog box. In the child form user will enter some value in the textbox and it he click on the Ok button it will return that value to the parent form. With that it will update the textbox of the parent form. And of course, if user click on the Cancel button, it will simply close the child dialog box without doing anything.


In all of the above case, there is nothing to do with the ASP.NET. All of things are actually handle by the javascript. See the javascript code of the child web form.


<input name="txtValue" type="text" id="txtValue" style="Z-INDEX: 101; LEFT: 16px; POSITION: absolute; TOP: 24px" />

<input type="submit" name="btnOK" value="Ok" id="btnOK" onclick="window.returnValue = document.getElementById('txtValue').value; window.close();" style="width:56px;Z-INDEX: 103; LEFT: 48px; POSITION: absolute; TOP: 56px" />

<input type="submit" name="btnCancel" value="Cancel" id="btnCancel" onclick="window.close();" style="Z-INDEX: 102; LEFT: 112px; POSITION: absolute; TOP: 56px" />

Yes, you can use response object to popup a alert message also. Here is the code for that:

Private Sub btnOpen5_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOpen5.Click

Dim strScript As String = ""

strScript = "<script>"

strScript = strScript & "alert('Simple alter message!!!!');"

strScript = strScript & "</script>"

Response.Write(strScript)

End Sub


above code, simply pop an alert message to the user.

If you want to display some variable message in the alert message then it you can do that with slight change.

Private Sub btnOpen6_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOpen6.Click

Dim strScript As String = ""

Dim intSum As Integer

strScript = "<script>"

intSum = 344 + 233

strScript = strScript & "alert('SUM : " & intSum & "');"

strScript = strScript & "</script>"

Response.Write(strScript)

End Sub


there will be a drawback again, in using above method to pop alert box, you will notice that if you have tried the above code. We will talk about it later on.

Same thing can be done by registering javascript code to the browser. Following is the example, will do the same thing, but here we will register the javascript to the page.

Private Sub btnOpen7_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOpen7.Click

Dim strScript As String = ""

strScript = "<script>"

strScript = strScript & "alert('Simple alter message!!!!');"

strScript = strScript & "</script>"

Page.RegisterClientScriptBlock("ClientScript", strScript)

End Sub


Now about that drawback, yes, you are right, it wash screen of the parent window when it pop the alert message or dialog box. The all controls of the parent window will remain hidden unless you close the alert box or dialog box.

Why?? Its because, the javascript that is generated is attached to the top of the html page. You can easily understand this you see the generated html code of the page. Look at the following:

This Code is generated using Response object :

<script>alert('Simple alter message!!!!');</script>

<HTML>

<HEAD>

<title>WebForm1</title>

</HEAD>

<body MS_POSITIONING="GridLayout">

</body>

</HTML>

Or the Code generated using RegisterClientScriptBlock method :

<HTML>

<HEAD>

<title>WebForm1</title>

</HEAD>

<body MS_POSITIONING="GridLayout">

<form name="Form1" method="post" action="MainForm.aspx" id="Form1">

<script>alert('Simple alter message!!!!');</script>

</form>

</body>

</HTML>


In the last case the code is generated just below the form tag, but still its above the all html and web controls. when the alert message or any modal dialog box is opened the focus will gone to the dialog box and rest of the controls will not visible as they are not rendered. When user close the alert message or ant modal dialog box, thereafter the rest of the control rendered.

So, What is I want to display modal dialog box with the populated controls in the parent forms. Its possible if you can put your generated javascript below the controls tags in the form. Is it possible?? Of course yes. Here is the technique. Use RegisterStartupScript method to put your javascript to the page. Look at the following code of display an alert message and a modal dialog box. If you look at the generated html code then you will easily understand the working behind this technique. Here is the generated html code.


<HTML>

<HEAD>

<title>WebForm1</title>

</HEAD>

<body MS_POSITIONING="GridLayout">

<form name="Form1" method="post" action="MainForm.aspx" id="Form1">

<script>alert('Simple alter message!!!!');</script>

</form>

</body>

</HTML>


Generated javascript is attached just above the closing tag of the form element and below of all html or web controls tag. So, first all of the html controls will render and there after the modal dialog box or modal dialog box will open.

Tuesday, April 19, 2005

How to prevent sending emails without subject in Outlook

How to prevent sending emails without subject in Outlook

1. Open your outlook
2. Press Alt+F11. This will open the Visual Basic editor
3. On the Left Pane, one can see "Project1", expand this, you can see “Microsoft Office Outlook Objects”, expand this. Now one can see the “ThisOutLookSession”. (If you are not seeing "Project1", press Ctrl+R or View-> Project Explorer).
4. Double - Click on “ThisOutLookSession”.
5. Copy and Paste the following code in the right pane.(Code Pane)

Private Sub Application_ItemSend(ByVal Item As Object, Cancel As Boolean)
Dim strSubject As String
strSubject = Item.Subject

If Len(strSubject) = 0 Then
Prompt$ = "Subject is Empty !!!, Are you sure? you want to send the Mail?"
If MsgBox(Prompt$, vbOKCancel + vbQuestion + vbSystemModal + vbMsgBoxSetForeground, "Check for Subject:-") = vbCancel Then
Cancel = True
End If
End If

End Sub

6. Now close the VB editor. From now on , this macro will make sure you do not make the mistake of sending an email without subject

Note:
You need to enable macros in the outlook for this code snippet to work.

Thursday, March 24, 2005

Programmatically Load User Controls

Programmatically Load User Controls

 

 This sample consists of 3 pages:

  • default.aspx -- the standard ASP.NET page
  • cbDefault.vb -- the codebehind page for default.aspx
  • ucHeading.ascx -- a usercontrol with a property called page heading.

default.aspx simply has a panel object as a placeholder, and references the code behind file.

default.aspx

<%@ Page EnableSessionState="false" explicit="true" strict="true" MaintainState="false" inherits="cbDefault" src="cbDefault.vb"%>
<html>
<head>
<title></title>
</head>
<body bgcolor="#FFFFFF" >
<asp:panel id="pnlHeading" runat="server" />
</body>
</html>

 

 

ucHeading has a single property called PageHeading. PageHeading is a string that is used to display the heading of the page for the web surfer.

ucHeading.ascx

<script runat="server">
Private _pageheading as String = ""
Public Property PageHeading As String
Get
    Return _pageheading
End Get
Set
    _pageheading = value
End Set
End Property
</script>
<h1><%=_pageheading%></h1>

 

cdDefault.vb is the code behind file for default.aspx. It contains the meat of this demo. The logic of cbDefault.vb is:

  • Load the UserControl
  • Get the type of UserControl
  • Get access to the property "PageHeader"
  • Set the property "PageHeader"
  • Add the UserControl to the panel object on default.aspx

cbDefault.vb

Option Strict On
Option Explicit On

Imports System
Imports System.Reflection
Imports System.Web.UI
Imports System.Web.UI.WebControls

Public Class cbDefault : Inherits Page
Public pnlHeading as Panel

Public Sub Page_Load(Src As Object, E As EventArgs)
  ' Load the control
  Dim myUC as UserControl = LoadControl("ucHeading.ascx")

  ' Set the Usercontrol Type
  Dim ucType as Type = myUC.GetType()

  ' Get access to the property
  Dim ucPageHeadingProperty as PropertyInfo = ucType.GetProperty("PageHeading")

  ' Set the property
  ucPageHeadingProperty.SetValue(myUC,"Access a Usercontrol from Code Behind",Nothing)

  pnlHeading.Controls.Add ( myUC )
End Sub

End Class

 

 

 



Have a Nice Day
 
Ritesh Kumar Kesharwani
Software Professional
Cell  :  011-91-9845657636

__________________________________________________
Do You Yahoo!?
Tired of spam? Yahoo! Mail has the best spam protection around
http://mail.yahoo.com

Monday, March 21, 2005

How To Read/Write Into XML

Private sub WriteXML()

Try

Dim doc As

XmlDocument

doc = New XmlDocument()

'Chk whether xml files is exists or not

Try

doc.Load(Server.MapPath("book.xml"))

Catch ex As

Exception

doc.LoadXml("<Books></Books>")

End

Try

Dim node As XmlElement, pNode As

XmlElement

pNode = doc.CreateElement("Book")

doc.FirstChild.AppendChild(pNode)

node = doc.CreateElement("Title")

node.InnerText = txtTitle.Text

pNode.AppendChild(node)

node = doc.CreateElement("Author")

node.InnerText = txtAuthor.Text

pNode.AppendChild(node)

node = doc.CreateElement("Year")

node.InnerText = txtYear.Text

pNode.AppendChild(node)

'save the output to a file

doc.Save(Server.MapPath("book.xml"))

ReadXml()

Catch Eh As

Exception

Response.Write("Exception: {0}" & Eh.ToString())

End

Try

End

Sub

Private Sub

ReadXml()

Try

Dim myDataSet As New

DataSet()

myDataSet.ReadXml(Server.MapPath("book.xml"))

dgBooksPretty.DataSource = myDataSet

dgBooksPretty.DataBind()

Catch ex As

Exception

Response.Write("Exception: {0}" & ex.ToString())

End

Try

Note: some more way of Reading / Writting XML using C#.net

http://riteshk.blogspot.com/2007/07/how-to-readwrite-xml-string-in.html

Monday, February 07, 2005

How to Attach and Detach Database for SQL Server.

sp_attach_single_file_db
Attaches a database having only one data file to the current server.

Syntax
sp_attach_single_file_db [ @dbname = ] 'dbname'
, [ @physname = ] 'physical_name'

Arguments
[@dbname =] 'dbname'

Is the name of the database to be attached to the server. dbname is sysname, with a default of NULL.

[@physname =] 'phsyical_name'

Is the physical name, including path, of the database file. physical_name is nvarchar(260), with a default of NULL.

Return Code Values
0 (success) or 1 (failure)

Result Sets
None

Remarks
When sp_attach_single_file_db attaches the database to the server, it builds a new log file and performs additional cleanup work to remove replication from the newly attached database.

Use sp_attach_single_file_db only on databases that were previously detached from the server using an explicit sp_detach_db operation.

Use sp_attach_single_file_db only on databases that have a single log file. Do not use this stored procedure on databases that have multiple log files.

Permissions
Only members of the sysadmin and dbcreator fixed server roles can execute this procedure.

Examples
This example detaches pubs and then attaches one file from pubs to the current server.

EXEC sp_detach_db @dbname = 'pubs'
EXEC sp_attach_single_file_db @dbname = 'pubs',
@physname = 'c:\Program Files\Microsoft SQL Server\MSSQL\Data\pubs.mdf'

Friday, February 04, 2005

Generate SQL Insert statements using Store Procedure


--EXEC sp_generate_inserts TABELNAME 
==========================================================
SET NOCOUNT ON 
PRINT 'Checking for the existence of this procedure' 
IF (SELECT OBJECT_ID('sp_generate_inserts','P')) IS NOT NULL 
BEGIN 
PRINT 'Procedure already exists. So, dropping it' 
DROP PROC sp_generate_inserts 
END 
GO 
CREATE PROC sp_generate_inserts 
(
@table_name varchar(776), 
@target_table varchar(776) = NULL, 
@include_column_list bit = 1, 
@from varchar(800) = NULL, 
@include_timestamp bit = 0, 
@debug_mode bit = 0, 
@owner varchar(64) = NULL, 
@ommit_images bit = 0, 
@ommit_identity bit = 0, 
@top int = NULL, 
@cols_to_include varchar(8000) = NULL, 
@cols_to_exclude varchar(8000) = NULL 

AS 
BEGIN
SET NOCOUNT ON 
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 specify both',16,1) 
RETURN -1 
END 
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 
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 
END 
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 
END 
IF @owner IS NULL 
BEGIN 
IF (OBJECT_ID(@table_name,'U') IS NULL) 
BEGIN 
RAISERROR('User table 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.' 
RETURN -1 
END 
END 
ELSE 
BEGIN 
IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = @table_name AND TABLE_TYPE = 'BASE TABLE' AND TABLE_SCHEMA = @owner) 
BEGIN 
RAISERROR('User table 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.' 
RETURN -1 --Failure. Reason: There is no user table 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), 
@IDN varchar(128) 
--Variable Initialization 
SET @IDN = '' 
SET @Column_ID = 0 
SET @Column_Name = 0 
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 
IF @owner IS NULL 
BEGIN 
SELECT @Column_ID = MIN(ORDINAL_POSITION) 
FROM INFORMATION_SCHEMA.COLUMNS (NOLOCK) 
WHERE TABLE_NAME = @table_name 
END 
ELSE 
BEGIN 
SELECT @Column_ID = MIN(ORDINAL_POSITION) 
FROM INFORMATION_SCHEMA.COLUMNS (NOLOCK) 
WHERE TABLE_NAME = @table_name AND 
TABLE_SCHEMA = @owner 
END 
--Loop through all the columns of the table, to get the column names and their data types 
WHILE @Column_ID IS NOT NULL 
BEGIN 
IF @owner IS NULL 
BEGIN 
SELECT @Column_Name = '[' + COLUMN_NAME + ']', 
@Data_Type = DATA_TYPE 
FROM INFORMATION_SCHEMA.COLUMNS (NOLOCK) 
WHERE ORDINAL_POSITION = @Column_ID AND 
TABLE_NAME = @table_name 
END 
ELSE 
BEGIN 
SELECT @Column_Name = '[' + COLUMN_NAME + ']', 
@Data_Type = DATA_TYPE 
FROM INFORMATION_SCHEMA.COLUMNS (NOLOCK) 
WHERE ORDINAL_POSITION = @Column_ID AND 
TABLE_NAME = @table_name AND 
TABLE_SCHEMA = @owner 
END 
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(@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 
--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 
--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 + '),'''''''',''''''''''''),''nvkon©'')' + ' + ''''''''' 
WHEN @Data_Type IN ('datetime','smalldatetime') 
THEN 
''''''''' + '+'COALESCE(RTRIM(CONVERT(char,' + @Column_Name + ',109)),''nvkon©'')' + ' + ''''''''' 
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,' + @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 
IF @owner IS NULL 
BEGIN 
SELECT @Column_ID = MIN(ORDINAL_POSITION) 
FROM INFORMATION_SCHEMA.COLUMNS (NOLOCK) 
WHERE TABLE_NAME = @table_name AND 
ORDINAL_POSITION > @Column_ID 
END 
ELSE 
BEGIN 
SELECT @Column_ID = MIN(ORDINAL_POSITION) 
FROM INFORMATION_SCHEMA.COLUMNS (NOLOCK) 
WHERE TABLE_NAME = @table_name AND 
ORDINAL_POSITION > @Column_ID AND 
TABLE_SCHEMA = @owner 
END 
--Loop ends here! 
END 
--To get rid of the extra characters that got concatened 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) 
--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(''+ ' + 'REPLACE(' + @Actual_Values + ',''''''nvkon©'''''',''NULL'')' + '+'')''' + ' ' + 
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(''+ ' + 'REPLACE(' + @Actual_Values + ',''''''nvkon©'''''',''NULL'')' + '+'')''' + ' ' + 
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 '--Problems/Suggestions? Contact Vyas @ answer_me@hotmail.com' 
PRINT '--http://vyaskn.tripod.com' 
PRINT '' 
PRINT 'SET NOCOUNT ON' 
--Determining whether to print IDENTITY_INSERT or not 
IF (@IDN <> '') 
BEGIN 
PRINT 'SET IDENTITY_INSERT ' + '[' + RTRIM(COALESCE(@target_table,@table_name)) + ']' + ' ON' 
PRINT 'GO' 
END 
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''' 
IF (@IDN <> '') 
BEGIN 
PRINT 'SET IDENTITY_INSERT ' + '[' + RTRIM(COALESCE(@target_table,@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 
SET NOCOUNT OFF 
GO 
PRINT 'Done' 

Friday, January 28, 2005

Friday, January 21, 2005

Recoding in DOTNET / Special Copy_ Past

If you want to do same task in multiple page the Recording is the best option
given by the DOTNET Tool.

For Start the Recording press Ctrl +Shift + R and write the code
that will record one by one whatever you typed.
now stop the recording (Ctrl +Shift + R)
and go to next page and again Play the recording (Ctrl +shift + P)
that will do the same step what you have done in previous page.
Note : Remember Mouse event Will not work while recording

Copy / Past

If you want to Copy multiple text and want to past one by one
use the Ctrl + Shift + V

Wednesday, January 12, 2005

( CustomValidation) Validating with a Custom Function for ASP.NET Server Controls

Validating with a Custom Function for ASP.NET Server Controls

If the existing validation controls do not suit your needs, you can define a custom server-side validation function and call it using the CustomValidator control. You can also add client-side validation for a quick check before the form is submitted by writing a function in ECMAScript (JScript) that duplicates the logic of the server-side method.
You should perform a server-side validation even if you use a client-side check. Server-side validation helps prevent users from bypassing validation by disabling or changing the client script.
Security Note By default, the Web Forms page automatically validates that malicious users are not attempting to send script or HTML elements to your application. As long as this validation is enabled, you do not need to explicitly check for script or HTML elements in user input. For more information, see Scripting Exploits.

Server-Side Validation

You define server-side validation by writing code in the control's ServerValidate event handler that checks the user's input. You hook up the event handler by setting the OnServerValidate attribute of the control. The string from the input control to validate can be accessed by using the Value property of the ServerValidateEventArgs object passed into the event handler as a parameter. The result of the validation is then stored in the IsValid property of the ServerValidateEventArgs object.

To validate on the server using a custom function

1. Add a CustomValidator control to the page and set the following properties:

Property Description

ControlToValidate : The ID of the control you are validating.

ErrorMessage, Text, Display : Properties that specify the text and location of the error or errors that will display if the validation fails. For details, see Controlling Validation Error Message Display for ASP.NET Server Controls.

2. Create a server-based event handler for the control's ServerValidate event. This event is called to perform the validation. The method has a signature such as the following:

Protected Sub CustomValidator1_ServerValidate(ByVal _
source As System.Object, ByVal args As _
System.Web.UI.WebControls.ServerValidateEventArgs) _
Handles CustomValidator1.ServerValidate


// C#
protected void ValidationFunctionName(object source, ServerValidateEventArgs args)

The source parameter is a reference to the custom validation control raising this event. The property args.Value will contain the user input to validate, and args.IsValid should be set to true if the value is valid, false otherwise.
The following example shows how you can create custom validation. The event handler checks whether the user's entry is eight characters long or longer.

' Visual Basic
Protected Sub TextValidate(ByVal source As System.Object, _
ByVal args As System.Web.UI.WebControls.ServerValidateEventArgs) _
Handles CustomValidator1.ServerValidate
args.IsValid = (args.Value.Length >= 8)
End Sub


// C#
protected void TextValidate(object source, ServerValidateEventArgs args)
{
args.IsValid = (args.Value.Length >= 8);
}
3. Add the OnServerValidate attribute to the validator in HTML view to indicate the name of the validation function.

OnServerValidate="TextValidate"
ControlToValidate="TextBox1"
ErrorMessage="Text must be 8 or more characters.">

4. Add a test in your Web Forms code to check for validity. For details, see Testing Validity Programmatically for ASP.NET Server Controls.

Client-Side Validation

You can also create client-side custom validation. To do so, you specify a function name for the control's ClientValidationFunction property, and create a function in client script that duplicates the logic of the server-side method.

To create custom validation logic on the client

1. Create a validation function on the client side in ECMAScript (JavaScript, JScript).

The following example illustrates custom client-side validation. An excerpt from the page shows a Textbox control referenced by a CustomValidator control. The validation control calls a function called validateLength to make sure that the user has entered at least eight characters into the Textbox control.



function validateLength(oSrc, args)

{ args.IsValid = (args.Value.length >= 8);}

asp:CustomValidator id="CustomValidator1" runat=server
ControlToValidate = "text1"
ErrorMessage = "You must enter 8 Chr"
ClientValidationFunction="validateLength"
asp:CustomValidator


2. Add a test in your Web Forms code to check for validity. For details, see Testing Validity Programmatically for ASP.NET Server Controls.