Dynamic Meta Tag Keywords

If you have a database with Dynamic Meta Tag Keywords, just query the database, assign them to a variable (like strKeys) and then, using an ASP.Net Literal Control, you can display them on the page like this:

litMeta.text=”<META NAME=’KEYWORDS’ CONTENT=’” & strKeys & “‘>”

To see a tutorial on the basics of creating dynamic content for a website, check out:
Adding Dynamic Content to Your Pages

Defining Error Displays Globally in ASP.NET

If you have many pages on a site, you may fall into a very easy situation. That situation is that, in each Try/Catch block that you’ve defined on on each page, you may have a different method of displaying in each section on each page.

This is where the need for consistency comes in. Of course, in a perfect world, you would have programmed it so well, that there would be no errors. But we know that’s not always going to happen. So, using the ASP.Net Try/Catch blocks, we try to encapsulate the errors and display them in a consistent manner.

However, in each ‘Catch’ section, we are free, as programmers, to trap and display the error messages any way we want. In this tutorial, we will attempt to show how to add a little more ‘global consistency’ to your pages in this area.

First, in a class in your .VB file (can be used with Inline coding also), we’ll create a Global variable called ‘sErrorMsg’:

Public sErrorMsg as String

Second, we’ll create a function called ‘ShowErrors’. At first glance, you will probably think that it’s really a simple function. But as you know, sometimes the greatest problems are solved with the greatest simplicity.

Function ShowErrors(sProc, sMsg) as String
	sErrorMsg= "An error has occurred (Proc: " & sProc & ")<br>" & sMsg
	Return sErrorMsg
End Function

If you’re using the Inline Coding method, if you have an existing .VB file you’re using, just include the function in your that page, or just create a new .VB file and create a new class inside that page. Then, add the function inside that class:

Public Class Basics Inherits System.Web.UI.Page Public sErrorMsg as String 'Put your Function here End Class

In the Page Directive of your .ASPX page, just add:

Inherits="Basics" src="PageName.vb"

In this function, we take the two strings as input from the page (as we’ll see below), as arguments in the function, and create another string, and assign it’s contents to the ‘sErrorMsg’ variable we created before. The first of the arguments will be defined on the page itself (the Procedure/Sub/Function being used in code).
Continues…

Inserting Record into Database

This sample uses ASP.Net 1.x – for a sample using ASP.Net 2.0 check out:
Inserting With a DetailsView

This code example actually shows three things. The first and main idea represented is how to insert a record into a database, based on form input. It is most likely the simplest method of doing this and includes form validation (Required Fields).

The second item this example shows is how to clear all the textboxes in a form, based on one of the Tips and Tricks from this web site.

The last thing is how to have three buttons in one form (the limit is only one form to a page), doing three different things. Two of the buttons have the ‘CausesValidation’ property set to false, so that when they are clicked, it won’t cause the ASP.Net validation controls to fire.

NOTE: The clear textboxes code example won’t work in this online example due to several items outside my control at this time – however, it will work by copying the code as is to your system.

To change this to work with a Stored Procedure, just change the SQL Statement to :
MySQL=”SProcName” – The Stored Procedure would actually be the SQL listed originally.
Then, after the Dim Cmd as New SQLCommand line, declare the type of command:
cmd.CommandType=CommandType.StoredProcedure
The only thing left is to create the parameters:
cmd.Parameters.Add(New SQLParameter(“@Fname”, frmFname.text))
cmd.Parameters.Add(New SQLParameter(“@Lname”, frmLname.text))

The rest is the same – that’s all there is to it!

Go to this sample done with an MS Access database

<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SQLClient" %>
<script language="VB" runat="server">

Sub doInsert(Source as Object, E as EventArgs)
	Dim MySQL as string = "Insert into testInsert (fname, lname) values (@Fname, @Lname)"
	Dim myConn As SqlConnection = New SqlConnection(ConfigurationSettings.AppSettings("YourAppSettings"))
	Dim Cmd as New SQLCommand(MySQL, MyConn)
	cmd.Parameters.Add(New SQLParameter("@Fname", frmfname.text))
	cmd.Parameters.Add(New SQLParameter("@Lname", frmlname.text))
	MyConn.Open()
	cmd.ExecuteNonQuery
	label1.visible="true"
	BindData()
	MyConn.Close()
	label1.text = "Your data has been received!"
End Sub

Sub viewthem(Source as Object, E as EventArgs)
mydatagrid.visible="true"
label1.visible="false"
	BindData
End Sub

Sub Page_Change(sender As Object, e As DataGridPageChangedEventArgs)
mydatagrid.visible="true"
	MyDataGrid.CurrentPageIndex = e.NewPageIndex
	BindData
End Sub

Sub BindData()
	Dim MySQL as string = "Select * from testInsert order by id desc"
	Dim myConn As SqlConnection = New SqlConnection(ConfigurationSettings.AppSettings("YourAppSettings"))
	Dim ds as DataSet=New DataSet()
	Dim Cmd as New SQLDataAdapter(MySQL,MyConn)
	Cmd.Fill(ds,"testInsert")
	MyDataGrid.Datasource=ds.Tables("testInsert").DefaultView
	MyDataGrid.DataBind()
End Sub

Sub cleartextboxes(Source as Object, E as EventArgs)
	Dim myForm As Control = Page.FindControl("form1")
	Dim ctl As Control
	For Each ctl In myForm.Controls
		If ctl.GetType().ToString().Equals("System.Web.UI.WebControls.TextBox") Then
			CType(ctl, TextBox).Text = ""
		End If
	Next ctl
End Sub
</script>

<form id="form1" runat="Server" >
<table border="0">
	<tr>
		<td align="right">fname</td>
		<td> <asp:textbox id="frmfname" runat="server" />
<asp:RequiredFieldValidator
runat="server"
id="vldfname"
ControlToValidate="frmfname"
ErrorMessage="First Name is required"
display="dynamic">
The fname field is Required!
</asp:RequiredFieldValidator></td>
	</tr>
	<tr>
		<td align="right">lname</td>
		<td> <asp:textbox id="frmlname" runat="server" />
<asp:RequiredFieldValidator
runat="server"
id="vldlname"
ControlToValidate="frmlname"
ErrorMessage="Last Name is required"
display="dynamic">
The lname field is Required!
</asp:RequiredFieldValidator></td>
	</tr>
	<tr>
		<td align="center"  colspan="2">
<asp:button id="button1" Text="Insert" onclick="doInsert" runat="server" />
<asp:Button id="button2" causesvalidation="false" Text="View Names" onclick="viewthem" runat="server" />
<asp:Button id="button3" Text="Clear" onclick="cleartextboxes" causesvalidation="false" runat="server" />
		</td>

	</tr>
</table>

<hr>
<div align="center"><asp:Datagrid runat="server"
	Id="MyDataGrid"
	GridLines="Both"
	cellpadding="0"
	cellspacing="0"
	Headerstyle-BackColor="#8080C0"
	Headerstyle-Font-Name="Arial"
	Headerstyle-Font-Size="14"
	Headerstyle-Font-Bold="true"
	Width="50%"
	BackColor="#8080FF"
	Font-Name="Arial"
	Font-Size="11"
	BorderColor="Black"
	AllowPaging = "True"
	PageSize = "5"
	PagerStyle-Mode = "NumericPages"
	PagerStyle-PageButtonCount = "5"
	PagerStyle-HorizontalAlign="Center"
	OnPageIndexChanged = "Page_Change"
	visible="false">
</asp:DataGrid></div>
</form>
<asp:Label ID="label1"  runat="server" />

Function to Kill Leading Zeros

If you have a string of numbers that has a bunch of leading zeros, and you want to get rid of them, just displaying the rest of the number, here’s a Function that will do it in DotNet:

Function KillEm(sItem)
Do While sItem.IndexOf("0") >-1
	if sItem.StartsWith("0")
		sItem=sItem.Substring(1)
	End If
Loop
Killem=sItem
End Function

Here’s a way to implement it in code:

Sub doZee(Source as Object, E as EventArgs)
	label1.text = KillEm(text1.text)
End Sub
<Form id="PutIDNameHere" runat="server">
<asp:TextBox id="text1" runat="server" />
<asp:Button id="Button1" Text="Kill the Zeroes" onclick="doZee" runat="server" />
</Form>
<asp:Label ID="label1"  runat="server" />

Creating a Feedback Form in ASP.NET

It’s rather simple in ASP.Net to create a generic FeedBack form. You can make it as simple or as complicated as you need. The simplest form would be merely a Form-To-Email version, which would ONLY send an email of the feedback to a specific destination. In many cases, this would for many users. However, most often, the reality is that sometimes emails get lost. Therefore, it would be more preferable to enter the data from the form, and then, also send the results by email. This way, if the email gets lost, there is still a record of the FeedBack.

There are a couple of things to consider when starting the design process. They are:

  1. Which database are you going to use?
  2. How many pieces of Information are you needing to capture?
  3. How do you want to interact with the data, once it’s in the database?

You can use any you want in this scenario, of course, but we’re only covering SQL Server and MS Access. It really doesn’t matter, in the long run. For most ANSII sql compliant databases, everything is going to be the same, except for the methods used to talk back and forth to the databases.

We also will only cover the basic fields needed in the form, but you can make the form as simple or complex as needed for your own purposes, as stated before. Just remember – for every field you have in the form, you should have a corresponding field in the database table which will be capturing the end-user’s input.

The fields we’ll be covering here are:

  1. Title
  2. Email Address (the address of the person entering the feedback,for follow-up)
  3. Feedback (multi-line textbox, sized as needed)
  4. Time Entered (automatic)
  5. Follow-up

You will need to create a database table with these fields – start with an ID field (autonumbering in MS Access or Identity in SQL Server – set as Primary Key also). Then, create the other fields however you’d like, size-wise, making the Time Entered field a Date/Time field and in our case, we’ll make the Follow-up field very small so that a ‘Yes’ can be entered when follow-up is finished concerning the feedback. If you’d like, you can add an extra field for follow-up notes.

Here is how the Form will look on the page:

Title: <asp:TextBox id="txtTitle" Runat="server" /><br>
Email Address: <asp:TextBox id="txtEmail" Runat="server" /><br>
Feedback:<br>
<asp:TextBox id="txtFeedback" Rows="4" Width="500" TextMode="MultiLine" Runat="server" /><p>
<asp:Button id="btnSubmit" Text="Submit" onclick="doInsert" Runat="server" />

As you probably noticed, the last two items in the list (Time Entered and Follow-Up) above are not included in the visual code for the feedback form. That’s because we will automatically get the system date and time and enter it into the database when the data is inserted, and the Follow-Up field is not for input, but obviously, as the name implies, for ‘follow-up’ – AFTER the data has been captured from the form.

Now, next, we’ll need an input sub that takes care of gathering the data entered into the form. Here is the code for doing just that:

Sub doInsert(Source as Object, E as EventArgs)
	Dim strConn as String = "server=YourServer;uid=sa;pwd=YourPWD;database=YourDB;"
	Dim MySQL as string = "Insert into feedback (Title, Email, Feedback, dtEntered, Followup) " & _
		"Values (@Title, @Email, @Feedback, @dtEntered)"
	Dim MyConn as New SQLConnection(strConn)
	Dim Cmd as New SQLCommand(MySQL, MyConn)
	With Cmd.Parameters
		.Add(New SQLParameter("@Title", frmTitle.text))
		.Add(New SQLParameter("@Title", frmEmail.text))
		.Add(New SQLParameter("@Feedback", frmFeedback.text))
		.Add(New SQLParameter("@dtEntered", DateTime.Now()))
	End With
	MyConn.Open()
	cmd.ExecuteNonQuery()
	'Put your Success statement Here
	'Create a label on the page and assign the success statement to the label's text value, like:
	'Label1.Text="Your inormation has been successfully received. " & _
		"We will get back to you as soon as possible"
	'Remember to Import the SQLClient Namespace also
	MyConn.Close
End Sub

Continues…

DataReader RowCount Check – Before Display

Sometimes, we’d like to know if there are actually records to be returned in our query. If there are no records, then, we could display a message accordingly. Otherwise, we can then display the record(s) as needed.

Using two reads of a DataReader, the following Code Sample demonstrates how to do this, using the Northwind Database (SQL Server)

<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SQLClient" %>
<html>
<head>
<meta name="GENERATOR" Content="ASP Express 2.1">
<title>DataReader Record Check</title>
<script language="VB" runat="server">
Dim strName as string
Sub searchit(Source as Object, E as EventArgs)
strName=text1.text
Dim strConn as string = "server=(local);uid=sa;pwd=PASSWORD;database=Northwind"
Dim sql as string = "Select FirstName, LastName, Title from NWEmployees where lastname=’" & strName & "’"
Dim conn as New SQLConnection(strConn)
Dim Cmd as New SQLCommand(sql, conn)
Dim objDR as SQLDataReader
conn.Open()
objDR=Cmd.ExecuteReader(system.data.CommandBehavior.CloseConnection)
if Not objDR.Read() then
Label1.text = "There are no employees with the name – " & strName & "."
objDR.Close
conn.Close
myDataList.visible="false"
label1.visible="true"
else
objDR.close
conn.Open
objDR=Cmd.ExecuteReader(system.data.CommandBehavior.CloseConnection)
MyDataList.datasource=objDR
MyDataList.Databind
myDataList.visible="true"
label1.visible="false"
End If
End Sub
</script>
</head>
<body>
<Form id="form1" runat="server">
Enter Last Name: <asp:TextBox id="text1" runat="server" /> <asp:Button id="button1" Text="Search" onclick="searchit" runat="server" /><br>
<font Size="2"><i>(Hint – Try ‘Davolio’, ‘Fuller’, ‘King’, ‘Peacock’ for valid names)</i></font>
<asp:DataList runat="server"
Id="MyDataList"
GridLines="Both"
cellpadding="2"
cellspacing="2"
Font-Name="Arial"
Font-Bold="false"
Font-Size="12"
Visible="false">
<ItemTemplate>
<b>Name: </b><%# Container.DataItem("FirstName")%>
<%# Container.DataItem("LastName")%><br>
<b>Title: </b><%# Container.DataItem("Title")%>
</ItemTemplate>
</ASP:DataList><br><asp:Label ID="label1" forecolor="red" font-Italic="true" runat="server" />
</Form>
</body>
</html>

Syntax error in INSERT INTO statement

If you get this error, make sure your field names aren’t reserved words when you create your tables. To get around after it’s fully created, if one of your fieldnames IS a reserved word, just surround it with sqare brackets, like this:
[YourFieldName]

To see a list of reserved words for SQL, search the Tips and Tricks for ‘Reserved’ or ‘Reserved Words’.

Introduction to Parsing Strings

There may come a situation where you have a string which needs to be broken up into parts for a particular reason. Learning how to do this is not the hardest thing to understand, but for someone just starting with ASP.Net, it may seem a little difficult.

Let’s say you have a string to manipulate that is someone’s full name. However, your database is set up to have the first name and last name separate from one another. This is an example that requires parsing the string – separating the whole, separating it into multiple (in this case, two) parts.

There are many ways this string may come into the page, but for this tutorial, let’s say it is received with a queysrtring:

myPage.aspx?fullname=John Hancock

The first thing we need to do, is to convert the querystring data into a varaible, for ease of use, and create variables for the First and Last names:

Dim sFullName as String Dim sFirst, sLast as String

It would be best to make these ‘global’ variables, so they can be more easily re-used. When using INLINE coding, to create a global variable, it needs to be dimensioned OUTSIDE any Sub or Function, but INSIDE the SCRIPT tags. In Code-Behind, you also create the variable OUTSIDE any Sub or Function. A variable is considered ‘global’ due to the fact that it can be used anywhere on the page, from the time it is populated. Otherwise, it is only available within the SUB or FUNCTION in which it is dimensioned.

Then, in the Page_Load event (for this scenario), we populate the variable:

sFullName = Request.Querystring("fullname")

Now comes the fun part. There are two methods in the String class that you will probably use a lot – Substring and IndexOf. ‘Substring’ is rather self-explanatory, as is ‘IndexOf’.
Continues…

Dynamically Loading User Controls

Sometimes, based on conditional statements, we may need to load one or more user controls, dynamically – like –
if condition #1 is true then
load control1
else
load control2
end if

This sample shows how to do this, based on three controls (First.ascx, Second.ascx, and Third.ascx)

The only code in each of theses User Control Files is in the following format:

<hr>
<div align=”center”><b><i>This is the First Control</i></b></div>
<hr>

Naturally, change the text for each User Control. Save each one with the file names above. Then, copy the code below to a new page. Also make note (from the code) that the files are in a directory called ‘aspnet’, off the root directory of your web site.

<html>
<head>
<meta name="GENERATOR" Content="ASP Express 2.1">
<title>Conditional Controls</title>
<script language="VB" runat="server">
Dim strLoad as string
Sub doit(Source as Object, E as EventArgs)
strLoad="/aspnet/" & rb1.selecteditem.text & ".ascx"
Dim myControl as Control=CType(Page.LoadControl(strLoad), Control)
ph1.Controls.Add(myControl)
End Sub
</script>

</head>
<body>
<Form id="form1" runat="server">
<asp:RadioButtonList id="rb1" runat="server">
<asp:listitem id="First" Value="First" runat="server"/>
<asp:listitem id="Second" Value="Second" runat="server"/>
<asp:listitem id="Third" Value="Third" runat="server"/>
</asp:RadioButtonList><br>
<asp:Button id="button1" Text="Load Controls" onclick="doit" runat="server" />
</Form>
<asp:placeholder ID="ph1" runat="server"></asp:placeholder>
</body>
</html>

Login failed for user /

If you are using SQL Server or MSDE and you get this error, it’s most likely due to the fact that you’re using Integrated Security in your login to the database. For this to work, the ASPNet account needs to have access to the database. This means the ASPNet account must be a user assigned in the database.

You can go to the command prompt and enter the following, based on your own machine’s configuration:
osql -E -S (local)\NetSDK -d puthereyourdatabasename -Q “sp_grantdbaccess ‘YourServer\ASPNET’”

AND THE SECOND ONE

osql -E -S (local)\NetSDK -d puthereyourdatabasename -Q
“sp_addrolemember ‘db_owner’, ‘YourServer\ASPNET’”

One other way to get around it is to use an explicit login and NOT use Integrated Security:
(“server=YourServer;uid=YourUID;pwd=YourPWD;database=YourDatabase”)