Error Trapping in ASP.NET

A new feature of ASP.Net is the Try/Catch block. If nothing else, it makes trapping errors much more elegant, and cleaner looking. Whenever your app encounters an error, it pretty much crashes, with a pretty ugly output for the end user. Sometimes, the user can understand the resulting page – - sometimes, not. Here, we will attempt to give you an Overview of the Try/Catch block, in order to guard against possible code errors.

Naturally, this isn’t a way for you to blow off your total development, but it is a way for you to catch unexpected errors without crashing the actual execution of the page. You’ll still want to check for logical, error-producing situations, and code around them, depending on your particular application’s circumstances, as well as using ASP.Net Validation Controls.

The Try block, of course, starts with ‘TRY’. Then, it ends with ‘END TRY’. Inside this block, you will ‘try’ or attempt to execute your code. Inside this block, you’ll want to add a ‘CATCH’ section. Here, this basically tells your page what to do when it encounters an error. An example of this would be:

Try ' do your code execution here Catch ex as Exception lblError.Text = "An error has occured/" lblError.Text+= ex.Message End Try

Continues…

Creating a Hit Counter in ASP.NET

Remember the ASP Classic Hit Counter? You’d create a text file for each page you wanted to record that page’s hits. To start with, you’d just type in a zero to begin the counting process. Then, you’d put this code in your ASP document:

Set fs = CreateObject("Scripting.FileSystemObject") CounterPage = Server.MapPath ("/counters/YourASPDoc.cnt") Set a = fs.OpenTextFile(CounterPage) ct = CLng(a.ReadLine) ct = ct + 1 a.Close Set a = fs.CreateTextFile(CounterPage, True) a.WriteLine (ct) a.Close Response.Write ct

Continues…

Sorting/Filtering Fixed DataSet Results in ASP.NET

OK – here’s the scenario – - you have a stored procedure in place already that returns data in a certain order and you have no time to get a new stored procedure in place to give you what you need and your boss needs it NOW!. What you need is a ‘sub-set’ of these results from the stored procedure – - not the whole thing. So, technically, what you need to do is to somehow, sort, or filter the results this procedure returns to you.

Luckily for you, there is a class with a couple of great properties that helps you do this. Let’s start with a simple scenario from ‘DataSet 101′ – Query/Create and Fill DataSet/Bind to DataGrid for Display:

Dim strConn as string = "server=(local);uid=yourUID;pwd=yourPWD;database=northwind" Dim MySQL as string = "spGetCustomerList" Dim MyConn as New SQLConnection(strConn) ' (OleDbConnection for Access and other OleDb databases) Dim ds as DataSet=New DataSet() Dim da as New SQLDataAdapter() Dim Cmd as New SQLCommand(MySQL,MyConn) ' (OleDbCommand for Access and other OleDb databases) Cmd.CommandType=CommandType.StoredProcedure MyConn.Open da.SelectCommand=cmd da.Fill(ds, "Customers") myDataGrid.Datasource=ds.Tables("Customers").DefaultView myDataGrid.DataBind()

Since you can’t manipulate the SQL query yourself, at first, it would seem that you are ‘up the creek’, so to speak. However, about this time, along comes the ‘DataView’ class, to save the day. The solution is to assign the results returned to a DataView, and using a couple of its built in properties (Sort and RowFilter) to manipulate the data the way you want.
Continues…

The Basics of Using SQL in ASP.NET

As you can see from the title, what we’re exploring here are the basics of SQL – Structured Query Language. Naturally, this won’t, then, be an exhaustive tutorial on SQL – that would require a book – and there are many already out there.

With SQL, we can query databases. It doesn’t matter whether the database is SQL Server, MS Access, MySQL, Oracle or any other. It just requires that the database is sql compliant, which, naturally, most commercially available databases these days, are.

The recommended methd for querying databases, in order to stop injection attacks, is parameterized queries….we won’t go into that in this tutorial, since a tutorial on that subject already exists.

The 4 basic types of queries we’re going to explore are:
Select
Insert
Update
Delete
Along with these 4 types, we’ll address a couple of clause types (Where and Order by)

Select Statement
I’d say that arguably, the most common use of SQL on the web is the SELECT statement. With the SELECT statement, we select data from the database and return the results to the user. The two most common forms are what I call the pure Select statement, and the qualified Select Statement. Here’s an example of a Select Statement in it’s purest, or most simple form:

Select FirstName, LastName, Phone from TableName

This query will return all the Firstname, LastName and Phone number for each record in the database, no matter how many records are in the database.

The other Select Statement I listed is the ‘qualified’ Select Statement. An example of this would use a ‘Where’ clause, like this:

Select FirstName, LastName, Phone from TableName’ Where LastName=’Jones’

As you probably expected, this will only return the FirstName, LastName and Phone for those records where the LastName is ‘Jones’.

Where clauses can contain multiple filtering sections also, using either ‘OR’ or ‘AND’. An example would be

Select FirstName, LastName, Phone from TableName’ Where LastName=’Jones’ OR LastName=’Smith’ OR FirstName=’Jim’

Another example would be:

Select FirstName, LastName, Phone from TableName’ Where LastName=’Jones’ AND FirstName=’Jim’

Insert Statement
Here, we would take user input and INSERT it into the table. We’ve all filled out forms with TextBoxes, RadioButtons, Checkboxes, etc.
Continues…

Querystring Results and SQL Statements in ASP.NET

The basis of using querystrings really hasn’t changed from the days of Classic ASP to ASP.Net, however the way you access them, in ASP.Net, has changed a little. This tutorial will show a simple way to use querystrings, receive them in an ASP.Net page, and then use the received results in an SQL statement.

Let’s start out with a scenario:
We have two pages: Page1.aspx (‘sending’ page) and Page2.aspx (‘receiving’ page). In the ‘sending’ page, we’ll create a querystring, which is assigned to a link to the second page. In this scenario, we’re assigning a querystring that includes a last name, so that, on the ‘receiving’ page , we can create a query based on whatever name is used in the querystring. In this case, we’ll be searching the fictitional ‘Customers’ database for the name passed in the querystring.

There are too many possibilities, in the ‘sending’ page, on how to arrive at the variable, so we won’t go into a scenario concerning that particular item. So we’ll just start out by creating the link on the ‘sending’ page, which will include the querystring :
<a href=”Page2.aspx?lname=Wilson”>Go to Page2.aspx, and search for Customer Details</a>.
Here, you create the name of the querystring any way you want – - we’re using ‘lname’

Next, in Page2.aspx, within the SCRIPT tags, but OUTSIDE of any subroutine or function, you will need to dimension a variable, to which the querystring will be assigned in the Page_Load event:
Dim sLName as String

Continues…

Customizing HTML output in ASP.NET

In This Article:

  • Specifying Display Properties in the DataGrid and DataList
  • Customizing Data-Binding Output in Templates
  • On the Web

We have used the data Web controls a numberof times in code examples in the past two chapters. However, theappearance of the output has left a lot to be desired. Fortunately,making the DataGrid and DataList output more visually pleasing is quitesimple, even for artistically challenged developers like myself!

As we will see in this chapter, both theDataGrid and DataList expose a number of properties that makespecifying these details a breeze. Additionally, we’ll look at howeditors like Visual Studio .NET and the Web Matrix Project makespecifying the appearance of the DataGrid and DataList as easy clickinga few buttons. (Note that the Repeater control does not contain anysort of stylistic properties; the developer is responsible forspecifying any aesthetic properties directly in the HTML markup of theRepeater’s templates.)

Continues…

Beginners Guide to COM in ASP.NET

As in all of the tutorials here, once you see what needs to occur, in order to use COM objects in your ASP.Net code, you will see that it’s not all that complicated. There are, however, a few things that do need to be put in place before it will happen.

The first item to be addressed is a property that needs to be added to the Page Directive:

ASPCompat=”True”

In case you don’t know about the page directive, you really ought to look into it because it’s very useful in many ways. It’s added at the beginning of your page, like this:

<%@ Page Language=”VB” Debug=”True” AspCompat=”True” Trace=”True” %>

The next thing that’s needed is quite important. To do this, the identity needs to be set to the ASPNet user account on the web server. In Win2K, go to Component Services, click on the main entry in the tree, where your COM objects are located, and click ‘Properties‘. Next, click the ‘Identity Tab‘. Here, under the line, ‘This application will run under the following account’, you will see two Account choices:

  1. Interactive user – the current logged on user
  2. This user

Since the ASPNet user is the one who needs access to the COM objects, here, you can choose ‘This user‘, and Browse to the ASPNet user account – then click ‘OK’.

Keep in mind, if you upgrade the Framework to a newer version, AFTER you follow these steps, you might need to go back into the Windows User accounts and reset the password (usually blank) for the ASPNet user account. The System password and the password entered in the ‘Identity Tab‘ must be the same. You will know whether or not you need to do this fairly easily. You will start getting identity errors, asking you to check the username/password.

There is also a slight difference in declaring and instantiating COM objects between Classic ASP and ASP.Net. In Classic ASP, you would merely add this to your code:

Dim MyObj

In ASP.Net, you must include the type, so you use ‘Object’:

Dim MyObj as Object

Continues…

Creating a Login/Email/Activation Page in ASP.NET

Many of you have gone to websites where you needed to create a ‘membership’ form, for future logging in, which in turn sent an email to you, with a link back to the site, which ‘activated’ your account/membership for that webste. This tutorial will attempt to lay the groundwork for the basics of that particular scenario.

First off – there needs to be a database with a table that gathers the information from the form you will design. In this case, we’ll just add a few fields – uid, pwd, fullname, email and verify, calling the table ‘Members’. You may download the SQL Server table creation script here. If you want the MS Access database, you can download it here. Other than the fields mentioned, we are adding an identity field (autonumber for MS Access), called ID and, we’re setting the verify field to have a default value of ‘NO’.

Next, we need a form to gather the data and insert it into the table. The code for that is here:

<form Name="form1" runat="server">
<table>
	<tr>
		<td align="right">uid</td>
		<td> <asp:textbox id="frmuid" runat="server" /></td>
	</tr>
	<tr>
		<td align="right">pwd</td>
		<td> <asp:textbox id="frmpwd" runat="server" /></td>
	</tr>
	<tr>
		<td align="right">fullname</td>
		<td> <asp:textbox id="frmfullname" runat="server" /></td>
	</tr>
	<tr>
		<td align="right">email</td>
		<td> <asp:textbox id="frmemail" runat="server" /></td>
	</tr>

		<td align="right">
		<asp:button
		id="button1"
		onclick="doInsert"
		Text="Submit" runat="server" />
		</td>
	</tr>
</table>
</form>

Continues…

The Beginner's Guide to an ArrayList in ASP.NET

An ArrayList, at first glance might be kind of hard to get your head around, if you’re a beginner programmer, or coming from the Classic ASP/HTML world. But, at its base, it’s just a list of items in memory, and can be treated as an object, but it’s not a control, like a ListBox. It has properties and methods, and the count of the items is Zero-based. For instance, let’s say we have an arraylist consisting of 5 colors (Blue, Red, Green, Orange and Pink). Since ArrayLists are Zero-based, the numbering of the items starts with zero and ends with 4.

To create an ArrayList, first, we must dimension it:

Dim MyArrayList as ArrayList

Then, to create a space for it in memory:

MyArrayList=New Arraylist

Next, we must populate the ArrayList. This can be done any one of many ways. It can be done manually:

MyArrayList.add("Blue")
MyArrayList.add("Red")
MyArrayList.add("Green")

or, we can populate it from a database table, using a DataReader, like so:

While objDR.Read()
	MyArrayList.add(objDR("FieldName"))
End While

Once it’s populated, then, we can ‘hook it up’ with a server control, like a ListBox or DropDownList:

DropDownList.datasource=MyArrayList DropDownList.databind

There are many properties and methods, and I won’t even begin to go into them all since this, like the title says, is the ‘Beginner’s ArrayList’, but if you go to the Quickstart Tutorials, you will find a very useful tool near the bottom of the TOC on the left, under Sample Applications, called ‘A Class Browser Application’. Look under the System.Collections Class to find it’s many properties and methods.

I will go into a few, just to show you a few common things that can be done with the ArrayList. As you probably have figured, from the tutorial so far, there is definitely a Count property. And, as logically as it sounds, it can be accessed like this:

Label1.text = MyArrayList.Count

We can iterate through the list, parsing or manipulating the items, but since it’s zero based, if we use a For/Next loop, we must do it like this:

for x=0 to MyArrayList.Count-1
	'manipulate the items
next

We can use this to put the items of an ArrayList into a string:

Dim sNewString as String
for x=0 to MyArrayList.Count-1
	'We step through the arraylist, one at a time
	'Here we create the string, adding each item, followed by a comma
	sNewString+=MyArrayList(x).ToString & ","
next

We can sort the ArrayList, in ascending order, easily like this:

MyArrayList.Sort

And, conversely, we can sort them descending like this:

MyArrayList.Reverse

As you’ve seen earlier, to add an item, we just call the ‘Add’ Method, and it also has a ‘Remove’ method to - you guessed it – Remove an item from the ArrayList. Also, it has an Item property, which uses the numbered position in the ArrayList as a parameter, and can be accessed like this:

Label1.text=MyArraList.Item(3)

That’s pretty much where I’m going to leave it for now, with the exception of a couple of links to Code Samples on this site, concerning ArrayLists:

Configuring a Trusted SQL Srvr Connection in ASP.NET

Following article demonstrates the steps involved in configuring a trusted SQL Server connection to access data using ADO.NET – Written by Shanthanu

Pre-requisites

1. A local instance of SQL Server has to be setup on the same machine as the IIS

2. Optionally, during setup, the SQL server must be configured to be accessible thro’ Windows Authentication Mode. (It doesn’t matter if you haven’t done so)

Step 1: Creating a Trusted SQL Server Connection

For convenience this discussion assumes that an Administrator account is going to be assigned as the trusted SQL Server Connection. (Please read the note at the end of this paper)

sql.server.user.set-1 1.     Open the SQL Server Enterprise Manager from the Windows Start Menu

2.     Navigate to the Security Node under (local)(Windows NT) node that represents the local instance of SQL Server 2000 installed on your computer.

3.     Right-Click the LogIns Node and ClickNew Login.

4. In the SQL Server Login Properties dialog for New Login, click the Browse button against the text box marked Name

untitled 1.     In the next dialog that opens up, select the computer from which the user account has to be chosen from the Drop down list captionedList Names From:

Continues…