Beginner's Guide to Master Pages in ASP.NET

All of us have struggled over the years to get a consistent look and feel for our web pages. There have been many ways, but now, with ASP.Net 2.0, Master Pages have created a very simple way for this to happen.

To begin with, there’s a new page extension (.Master). So, the first thing to do is to create a new Master page, with the .Master extension, and lay it out any way you’d like. At the top of that page, there’s a Master Directive, much like the Page Directive (and others) you’re already familiar with:

<%@ Master Language="VB" %>

The basic concept is, that you will then create Content pages, which in the Page Directive, will refer to the master page:

<%@ Page Language="VB" MasterPageFile="Main.master" Title="My Content Page" %>

Within each master page, you can have one or more ContentPlaceHolders (a new ASP.Net control):

<asp:contentplaceholder id="cph1" runat="server">
</asp:contentplaceholder>

Then, in the Content Pages, there are new Content controls, which refer back to the ContentPlaceHolder’s ID in the Master Page:

<asp:Content ID="first" ContentPlaceHolderID="cph1" Runat="Server">
	Here's where you put the actual content
</asp:Content>

The Content Pages use the normal ‘.aspx‘ extension.

One of the really cool features, is that, you can, from the Content pages, refer to any control on/in the Master Page, and change the properties of it. Let’s say you have an ASP.Net Image Control in the top left corner of the Master Page, and you want to change it in your Content page. Just create your image control, using whatever properties you’d like to assign:

<asp:Image id="imMain" Runat="server" />

Then, inside the Page_Load event of your Content page, your code would look something like this:

Dim Img As Image = Master.FindControl("ImMain")
Img.ImageUrl="page2.gif"

You can do this with any DotNet control you put on the Master Page. Let’s say you also have a label control at the bottom of your Master page, for the footer, called ‘lblFooter’. You want it to always say the same on every page, at least. But then, on one or more of your Content pages, you need to add something. So – in the Content Page’s Page_Load event:

Dim lbl as Label=Master.findControl("lblFooter")
lbl.Text=lbl.Text & "
Special Content -  Copyright by the Author - Harold Magnolia"

This will keep the same footer that you have on every other page, and also add the extra text (on a second line) above.

To see these basic concepts in action Click Here.

Code for the Master Page:
Continues…

Beginner's Guide to Themes in ASP.NET

Using Themes with ASP.Net 2.0 is very simple. Most web designers by now understand the concept of ‘skins’. That’s the way Theming in ASP.Net 2.0 is built, by creating skins, or a ‘look and feel’ for a web site.

Here are the absolute necessities to build a theme:

  1. A folder called ‘App_Themes‘ in the application’s root directory
  2. At least one folder, with the name of the ‘skin’ as its name.
  3. Within that folder, at least one ‘skin’ file

Number 1 is fairly straightforward, but if this is your first time learning about Themes in DotNet 2.0, you may not know what a ‘skin’ file is. Basically, it’s only a text file, with ‘.skin’ used as the extension. Inside that text file is where you build what will be your ‘skin’. The only things that are required inside this .skin file is a list of all the ASP.Net server controls, the look of which you want to control. Let’s say that, for each and every textbox you have in your website, you would like the border color to be solid, 1 pixel in width and Light Gray in color, and you want it to have an Antique White back color. No problem. In the skin file, you build an ASP.Net Textbox, including the Runat=”Server” designation, but WITHOUT the ID attribute, using the look and feel you desire. For instance, in this example, it would look something like this:

<asp:TextBox
  BorderColor="LightGray"
  BackColor="AntiqueWhite"
  BorderWidth="1px"
  Runat="server" />

Now, you create a look and feel for each and every ASP.Net server control you want to include in this skin file. There’s no real need to include EVERY server control in the skin file, but you probably should include each server control that you’ll most likely be using in the application. Then, save that skin file, with a .skin extension, with the same name as the designated skin, and inside the designated Theme directory.

Continues…

Sending Emails With ASP.Net

If you haven’t checked into it yet, there are several things that have changed from ASP.Net1.1 and ASP.Net 2.0, concerning email, however, it’s still not very complicated.

The first thing you’ll notice is that the namespace has changed from System.Web.Mail to System.Net.Mail. Also, now, to get the email working, there are two classes that need to be addressed:

  • MailMessage()
  • SmtpClient()

To use these, it will look something like this:

Dim Msg as MailMessage = new MailMessage()
Dim MailObj As New SmtpClient("mail.YourDomain.com")

Now – to add your To and From addresses, the Subject, Body and Body type, you’d do something like this:
Continues…

A Beginner's Guide to the GridView

OK – remember when you first heard about the DataGrid, and how Paging and Sorting were what was called “built-in”? And then, when you found out what a hassel it was, even though it was a lot better than what you had before, you still were kind of disappointed?

Well – now we have the GridView, in ASP.Net 2.0 and your disappointment is over! The ‘AllowPaging’ and ‘AllowSorting’ properties mean exactly what they say – once you set them to ‘True’ – that’s it – that’s all you need to do. It’s what we were all wishing for with the DataGrid.

But wait – there’s more (I hope this doesn’t sound too much like an infomercial)! With only one other control on the page, you can display data quickly and efficiently and never write a line of code to bind to the GridView. That control is the DataSource control. (You can find out more about how to use it here). Add a DataSource control to the page, assign the desired values to the properties both it and the Gridview and you’re through. No more forgetting the Sorting Sub or the Paging Sub or forgetting that you need a DataSet – not a DataReader, in able to add sorting and paging to the grid.

I know – you might be saying to yourself “That can’t be correct!”, but I assure you, it is. Here’s all you need to display data from your favorite Database table:

<asp:GridView id="MyGridView" DataSourceID="MyDataSource1" Runat="Server"/>

<asp:SqlDataSource ID="MyDataSource1" runat="server"
  ConnectionString="Server=YourServer;uid=YourUID;pwd=YourPWD;database=YourDB"
  ProviderName="System.Data.SqlClient"
  SelectCommand="SELECT [Field Name List] FROM [Table Name]">
</asp:SqlDataSource>

Really! – that’s all there is to it! One thing to remember is that the Provider name is apparently case-sensitive, so make aure that’s entered correctly. And – as was noted earlier, to enable Paging and/or Sorting, just add the ‘AllowPaging’ and ‘AllowSorting’ properties to the GridView:

<asp:GridView id="MyGridView"
	DataSourceID="MyDataSource1"
	AllowSorting="True"
	AllowPaging="True"
	Runat="Server"/>

Naturally, there are many more features/attributes to the GridView, much like the DataGrid, including all the formatting options you might need. And, you’re probably saying – “Yea – but what about updating/editing?”. Well, that’s gotten a lot easier also. Just a few things to add.

  1. Enter an Updatecommand (Update SQL Statement) to the existing DataSource, just as you added a SelectCommand.
  2. Add two properties to your GridView (AutoGenerateEditButton and DataKeysNames)

So – here’s what’s needed in the changed Controls (using Pubs as an example):
Continues…

A Beginner's Guide to the DataSource Control

The DataSource control (new in ASP.net) is a real timesaver for programmers. Now, instead of writing all the code to populate a grid, it’s possible to use a DataSource control, a new ‘genre’ (if you will) of controls, which provide ‘declarative’ access to data. Though I won’t go into all of them (there are several – SQL, Access, XML, SiteMapDataSource and ObjectDataSource controls), I will cover the Database type DataControl (SQLDataSource and AccessDataSource). The properties are similar for both.

In general, at the basic level, what happens is that each DataSource control has many properties which the programmer populates, like the ConnectionString property and the SQL statement properties (SelectCommand, UpdateCommand, etc).

Once these properties have been provided, a presentation control (like a GridView, FormView or DetailsView control, all new in v2.0 of the Dotnet Framework) can point to the DataSource control, and without any coding at all – voila – a web page has been created that displays data from a data source. Naturally, it doesn’t do much except presentation, at this point, but like was said earlier, this is just the basic leve..

For the SelectCommand, one can choose a pure SQL Select statement (Select [field name list] from [Table name]), or a Stored Procedure. If a Stored Procedure is used, the ‘SelectCommandType’ property needs to be set thusly:

SelectCommandType="StoredProcedure"

Here, we might add that a new section has been added to the Web.Config file, specifically for Connection Strings. And, as you might figure, the section is called ‘ConnectionStrings’, and is placed inside the Configuration section of the Web.Config file, much like the AppSettings section was used earlier, for the connection strings. The main difference here, is, instead of ‘add key’, we use ‘add name’:

Continues…

Coolest New ASP.NET 2.0 Additions

Here are the coolest features, as I see it, in ASP.Net 2.0:

  1. Cross Page Posting
  2. Focus API
  3. Validation Groups
  4. New Client-Script Features

Yes, ASP.Net was a huge advance in the programming world. BUT – there were several (maybe even quite a few) annoyances that really bugged most of us. This list of Top 4 Coolest Features in 2.0 address some of those items directly.

Ok, let’s start with the biggest one of the four - . For all of us that came from Classic ASP world, this is a biggie! Though I really like the new paradigm of posting back to the same page, and use that most of the time, we’ve all found instances that really needed this feature.

if you go to the quickstarts, you’ll find an example of how to handle this. then, you’ll say to yourself, “Here we go again, with the off the wall, klunky code concepts”. However, don’t worry about it - I have good news.

First off, the posting page is NOT listed in the FORM tag. That’s not really a big problem, because it’s a property in the button control – the PostBackUrl property. For example:


<asp:Button id="button1" Text="Submit" onclick="whatever" PostBackURL="NextPage.aspx" Runat="server" />

Then, (here’s where the new coding concept comes in) according to the QuickStarts example, we should do this, in the Postback page’s Page_Load event:
Continues…

Creating a 'States' User Control in ASP.NET

A good example of a particular repeatable scenario within a website would be a DropDownList of States (for those living in the United States, of course). There’s no need to create the code for this scenario multiple times within a web site. The best choice is to create a User Control for this, if you have multiple places where it can be used.

Let’s start off by creating the DropDownList on the page:

<asp:DropDownList id="ddlStates" runat="server"/>

Now, let’s populate the DropDownList with the states (some of you will recognize this from a previous Code Sample).

Sub Page_Load(Source as Object, E as EventArgs) if not Page.IsPostBack then Dim sStates() as string={"","AK", "AL", "AR", "AS", "AZ", "CA", "CO", "CT", _ "DC", "DE", "FL", "GA", "GU", "HI", "IA", "ID", "IL", "IN", "KS", "KY", "LA", _ "MA", "ME", "MD", "MI", "MN", "MO", "MP", "MS", "MT", "NC", "ND", "NE", _ "NH", "NJ", "NM", "NV", "NY", "OH", "OK", "OR", "PA", "PR", "RI", "SC", "SD", _ "TN", "TX", "UT", "VA", "VI", "VT", "WA", "WI", "WV", "WY"} ddlStates.datasource=sStates ddlStates.databind() end if End Sub

So far, that’s pretty straightforward, but since we won’t be accessing the DropDownList directly, inside the User Control, we must create properties which can be used to do what we need, for any properties which aren’t intrinsically inherited. For this example, we’ll create a SelState Property and a TabIndex Property. You’ll most likely recognize the TabIndex property from other controls. Here, since you’re creating your own properties, you can call it anything you’d like. For the sake of simplicity, we’re calling it ‘TabIndex’ so that it’s function will be automatically recognized. To do this, here’s the code:
Continues…

Iterating Through a List-Type Server Control

As many of you know, there are several List-Type server controls in ASP.Net, like the ListBox, DropDownList, CheckBoxList, and RadioButtonList. Since these controls are all of the same type, most of the same properties and methods work for each of them. The DropDownList and the RadioButtonList do have one drawback. Of the controls listed above, those two do NOT allow multiple selections, so they will not be addressed or included in this tutuorial. But for the Listbox and CheckBoxList, what you will learn here will become very handy.

First off, one basic way to iterate through a List Control is with the For/Next Loop, like this:

Dim li as ListItem For each li in YourListControl.Items If li.Selected = True Then ....Process your Data End If Next

You can see a ListBox code sample, using this technique here:
ListBox – Select All/Select None

If you were referring to an individual listItem in your programming, you would use the ‘SelectedItem’ property (either Text or Value) Inside, the loop, when you process the individual items, you can refer to each item in the list (li) and all it’s properties, directly, like:

  • li.Value
  • li.Text

Sometimes, though, you may want to process your data differently, and it may become necessary to use a different For/Next Loop, so, you can also use it this way:

Dim li as ListItem Dim x as Integer For x = 0 to YourListControl.Items.Count-1 If YourListControl.Items(x).Selected="True" Then ....Process your Data End If Next x

Continues…

Beginner's Guide – Installing MSDE

These days, with the Windows interface, many people, especially people who are new to the programming world, have not had much experience with the Command Prompt. For those people, using the Command Prompt will be the hardest part of using MSDE, though, when broken down, really isn’t all that hard.

Here are the steps necessary for installing MSDE:

  • Download SQL2kdesksp3.exe (unpacks to a folder - http://www.microsoft.com/sql/downloads/2000/sp3.asp)
  • Run/unpack downloaded file to the folder of your choice. (hint: make it easy to get to from the command prompt)
  • Open the Command Prompt (Start/Run/Cmd) – some of you may call it a DOS prompt, also.
  • Navigate to the directory where the unpacked files reside (like “c:\sql2ksp3″)
  • Hardest part: Run Setup.exe, with parameters *** (explained below)

***There are quite a few switches and parameters that the Setup program can accept, but for the most part, we are going to concentrate on just a few. In case you don’t know, an argument, in this case, is merely a set of instructions, passed to the Setup application, telling it how you’d like MSDE to be set up. For an entire list of parameters available, check out this MSDN article.

The three parameters we’ll be adressing here, are the Instancename (what we’ll call this instance of MSDE), the password given to the SA (System Admin) account, and the type of security you’d like to have for MSDE. If your’re unfamiliar with passing parameters to a program in the command prompt, it looks a lot like this:

c:\sql2Ksp3 >Setup.exe INSTANCENAME=db2000 SAPWD=yourpassword SECURITYMODE=sql

First off – “INSTANCENAME” – that’s what we’re naming this ‘instance’ of MSDE. (You can have multiple instances of MSDE running on your computer

).

Next, we’ll look at SAPWD. With this argument, we assign a password to the SA account. There is an argument allowing a Blank Password, but I’d highly recommend against that for obvious security reasons.

Continues…