Adding Dynamic Content to Your Pages in ASP.NET

In a data-driven website, there becomes a need to have only one page serve up different data, based on the call to the database. Naturally, you wouldn’t want to have the same Title on the page’s drag bar, and you certainly would like to have different Keywords in your meta tag along with every section of content received from the database. This tutorial will attempt to provide a simple example/overview of how to dynamically add, not only the content, but the Title of the page and the Keywords for the HTML Meta Tags in order to get you started in this direction.

First we’ll start with the database table structure. Keep in mind, I previously said ‘a simple way’, so, keeping that in mind, here would be four fields needed to do this:

  • id (in MS Access, Autonumber/in SQL Server – Identity)
  • Title
  • Keywords
  • Content – content for the page

For each section of content we plan to show in this page, when we enter the data into the table, we will, of course, make the fields not accept nulls.Since the ID field is autonumbering, we don’t need to worry about that field when inserting data. When we call this page (let’s call it ‘Content.aspx’), it will need a querystring added to it, which will be based on the ID field – something like ‘Content.aspx?id=1″. This way, we will then query the database in the Page_Load event, requesting record #1 from our table. it will then return the Title, Keys and the Content for the page. Outside of Page_Load, we dimension the variables:

Dim sKeys, sTitle, sContent as String

We’ll only need a DataReader to retrieve this information, and we can put the information into variables for use within the page, like this:

While objDR.Read
	sContent=objDR("Content")
	sTitle=objDR("Title")
	sKeys=objDR("keywords")
End While

Continues…

Menu User Control with Rollovers in ASP.NET

Many people have asked about using Rollover button images in Forums and ListServs lately. Therefore, this tutorial will attempt to explain how to create a menu system as a user control, using Javascript Rollover images. If you’ve read any of the tutorials on this site before, you know how many times they’ve started out with something like, “This is not going to be as hard as it sounds”. Well, this time is no exception.

If you’ve ever used an HTML/Javascript solution for creating Javascript Rollover Buttons, you know how complicated it can get if you’re not using an editor that will help you do it. Technically, the way that is about to be explained uses the same Javascript principles, but in a much less complex way.

First, we start out with creating a new User Control. Call it menu.ascx. You can create the visual portion anyway you want it – vertically or horizontally, in a Table or not. However, today, we’re creating one in an HTML table, horizontally. In our new menu, there will be three buttons, Art, Contact and Web Design. Keep in mind here, that, for each of these three menu buttons, you will need to create 3 buttons for the different ‘States’ of the buttons (basic, OnMouseOver, OnMouseDown). As you can see, at this point, this tutorial is going a little bit further than just having a ‘Hover’ or ‘OnMouseOver’ state. the ‘OnMouseDown’ state is for two things – when the button is clicked, and defining a button for when the page relating to the button is the current open page.

Continues…

Transferring ASP.NET Form Results to 2nd Page

Since ASP.Net forms submit to themselves by default, many people have asked how to get the form results passed on to another page. There is more than one way to do this. One pretty much entails not putting the ‘runat=”server”‘ designation in the form tag, building it just like it was in Classic ASP. However, the main focus of this tutorial is showing you how to accomplish this using the Server.Transfer method.

Server.Transfer actually transfers the user to a new page, but there is one down side to this, in some people’s eyes. The fact that you are on another page may not be readily known by the end-user. The TITLE of the page changes, but the address bar of the receiving page remains the same as the first page.

So here’s the full code of what we need on the first page: Yes, Server.Transfer DOES technically work by itself because it moves the browser to the next page, but it takes a little extra work to be able to take all the form results with it when the system gets to the next page. Everything starts with the form, naturally. Here’s a sample form for the scenario.

<Form id="form1" runat="server">
	First Name:  <asp:TextBox id="txtFirst" runat="server" /><br>
	Last Name:  <asp:TextBox id="txtLast" runat="server" />
	<asp:Button id="button1" Text="Submit" onclick="doSubmit" runat="server" />
</Form>

Continues…

Using the ASP.NET AdRotator Control

Here’s where it all starts:

<asp:adRotator AdvertisementFile=”/myads.xml” Runat=”server”/>

Let’s say you want the ads on your site to be at the top or bottom of the page. You merely place the adRotator control wherever you want it on your page. This is one of the built in ASP.Net server controls. As you can see, the property ‘AdvertisementFile’ must point to an xml file. Here, it is named ‘myads.xml’, but you can name it anything you want – but it needs to be in xml format. Therefore, you might want to brush up on the basics of xml if you don’t know what an xml file is. If you know a little about the basics of databases, the format should at least look a little familiar. Just have the path to the xml file an exact one so that the server control can find it, in reference to the page it’s on.If you wanted the URLs loaded in a new blank page, you could add the ‘target’ property inside the adRotator control (target=’blank’).

Here’s the basic format of what’s needed in the xml file:
Continues…

The 3 'Execute' Command Methods in ADO.NET

Here, we’re going to look at the most often used or needed methods of the command object (OleDbCommand or SQLCommand), their differences and how each one is used. They are the ExecuteReader, ExecuteNonQuery, and ExecuteScalar methods. Once you make a connection to your database and create a command, you’re going to need one of these methods to execute the command.

    Simple Overview:

  • ExecuteReader – basically, this method returns a DataReader which is filled with the data that is retrieved using the command.
  • This is known as a forward-only retrieval of records – it uses your sql statement to read through the table from the first to the last.
    There are many DataReader examples on this site. Just go to http://aspnet101.com/aspnet101/aspnetcode.aspx and choose DataReader from the DropDownList

    Useage: cmd.ExecuteReader

  • ExecuteNonQuery – this method returns no data at all. It is used mainly with Inserts and Updates of tables.
  • Here, also, we have many code samples using ExecuteNonQuery.
    Inserting records
    Updating a Record

    Useage: cmd.ExecuteNonQuery

  • ExecuteScalar – Returns only one value after executing the query – it returns the first field in the first row. This is very light-weight and is perfect when all your query asks for is one item.
  • This would be excellent for receiving a count of records (Select Count(*)) in an sql statement, or for any query where only one specific field in one column is needed.

    Useage: cmd.ExecuteScalar

Displaying DataBase Information in ASP.NET

Have you ever asked this question:

“How can I connect to a database and display it in a web page?”

Unfortunately, that’s pretty much like asking : “What occupations are available for me in the world?” Well, it’s not quite that bad, but there are a lot of different ways to do it. First, let’s break it down into two sections – Connecting to and getting information from the database, and Displaying it in the web page. For each of those sections (which could easily have been broken down further), there are multiple possibilities, which this tutorial will at least partially address.

However, to make this merely a simple tutorial, instead of a book, hitting the highlights of the basic things necessary for Dispaying DataBase information on a web page, using ASP.Net. Also, the only databases covered here will be SQL Server and MS Access, the only language covered here will be VB.Net and we’re only going to address Select Queries, leaving out (updates, deletes and inserts).

    In connecting to a database, there are several items which are necessary:

  • Namespaces
  • Connection String
  • Connection
  • SQL Query (or non-query, in the case of an insert, update or delete)
  • Opening the Connection
  • Executing the Query
  • Closing the connection

Namespaces
For both SQL Server and MS Access, we import the System.Data Namespace. Separately, for SQL Server, also:
Continues…

Displaying Sessions/Visitors Online on an ASP.NET Page

One of the more common questions I’ve found on the net is ‘How do you show the number of current users browsing my site?”, like ASPNet101.com has on the bottom left of each page. This tutorial will take the mystery out of this by breaking it down, piece by piece.

It all starts with the Global.asax file. For those of you who have come from the Classic ASP world, you will probably recognize the name of this file, since Classic ASP also had a Global.asa file. Here, we track the active Sessions for our application. There are three subroutines into which we’ll be looking to do this – Application_OnStart, Session_OnStart, and the Session_OnEnd.

First, in the Application_OnStart sub, we basically set the user count to 0, when the server starts

Sub Application_OnStart (Sender as Object, E as EventArgs)
	' Set our user count to 0 when we start the server
	Application("ActiveUsers") = 0
End Sub

Next, in the Session_OnStart subroutine, there are several things happening:

Sub Session_OnStart (Sender as Object, E as EventArgs)
	Session.Timeout = 10
	Session("Start") = Now
	Application.Lock
		Application("ActiveUsers") = Cint(Application("ActiveUsers")) + 1
	Application.UnLock
End Sub

Continues…

Sending Bulk Emails in ASP.NET

Just like setting up emailing from a form, in general, is not difficult, neither is sending emails to multiple people at the same time. First, we need to dimension a variable called ‘MyVar’: to hold all the email addresses in a string:

Dim MyVar as String

In inline coding, this would be placed inside the script tag, but outside any Sub or Function.

Next we need to set up the BCC field, grabbing all the emails from a database field called (surprise!) ‘email’:

Dim MySQL as string = "Select email from yourTableName"
Dim MyConn As SqlConnection = New SqlConnection(ConfigurationSettings.AppSettings("UrAppString"))
Dim objDR as SQLDataReader
Dim Cmd as New SQLCommand(MySQL, MyConn)
MyConn.Open()
objDR=Cmd.ExecuteReader(system.data.CommandBehavior.CloseConnection)
MyVar=""
While objDR.Read()
	MyVar+=objDR("email")& ";"
End While
MyVar=MyVar.substring(0,(MyVar.Length-1))

Continues…

Emailing Form Results in ASP.NET

The task at hand is taking the input from a form, and emailing those results to a desired target. It’s not as hard as one might think. Many of you probably worked with the CDO object in Classic ASP to get this done. If so, you’re much closer to understanding this than you think. Even if you are new to programming, you’re going to be amazed at how simple this really is.

The first thing that’s necessary, of course is the form. For this example, we’re using VB.Net and ASP.Net server controls. Naturally, for the purposes of this tutorial, we’re going to keep it fairly simple, but the same principles apply for a much more expanded form. Here’s a sample of the HTML section for the form:

<Form id="form1" runat="server">
First Name: <asp:TextBox id="txtFname" runat="server" />
Last Name: <asp:TextBox id="txtLname" runat="server" />
Email: <asp:TextBox id="txtEmail" runat="server" />
<asp:Button id="btnEmail" Text="Email Form" onclick="doEmail" runat="server" />
</Form>

The next thing to make sure we have listed on our page is a reference to the correct namespace. For emailing, it’s:

<%@ Import Namespace=”System.Web.Mail” %>

As you probably noticed, there is an ‘onclick’ event referenced for the form’s button, ‘doEmail‘. This is where we’ll take the output of the form and do the actual emailing of the input.

Sub doEmail(Source as Object, E as EventArgs)
	Dim sMsg as String
	sMsg+="Hi there - here's the information I entered in the form." & vbcrlf
	sMsg+="First Name : " & txtFname.Text & vbcrlf
	sMsg+="Last Name : " & txtLname.Text & vbcrlf

	Dim objEmail as New MailMessage
	objEmail.To=txtEmail.text
	objEmail.BCC="JohnnyWhite@jwmason.com" '<--- this would be where you can send it to yourself at the same time.
	objEmail.FROM="me@here.com"

	objEmail.SUBJECT="Here's the subject of the email"
	objEmail.BODY=sMsg
	objEmail.BodyFormat = MailFormat.Text
	SmtpMail.SmtpServer ="mail.Wherever.com"
	SmtpMail.Send(objEmail)
End Sub

In this sub, you’ll notice that the first thing we’re doing is creating a string variable to store our email message. The first part of the message is the opening line, but then you’ll see we’re adding and formatting the specific data from the form, item by item. Naturally, that can be formatted pretty much most anyway you’d like.

Next, we actually reference and instantiate the email object (MailMessage), followed by the essential, basic parts of any email message, the To, From, Subject and Body segments, along with the CC (carbon copy) section. We could also add a BCC section if wanted (Blind Carbon Copy). Remember that string variable we created at the first of the subroutine? We assign it in the Body section. You’ll probably notice that there are no quote marks around sMsg, and that’s BECAUSE it’s a variable. If you wanted to hard code a BODY section here, you’d surround it with double quotes.

Before sending the message, there are two things necessary – assigning a format (Text or HTML), and assigning an SMTP server. If you are using a hosted site, many of them use the format – ‘mail.Wherever.com‘, with ‘Wherever.com’ section being your own domain name. In this case, we’re using a pure text format, but, just as easily, we could have used an HTML format:

objEmail.BodyFormat = MailFormat.HTML

You could then use just about any valid HTML markup tags you wanted inside the BODY section. Of course, you’d need to make sure the person to whom the email is being sent (most likely YOU, in this case) can accept HTML emails correctly. Then, the last line is what really creates and sends the email message:

SmtpMail.Send(objEmail)

Naturally, you’d probably want to add in some validation (ASP.Net validation will be addressed in another Tutorial here), so blank form field results are not sent in the email. So, here you have it in a nutshell – create an input form, along with a subroutine to actuallysend the email, and you’re ready to go. The user just fills in the information for which you asked, clicks the ‘Email Form’ button and the email is on it’s way.

‘What about attachments?’, you may ask. That’s a very good question. In continuing with my ‘It’s not as hard is it may sound’ way of presenting – that’s exactly right – it’s very simple. All you need to do (before the SMTP.Send method, of course is to add this line:

objEmail.Attachments.Add(New MailAttachment(server.mappath(“/yourpath/yourfile.txt”)))

The only catch here is that the file that you’re sending MUST to be ON the file server, and the path you include here needs to be a valid path, either using ‘Server.Mappath’, or an explicit path.

Well – that’s all there is to it…no pain, right?

You might want to check out another Emailing Tutorial on this site, entitled ‘Sending Multiple Emails at Once (Mass Emails)‘ also.

Inserting Data Into Two Tables in ASP.NET

One of the most common questions on the net these days is how to do the following scenario:
“How do I insert data into one table, get the ID from that table and insert that ID and other data, into the second table?”

This tutorial uses the SQL Server managed provider for demonstration purposes. The most widely accepted ‘best’ way to accomplish this, would be to create a Stored Procedure in SQL Server to do it all for you, so that’s the direction this tutorial will take….
Here’s one I just snipped out of one of mine and edited a little:

CREATE   PROCEDURE procInsSamples
@CategoryID int,
@Title varchar(100),
@Description text,
@Link varchar(150),
@Whatever
AS
Begin
	Set NoCount on
	DECLARE @WhateverID INT
	Insert Table1(Title,Description,Link,Whatever)
	Values
	(@title,@description,@link,@Whatever)

	Select @WhateverID=@@Identity

	Insert into Table2
	(CategoryID,WhateverID)
	Values
	(@CategoryID,@WhateverID)
End

This way, you take input from a form (wherever) and insert it into table one – then the next line gets the ID from the newly entered data:

Continues…