Function Libraries

Remember the old days of Classic ASP, when you could have one file, included on each page, which housed all your common functions? Well, it’s still possible today. But, instead of having an ‘Include’ file, today, in ASP.Net, you can create a Function Library, all in one file. Yes, includes are still possible in ASP.Net, in fact, simple, headers and footers are still a good a very clean and efficient way, in my opinion, to handle these. But, when it comes to common functions, referencing a Function Library on each page is the way to go.

Let’s start out by creating a clean, new file (save with .cs or .vb). Since this is a VB.Net example, we’ll call it ‘LIB.vb’. First, let’s Import a few namespaces (you’ll want to import whichever ones fit your needs). In our case, we’ll need these :

Imports System.Data Imports System.Data.SqlClient Imports System.Web.UI Imports System.Web.UI.WebControls

Then, let’s create our own Namespace, called ‘ASPNet101:

NameSpace ASPNet101 End Namespace

Inside that new namespace, on that page, we’ll create a new Class:

Public Class LB End Class

Now, let’s create several variables, inside that class that we’ll need to use:

Public Shared strConn as string = "server=YourServer;uid=YourUID;pwd=YourPWD;database=Your_DB" Public Shared MyConn as New SQLConnection(strConn) Public Shared MySQL as String Public Shared objDR as SqlDataReader

Now, since this a common function repository, we’ll include one function, to start out with, called ‘FillListBox’, and we’ll give it several arguments (Listbox, TblName, TblField, and TblID:

Public Shared Function FillListBox(LBName as ListBox, TblName as String, TblField as String, TblID as String) MySQL = "Select " & TblField & ", " & TblID & " from " & TblName MyConn.Open() Dim Cmd as New SQLCommand(MySQL, MyConn) objDR=Cmd.ExecuteReader(system.data.CommandBehavior.CloseConnection) lbName.DataSource = objDR lbName.DataTextField=TblField lbName.DataValueField=TblID lbName.DataBind() MyConn.Close() End Function

Click here, to see everything we have so far. Now, you’re probably asking, “But, how do I use it in my web page?” That’s no problem. In fact, that’s all that’s left to do in this tutorial. First, at the top of the page, let’s reference the ‘.vb’ file we just created:

<%@ Import Namespace="ASPNet101" %> <%@ Assembly src="LIB.vb" %>

Let’s create a Listbox on the page first, called ‘Listbox1′. Then, in the code section, we’ll reference populate the listbox with the Category Names from the Categories Table in the Northwind Database, using the code in the .vb file:
Continues…

Sending Mass Emails Part 2

If you haven’t read Part 1 in this series, you can do so now, by clicking here:

Sending Multiple Emails At Once

One of the major drawbacks of creating a mass emailing like we did in Part 1, was personalization and customization were practically non-existent. All email addresses were kept in a string, which populated the BCC section. Each recipient could easily see that this was a mass email. Naturally, that’s normally OK, but by being able to personalize an email gives the recipient a better feeling when he things that the ‘Sender’ of the email took the time to send the email to him, personally. By building your mass email this way, practically any level of personalization and customization is all up to you. For instance, you could create a link in the email itself, that, when clicked, can run a script on your web site to delete that user from the email list automatically.

For this example, all you’ll really need is:

  1. Import the System.Web.Mail namespace
  2. Import the Database namespaces necessary
  3. A table of Data, in the Database (for this sample, we only have two fields (Name and Email)
  4. One subroutine for the code (for this example, we’ll use Page_Load)
  5. A label with an ID of ‘lblEmails’ (only to show the list of emails for the test)

First, we’ll Import the namespaces. For emailing, we must add:

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

For the database (we’re using SQL Server for this tutorial), we must add:

<%@ Import Namespace="System.Data" %> <%@ Import Namespace="System.Data.SQLClient" %>

Now, for the real ‘meat’ of this tutorial, first, we’ll add two Global variables:

Dim sEmail as String Dim sBody as String

Next, in a Subroutine of your choice, add this code:
Continues…

Beginners Guide to Forms Authentication in ASP.NET

There are four basic parts to simple forms authentication. Those parts are:

  1. The form (to gather user ID & pwd) itself
  2. The Web.Config File entry
  3. The Data Store (the place where you keep the usernames and passwords
  4. The Validation Process, triggered in the click event of the form.

Here is an example of the simplest of Forms (let’s call the page ‘Login.aspx’), designed to gather the user ID and password:

<table> <tr> <td align="Right" valign="Top"><b>User ID: </b></td> <td align="Left" valign="Top"> <asp:TextBox id="txtUID" Runat="server" /> </td> </tr> <tr> <td align="Right" valign="Top"><b>Password: </b></td> <td align="Left" valign="Top"> <asp:TextBox id="txtPWD" TextMode="Password" Runat="server" /> </td> </tr> <tr> <td align="Right" valign="Top" Colspan="2"> <asp:Button id="submitButton" Text="Login" onclick="doLogin" Runat="server" /> </td> </tr> </table>

In the Web.Config file, add this:

<authentication mode="Forms"> <forms name=".FormName" loginUrl="login.aspx" ' remember how we named the page for the form? protection="All" timeout="480" path="/" /> </authentication> <authorization> <deny users ="?" /> </authorization>

For the DataStore – you can use anything you’d like – however, I’m a bit partial to databases for quick interaction, so this example will be using a database. You’ll need to create a table in your database to store your names, User ID and Passwords. Here’s a list of the basic table fields you’ll need:

Field Name DataType Notes
id Integer (for Access, use AutoNumber; for SQL Server, create Identity)
Name MS Access: Text; SQL Server: VarChar use a length you feel is appropriate
- you can also make this two fields (First and Last names) to be able to more easily use their first name other places on the site, once they’re logged in
Login MS Access: Text; SQL Server: Varchar, unless you want an exact number of characters.
Password (same as above)

For the actual work to do this, create a click event for the button in the form. Let’s call it ‘doLogin’. Also, you’ll create a Function to do the validation – - let’s call it ‘ValidateUser’, with a couple of arguments, ‘uid‘ and ‘pwd‘. Also, create a label with an ID of ‘lblError’, just in case the login attempt fails.
Continues…

Using MySQL with ASP.NET

Many people have asked me for this tutorial, so here goes.

For those of you who don’t know, MySQL is an open-source DataBase server. Being that it’s open-source, it’s also free. That’s about as low-cost as you can get. Of course, you may ask ‘Why use MySQL’? Did you read the previous sentences?? It’s free, as well as being a fairly robust database server!

To be able to use MySQL, there are a couple of downloads that must be done:

  1. MySQL Itself
  2. MySQL ODBC Driver

The Database Server (MySQL), itself can be downloaded here: http://dev.mysql.com/downloads/mysql/4.0.html

The Driver (for Windows) can be downloaded here:
http://dev.mysql.com/downloads/connector/odbc/3.51.html

The biggest hurdle in using MySQL, is the setup – much like many other users of MSDE have found out. Without a user interface, it’s quite cumbersome, requiring a command prompt to do all the work. Here’s the best page I’ve found so far to take you, step-by-step through this process:
http://www.analysisandsolutions.com/code/mybasic.htm#installation

Now, once this is all set up – guess what – you have no data. If you want, the above installation page will also help you get started creating databases, tables and fields for your sample data. But, if you want a much quicker way to populate your database server, so you can get started, AugustWind Software has user interface for MySQL called Data Management Toolkit. Check it out here

Now – the part you actually came here for – - the easy part!

On other parts of this site, you’ve seen many samples, using MS Access and SQL Server. As you might have noticed, there are only three major differences in using these.

  1. Namespaces used
  2. Connection String
  3. Prefix to data classes (like: OleDbDataAdapter vs. SQLDataAdapter, specific to the Imported Namespaces

For MySQL, the driver which you downloaded (above), is an ODBC Driver, therefore, numbers 1 and two in the above list use ‘ODBC’:

<%@ Import Namespace="System.Data.ODBC" %>

Continues…

Matching Regular Expressions (Regex) in ASP.NET

There may come a time when you want to match a Regular Expression against a string and you don’t necessarily want or need to use one of the built in ASP.Net Regular Expression Validators. For instance, using a validator, if the match doesn’t occur, you are not allowed to submit your form data. But, let’s say, you want to validate the data, but you don’t really mind if the data is a match or not and you merely want to send the user a message that the data didn’t match the correct format.

Using the System.Text.RegularExpressions Namespace (don’t forget to import it!), you can accomplish this in code. Note the following function:

Function RegExMatch(sItem as String, sRegEx as String) as Boolean Dim r As Regex = New Regex(sRegEx) Dim m As Match = r.Match(sItem) Return m.Success End Function

Here, we’re taking the first argument in the function (sItem) and matching it against the Regular Expression, which is in the second argument. Since the Function returns a boolean, naturally, the only two possibilites are TRUE or FALSE.

So, to implement this in code, let’s create a scenario where you are entering parts into your online system. For the partnumber itself, you use the format:
####.## – where all characters must be numeric. The Regular Expression for this would be:
^[1-9][0-9][0-9][0-9]\.[0-9][0-9]

So, in your code, you can do something like this:
Continues…

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…

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…

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…

Adding 'Last Updated' To Footer in ASP.NET

In the ‘old’ Classic ASP days, we could use the FileSystemObject, in an include file, to automatically display a ‘Last Modified’ section. This possibility has not gone away, with the advent of ASP.Net. In fact, using the System.IO namespace, there are a couple of ways to do it.

You’ll probably recognize this Classic ASP code, using the FileSystemObject:

<% Dim oFS Dim sPath Dim oFile Set oFS = Server.CreateObject("Scripting.FileSystemObject") sPath = Request.ServerVariables("Path_Translated") Set oFile = oFS.GetFile(sPath) response.write "Last Updated " & oFile.DateLastModified & _ " © 2004 YourCompanyName - All rights reserved" Set oFile = Nothing Set oFS = Nothing %>

Now, we merely import the System.IO namespace, add a label to the page and we change it to this:

Dim sPath as String = Request.ServerVariables("Path_Translated") Dim dt As DateTime = File.GetLastWriteTime(sPath ) lblBottom.Text= "Last Updated " & dt.ToString & _ " / ©2004 YourCompanyOrWebSiteName / All rights reserved"

There are a couple of ways you can do this, also. One way is to create a Footer User Control. As you probably know, User Controls are new wtih ASP.net. I won’t go into an explanation of User Controls here, since another Code Sample on this site shows how to create a simple header or footer User Control

.

The other way might surprise you. Most people are under the impression that Include Files have simply gone away, with the advent of ASP.Net. However, this is not true. There are some things that won’t work in an include file, but in general, it can still be used.

With the above sample, all that would be needed is to create a new ASPX file, to use as your footer. In that file, create a script block and Page_Load routine, just as you would with any other ASP.Net page which uses inline coding. You would put any text or formatting you need, however you need it, and then, put a label where you’d want this to appear. Here is a sample:

<%@ Import Namespace="System.IO" %> <script language="VB" Runat="server"> Dim sPath as String Dim dt as DateTime Sub Page_Load(Source as Object, E as EventArgs) sPath = Request.ServerVariables("Path_Translated") dt = File.GetLastWriteTime(sPath ) lblBottom.Text= "Last Updated " & dt.ToString & _ " / ©2004 YourCompanyName / All rights reserved" End Sub </script> <div align="center"><Font Size=2>Please, email your questions or comments to : <a href="mailto:questions@yourSite.com?Subject=Questions"> (questions@yourSite.com)</a></Font> <BR> <font Size="1"> <asp:Label ID="lblBottom" Runat="server" /> </font></div>

That’s basically it – - as you can see, just like other samples and tutorials on this site, it’s much simpler than you might have thought!
Happy coding!