Navigation

Search

Categories

On this page

Using Explicit Parameters with the ObjectDataSource control
Handling Errors At the Page-Level
Comparing Records from Two Tables
RegEx for validating email addresses with RegularExpressionValidator
Update records from two tables
Conditional GridView Cell Formatting
Displaying all files in a directory and in a datatable
Using XMLHttpRequest
Clearing a Form In ASP.NET
Google AJAX Search API
Javascript/AJAX Library

Archive

Blogroll

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

RSS 2.0 | Atom 1.0 | CDF

Send mail to the author(s) E-mail

Total Posts: 378
This Year: 6
This Month: 1
This Week: 0
Comments: 17

Sign In
Pick a theme:

# Wednesday, July 25, 2007
Wednesday, July 25, 2007 8:02:49 PM (GMT Daylight Time, UTC+01:00) ( ASP.NET )

The order of the parameters does not matter - just the names of the parameters.  You can specify the type of a parameter using the Type property - Int32, Decimal and DateTime.

Here is a demo of this code.

*** Movies.vb ***

Imports System.Web.Configuration

Public Class Movies

Private ReadOnly _conString As String

Public Sub UpdateMovie(ByVal id As Integer, ByVal title As String, &_
ByVal director As String, ByVal dateReleased As DateTime)
' Create Command
Dim con As New SqlConnection(_conString)
Dim cmd As New SqlCommand()
cmd.Connection = con
cmd.CommandText = "UPDATE Movies SET Title=@Title,Director=@Director,DateReleased=@DateReleased WHERE Id=@Id"

' Add parameters
cmd.Parameters.AddWithValue("@Title", title)
cmd.Parameters.AddWithValue("@Director", director)
cmd.Parameters.AddWithValue("@DateReleased", dateReleased)
cmd.Parameters.AddWithValue("@Id", id)

' Execute command
Using con
con.Open()
cmd.ExecuteNonQuery()
End Using
End Sub

Public Function GetMovies() As SqlDataReader
' Create Connection
Dim con As New SqlConnection(_conString)

' Create Command
Dim cmd As SqlCommand = New SqlCommand()
cmd.Connection = con
cmd.CommandText = "SELECT Id,Title,Director,DateReleased FROM Movies"

' Return DataReader
con.Open()
Return cmd.ExecuteReader(CommandBehavior.CloseConnection)
End Function

Public Sub New()
_conString = WebConfigurationManager.ConnectionStrings("MyDatabase").ConnectionString
End Sub

End Class


*** ExplicitShowMovies.aspx ***

<%@ Page Language="VB" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
<title>Show Movies</title>
</head>
<body>
<form id="form1" runat="server">
<div>

<asp:GridView
id="grdMovies"
DataSourceID="srcMovies"
DataKeyNames="Id"
AutoGenerateEditButton="true"
Runat="server" />

<asp:ObjectDataSource
id="srcMovies"
TypeName="Movies"
SelectMethod="GetMovies"
UpdateMethod="UpdateMovie"
Runat="server">
<UpdateParameters>
<asp:Parameter Name="title" />
<asp:Parameter Name="director" />
<asp:Parameter Name="dateReleased" Type="DateTime" />
<asp:Parameter Name="id" Type="Int32" />
</UpdateParameters>
</asp:ObjectDataSource>

</div>
</form>
</body>
</html>

Comments [0] | | # 
Wednesday, July 25, 2007 2:30:11 AM (GMT Daylight Time, UTC+01:00) ( ASP.NET )

I just learned about the Page_Error sub which you can use to capture the error that occurred and redirect the user to a page which displays a user-friendly message that an error occurred.  The Page_Error event of the ASP.NET Page object is raised any time an unhandled error occurs in a page.

ASP.NET provides you with the ability to redirect the user to another page when an error occurs. To use this feature, set the ErrorPage property of the Page object to the URL of the page you want the user to see. You can add querystring parameters to the URL to pass specific error messages to the page. For instance, in the code snippets shown next, we've added three querystring parameters to the URL of an error message page: PageHeader, Message1, and Message2. PageHeader is set to the message "Error Occurred." Message1 is set to the message in the lastError exception. This will be the message from the last exception thrown. Message2 is a message we've added to say where the error was processed.

Example:

Protected Sub Page_Error(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Error
            Dim lastError As Exception

            'get the last error that occurred
            lastError = Server.GetLastError( )

            'do any logging, notifications, etc. here

            'set the URL of the page that will display the error and
            'include querystring parameters to allow the page to display
            'what happened
            Page.ErrorPage = "error_page.aspx" &_
                 "?PageHeader=Error Occurred" &_
                 "&Message1=" &lastError.Message &_
                 "&Message2=" &_
                 "This error was processed at the page level"

End Sub

Comments [0] | | # 
# Monday, July 23, 2007
Monday, July 23, 2007 4:09:52 PM (GMT Daylight Time, UTC+01:00) ( SQL )

I picked this up from SQLTeam.com and it's come in handy a few times.

CREATE PROCEDURE CompareTables(

@table1 varchar(100), 
@table2 Varchar(100),
@T1ColumnList varchar(1000),
@T2ColumnList varchar(1000) = '')
AS

-- Table1, Table2 are the tables or views to compare.
-- T1ColumnList is the list of columns to compare, from table1.
-- Just list them comma-separated, like in a GROUP BY clause.
-- If T2ColumnList is not specified, it is assumed to be the same
-- as T1ColumnList. Otherwise, list the columns of Table2 in
-- the same order as the columns in table1 that you wish to compare.
--
-- The result is all records from either table that do NOT match
-- the other table, along with which table the record is from.

declare @SQL varchar(8000);

IF @t2ColumnList = '' SET @T2ColumnList = @T1ColumnList

set @SQL = 'SELECT ''' + @table1 + ''' AS TableName, ' + @t1ColumnList +
' FROM ' + @Table1 + ' UNION ALL SELECT ''' + @table2 + ''' As TableName, ' +
@t2ColumnList + ' FROM ' + @Table2

set @SQL = 'SELECT Max(TableName) as TableName, ' + @t1ColumnList +
' FROM (' + @SQL + ') A GROUP BY ' + @t1ColumnList +
' HAVING COUNT(*) = 1'

exec ( @SQL)

Comments [0] | | # 
# Thursday, July 19, 2007
Thursday, July 19, 2007 7:34:44 PM (GMT Daylight Time, UTC+01:00) ( ASP.NET )

ASP.NET comes with a RegularExpressionValidator which provides for a lot of flexbility when validating user input.  This is the best regular expression for emails I've seen. It tends to error on the side of accepting bad emails rather then rejecting good ones.

 

^([a-zA-Z0-9_'+*$%\^&!\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9:]{2,4})+$

 

Here is an example:

E-mail: <asp:textbox id="textbox1" runat="server"/>
<asp:RegularExpressionValidator id="valRegEx" runat="server"
ControlToValidate="textbox1"
ValidationExpression="^([a-zA-Z0-9_'+*$%\^&!\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9:]{2,4})+$"
ErrorMessage="* Your entry is not a valid e-mail address."
display="dynamic">*
</asp:RegularExpressionValidator>

Comments [0] | | # 
# Wednesday, July 11, 2007
Wednesday, July 11, 2007 9:17:55 PM (GMT Daylight Time, UTC+01:00) ( SQL )

UPDATE table1
SET col1 = t2.col1
FROM table1 AS t1
JOIN table2 AS t2
ON t1.col2 = t2.col2

Comments [0] | | # 
# Monday, July 09, 2007
Monday, July 09, 2007 2:31:48 PM (GMT Daylight Time, UTC+01:00) ( ASP.NET )

This code sample shows how to either show or make invisible, a checkbox in each row of the Gridview, along with making text conditional, based on certain criteria. In this case, if the Postal code starts with a non-numeric character, we change it to "Alt Text", and we set the Visible property of the checkbox in that row to "False"

<%@ Import Namespace="System.Drawing" %>
<script language="VB" Runat="server">
Sub DataCheck(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
Dim chkExp as CheckBox
If e.Row.RowType = DataControlRowType.DataRow Then
Dim sCode as String=e.Row.Cells(7).text
If Not isNumeric(sCode.Substring(1,1)) Then
e.Row.Cells(7).text="<i style='color:red'>(Alt Text)</i>"
        chkExp= CType(e.row.FindControl("ck1"), Checkbox)
        chkExp.Visible="False"
End If
End If
End Sub    
</script>
<html>
<head runat="server">
    <title>Conditional GridView Cell Formatting</title>
</head>
<body>
<form id="form1" Runat="server">
<asp:GridView OnRowDataBound="DataCheck" AutoGenerateColumns="False"
    DataSourceID="SqlDataSource1" ID="GridView2" runat="Server">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="ck1" runat="server"></asp:CheckBox>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="FirstName" HeaderText="First" />
<asp:BoundField DataField="LastName" HeaderText="Last" />
<asp:BoundField DataField="Title" HeaderText="Title" />
<asp:BoundField DataField="Address" HeaderText="Address" />
<asp:BoundField DataField="City" HeaderText="City" />
<asp:BoundField DataField="Region" HeaderText="Region" />
<asp:BoundField DataField="PostalCode" HeaderText="PostalCode" />
<asp:BoundField DataField="country" HeaderText="country" />
</Columns>
<HeaderStyle BackColor="Blue" Font-Bold="True" ForeColor="White" />
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>"
SelectCommand="Select FirstName, LastName, Title, Address, City, Region, PostalCode, country from Employees">
</asp:SqlDataSource>
        </form>
    </body>
</html>

Comments [0] | | # 
Monday, July 09, 2007 2:27:20 PM (GMT Daylight Time, UTC+01:00) ( ASP.NET )

This sample shows how to create a datatable manually, adding files from a directory (using System.IO), and then binding the datatable to a Gridview

<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.Data" %>
<script language="VB" Runat="server">
Dim dt As DataTable
Dim dr As DataRow
    Sub Page_Load(Source as Object, E as EventArgs)
dt = GetFiles()
gvFiles.DataSource = dt
gvFiles.DataBind()
    End Sub
Public Function GetFiles() As DataTable
Dim strFilePath = Server.MapPath("\test\")
Dim DirInfo As New DirectoryInfo(strFilePath)
Dim Files As FileInfo() = DirInfo.GetFiles()

Dim myTable As New DataTable
myTable.Columns.Add("File Name", Type.GetType("System.String"))
myTable.Columns.Add("Last Write Time", Type.GetType("System.String"))
Dim i As Integer
For i = 0 To Files.Length - 1
Dim Filename As String = Files(i).Name
Dim sWrite As String = Files(i).LastWriteTime
Dim myrow As DataRow
' create new row
myrow = myTable.NewRow
' add files/write times into cells
myrow("File Name") = Filename
myrow("Last Write Time") = sWrite
myTable.Rows.Add(myrow)
Next
Return myTable
End Function    
</script>
<html>
    <head runat="server">        
        <title>Displaying all files in a directory and in a datatable</title>
    </head>
    <body>
<asp:GridView ID="gvFiles" runat="server" Width="432px">
</asp:GridView>
        </form>
    </body>
</html>

Comments [0] | | # 
# Tuesday, July 03, 2007
Tuesday, July 03, 2007 6:48:50 PM (GMT Daylight Time, UTC+01:00) ( Javascript/AJAX )

A coworker passed along this link from IBM which provides a nice series of tutorials on AJAX. The example below is a classic example of how to use the XMLHTTPRequest object while checking for different browser types and then using the server's response for something.

<script language="javascript" type="text/javascript">
var request = false;
try {
request = new XMLHttpRequest();
} catch (trymicrosoft) {
try {
request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (othermicrosoft) {
try {
request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (failed) {
request = false;
}
}
}

if (!request)
alert("Error initializing XMLHttpRequest!");

function getCustomerInfo() {
var phone = document.getElementById("phone").value;
var url = "/cgi-local/lookupCustomer.php?phone=" + escape(phone);
request.open("GET", url, true);
request.onreadystatechange = updatePage;
request.send(null);
}

function updatePage() {
if (request.readyState == 4) {
if (request.status == 200) {
var response = request.responseText.split("|");
document.getElementById("order").value = response[0];
document.getElementById("address").innerHTML = response[1].replace(/\n/g, "<br />");
} else if (request.status == 404) {
alert ("Requested URL is not found.");
} else if (request.status == 403) {
alert("Access denied.");
} else
alert("status is " + request.status);
}
}

</script>

<body>
<p><img src="breakneck-logo_4c.gif" alt="Break Neck Pizza" /></p>
<form action="POST">
<p>Enter your phone number:
<input type="text" size="14" name="phone" id="phone"
onChange="getCustomerInfo();" />
</p>
<p>Your order will be delivered to:</p>
<div id="address"></div>
<p>Type your order in here:</p>
<p><textarea name="order" rows="6" cols="50" id="order"></textarea></p>
<p><input type="submit" value="Order Pizza" id="submit" /></p>
</form>
</body>

Comments [0] | | # 
Tuesday, July 03, 2007 2:07:15 PM (GMT Daylight Time, UTC+01:00) ( ASP.NET )

Clearing a form of all entries or values is a common task in HTML but seemed to be a bit more challenging in ASP.NET.  It seemed the only way to do this was by posting the page back to itself using server.transfer("page.aspx")

I just stumbled across this method new to ASP.NET 2.0 using OnClientClick and it works great.

<asp:Button ID="btnReset" CssClass="smalltext" OnClientClick="Form1.reset();return false;" runat="server" Text="Clear Form" />

HTML version:

<input type="reset" value="Clear Form" name="Reset" onclick="ResetControls(this.form)">

Comments [0] | | # 
# Monday, July 02, 2007
Monday, July 02, 2007 5:48:54 PM (GMT Daylight Time, UTC+01:00) ( Javascript/AJAX )

Google makes a cool API that utilizes AJAX to which allows developers to add a Web or local search to their sites relatively easily. 

I created an example of it here: http://www.stonecoastwebdesign.com/search/example.htm

Comments [0] | | # 
Monday, July 02, 2007 3:37:01 PM (GMT Daylight Time, UTC+01:00) ( Javascript/AJAX )

A co-worker passed this along to me which looks pretty cool

http://extjs.com/

Comments [0] | | #