[ASP.NET] Horizontal Submenu from XML

In my last post I showed you a workaround that allowed you to create a horizontal submenu when you clicked on a MenuItem from another menu on the same page. That example hard-coded the MenuItem definitions into the code file, and I said that I’d be demonstrating how to create a horizontal submenu from a sitemap file. While attempting this, I got hit in the face by an error that has to do with hierarchy which I researched only to find that most people suggest it would be easier to find another alternative rather than try to solve the problem.

My alternative was to create a custom xml file that contains property definitions for the MenuItem class (namely Text and NavigateURL). Here it is:

<name>Visual Basic.NET</name>

1 <?xml version=1.0encoding=utf-8?>
2 <CategoriesMenu>
3 <item>
4 <id>0</id>
5 <name>VBScript</name>
6 <url>~/Articles/List.aspx?t=cat&amp;r=vbs</url>
7 </item>
8 <item>
9 <id>1</id>
11 <url>~/Articles/List.aspx?t=cat&amp;r=vbs</url>
12 </item>
13 <item>
14 <id>2</id>
15 <name>ASP.NET</name>
16 <url>~/Articles/List.aspx?t=cat&amp;r=vbs</url>
17 </item>
18 </CategoriesMenu>

Unfortunately, here’s where the frustration kicked in (mostly because I have very little experience working with XML). I had a lot of problems figuring out how to get the right values out of the XML and into my menu where I needed them. Good thing for you, I’ve spared you the aggravation by fighting through it for you.

Basically, we need to select each <name> and <url> element outlined in the XML and use the text inside of those as our menu definition properties. It took a few hours, but I managed it; here’s how:

<col style="width: 760 Continue reading

Visual Basic Guestbook – Part 3

In this last section of the Visual Basic Guestbook code, we’ll explore how to delete entries from the database in the simplest way possible. We’re going to add a section to our view page that we can use to delete the entries.

Now what you’ll find in a lot of guestbooks is a button on each entry that you can select that will delete the entry. I haven’t learnt how to do that yet, so we’ll be using a textbox control and a button. You’ll need to enter the PostID of the entry you want to delete and click the button. So lets get started.

The first thing we want to do is secure the delete function so that not just anyone can remove entries. To do this, we’re going to add a password to the event handler that the user will have to enter before (s)he can see the delete dialog:

NOTE: As opposed to using normal hyperlinks to the DataRepeater on the view page, add buttons for these functions just before the DataRepeater. This will make it easier to get the event handlers organised.

On your page, add the following controls:

txtAdminPass = TextBox
btnVerify = Button
lblStatus = Label
txtEntry = TextBox
btnDelEntry = Button

Add a Page_Load event handler and set the visibility of these controls to false. After you’ve done that, add the following to the click event handler for the delete button:

txtAdminPass.Visible = True
btnVerify.Visible = True

After that, add an event handler for btnVerify:

If  txtAdminPass.Text = “enter_your_password_here” Then
    lblStatus.Visible = True
    lblStatus.Text = “Access granted.”
    lblStatus.Forecolor = Drawing.Color.Green
    txtEntry.Visible = True
    btnDelEntry.Visible = True
    lblStatus.Visible = True
    lblStatus.Text = “Access denied”
    lblStatus.Forecolor = Drawing.Color.Red
End If

This just displays the controls that we’ll use to delete the entry from the database. Now we have to actually delete the entry:

This code goes into the click event handler for btnDelEntry:

Dim con As New SqlConnection(Data Source=.\SQLEXPRESS;” & _
                                                                 “Initial Catalog=Guestbook;” & _
                                                                 “Integrated Security=True;”)

Dim sql As String = “DELETE FROM UserPosts WHERE [PostID] = @Post”

Dim command As New SqlCommand(sql, con)

Dim i As Integer

If Integer.TryParse(txtEntry.Text, i) Then
    command.Parameters.AddWithValue(“@Post”, Convert.ToInt32(txtEntry.Text))

    lblStatus.Text = “Please enter a numeric value.”
    lblStatus.ForeColor = Drawing.Color.Red
End If

That’s it. Basically all we’re doing here is initially (in the Page_Load) event handler, we’re making sure that the controls meant for deleting entries are hidden. We’re displaying the user verification controls (txtAdminPass, btnVerify) when the user clicks on the delete entry button that’s next to the sign guestbook button. We’re checking user input in the textbox against a value that’s defined in the code. If the user input matches, we’ll display the next set of controls, otherwise, we inform the user that the password entered was incorrect.

To delete the entries, we create the connection, sql command and sql parameter. We’re also creating an integer. The reason we create the integer is so that we can make sure that what the user entered into the txtEntry textbox is an integer. If it is, we delete the entry, if not, we inform the user that only a numeric value can be used.

You’ll notice the difference in the sql parameter to the ones we created in Part 2. This difference basically makes sure that the data entered into the textbox (which is, by default, of the data type string) in converted to an integer.

I’d like to thank you for your time, and for reading my blog. If you’ve got any questions, ask them in comments. Alternatively, head off to http://code.msdn.microsoft.com/netguest and download the application. It installs itself, is lightweight and easy to use.

PLEASE NOTE: If you decide to use my guestbook, but don’t have sa access to the SQL Server on the server that your websie’s hosted on, go into the Default.aspx code file in the root directory of the guestbook and change the uid and pwd parts of the connection string on that page and enter your access details for SQL Server (probably the same username and password you access your website’s control panel with).


Visual Basic Guestbook – Part 2

What with job hunting and doing this and that around the house, I haven’t had much opportunity to write this post and I apologise for the delay.

If you’ll remember, in Part 1, we created the database the guestbook would use and populated it with an entry that will aid us during testing.
In Part 2, we’ll be creating the forms that will allow us to view and sign the guestbook. We’ll deal with deleting entries in the next section.

View Guestbook Entries
On our home page for the guestbook (I’m using Default.aspx), we want to view the guestbook. The best way to do that is by using a Data Repeater which basically displays the data in the database table repeatedly (as it’s name suggests). So the first thing we need to do is add a SQL Data Source to the page, so drag one onto the page and configure the data source using the wizard. For this example, a standard connection string will do (i.e. Data Source=.\SQLEXPRESS; Initial Catalog=Guestbook; Integrated Security=True;). You can view the connection string if you like and proceed in the wizard to select all fields within the table in our database.

Now drag a Data Repeater onto the page and switch to your code view.
We could use the <HeaderTemplate></HeaderTemplate> tags within the data repeater to place our sign and delete links, but I found that if you do it this way, the links become part of the data repeater and you can’t use them in your code file..

The code for your links and data repeater should look like this:
<a href=”Sign.aspx”>Sign Guestbook</a> | <a onclick=”EntryDelete”>Delete Entry</a>
<asp:Data Repeater runat=”server” id=”rptGuestbook” Data Source=”SqlDataSource1″>
        <table width=”400px”>
                <td width=”10%”><%#Container.DataItem(“PostID”) %></td>
                <td width=”40%”>Posted By: <%#Container.DataItem(“UserName”) %></td>
                <td width=”25%”><a href=”mailto: <%#Container.DataItem(“Email”) %></td>
                <td width=”25%”><a href=”<%#Container.DataItem(“URL”) %></td>
            <tr><td colspan=”4″><%#Container.DataItem(“Message”) %></td></tr>

Basically all we’re doing here is to bind the information within the cells to the data in the database. This is made possible by the fact that we linked the Data Repeater to the SQL Data Source we linked to the database.

Sign Guestbook
Now we get to the fun part. Add a page to your project and call it Sign.aspx. Add 4 labels4 textboxes, and 1 button to the page. Arrange them logically and name them as shown below:

Labels Textboxes
lblName txtName
lblEmail txtEmail
lblAddress txtAddress
lblMessage txtMessage

Remember to make txtMessage a multiline textbox.

Now right-click on btnSign and add the following code to the event handler that is created:

Dim constr As String = “Data Source=.\SQLEXPRESS;” + _
                                  “Initial Catalog=Guestbook;” + _
                                  “Integrated Security=True;”

Dim con As New SqlConnection(constr)

Dim sql As String = “INSERT INTO UserPosts(UserName, Email, URL, Message) Values(@UserName, @Email, @URL, @Message)

Dim cmd As New SqlCommand(sql, con)
cmd.Parameters.Add(“@UserName”, SqlDbType.varchar, 50)
cmd.Parameters(“@UserName”).Value = txtName.Text
cmd.Parameters.Add(“@Email”, SqlDbType.varchar, 50)
cmd.Parameters(“@Email”).Value = txtEmail.Text
cmd.Parameters.Add(“@URL”, SqlDbType.varchar, 50)
cmd.Parameters(“@URL”).Value = txtAddress.Text
cmd.Parameters.Add(“@Message”, SqlDbType.text)
cmd.Parameters(“@Message”).Value = txtMessage.Text


Please remember to add your imports at the very top of your code file:
Imports System.Data
Imports System.Data.SqlClient

I haven’t tested this code yet, but I adapted if from a Visual Basic cheat sheet I downloaded as part of training material from Microsoft. To be 100% honest, I’m not entirely sure the application will accept the parameter added for the message field. Although, if this is a problem, just replace the data type in the database with varchar(1000). This might help to keep the database size down.

So that’s it for this section. I’ll try to get the next one out to you soon. I’m just working through the finer details myself 🙂


Visual Basic Guestbook – Part 1

Welcome to beginning of a series of posts in which I’ll be showing you how to create a very basic vb.NET guestbook which can be used as a stand-alone Windows application or an integrated application for your website.

Before you ask, I’m doing this in a series because there’s a lot to get through and you’ll likely be scrolling for a long time if I were to put it all in 1 post. In part 1, we’ll be creating and populating the database that will be the data source for the guestbook.

You’ll need a version of Visual Studio or Visual Web Developer for a purely web-related application. If you don’t have either of these, you can get the express tools from Microsoft‘s website. Be warned though, these downloads are pretty big!
Alternatively, you can check out my post on MDSN (search for vb.NET Guestbook) in a little while (I hope to have it out by Xmas). I’ll be posting absolutely all the code there. I’m using Visual Studio 2005

Lets get to it!

The first thing you’ll need to do is create a new database. We’ll be using a SQL Server database, so open your Server Explorer (View – Server Explorer). Under Data Connections, add a new connection.
In the dialog that appears, select SQL Server Express 2005 as the database type and enter the server name (by default, [MachineName]\SQLExpress) and enter “Guestbook” as the database name. We’re going to use Windows authentication, so you can test the connection. If it works, great! Click OK and lets move on.

Now it’s time to add a table to the database, so under Data Connections in your Server Explorer, right-click on the Guestbook database that we just created and click “Add a New Table”. The first row we’re going to add to the table will be our Identifier. Call the first row “PostID” and set it up as the identifier by looking for Identity | Is Identity in the bottom section of the screen. Set it as the Primary Key by right-clicking on the row and selecting “Primary Key”. Add the following rows too:
Username – varchar(50) – No Nulls
Email – varchar(50) – Nulls
URL – varchar(50) – Nulls
Message – text – No Nulls

We’re not allowing Nulls on the Username and Message fields because these are going to be required fields. Lastly, lets populate the table with a test entry. Right-click on the table in Server Explorer and select DataSheet View. If you’re prompted to save, Save the file as UserPosts. In the DataSheet view, fill in one or two test entries. This will help us to make sure that our forms are working properly.

It seems a shame to leave it just hanging there, but I’ll be writing again soon to show you how to create the forms. Stay tuned…


Learning .NET by yourself isn’t exactly easy, PHP isn’t any easier…

I’ve been trying to learn .NET for a long time now (3-4 years). Because I haven’t had the bandwidth to download training material or even run through training material online, It’s been really hard to learn even the basics!
Heck, I only got a copy of Visual Studio 2005 about a month ago…

A few months ago, I started spending as much time on IRC as possible, in a channel made for web developers. I thought “gee, this might be an awesome place to pick up some learning aids and training material”. It wasn’t. Little did I know that the channel I’d joined was full of PHP developers who (if it weren’t illegal) would go out and brutally assault or even murder every .NET developer they could find.
So I figured that maybe .NET was too complicated and started learning PHP. I’d never lost my love for .NET though and constantly demonstrated how it was superior to PHP at every opportunity. If you’re into PHP, you should’ve stopped reading about a paragraph ago… It’s only going to get worse for you.

For one thing, there are so many symbols and operators and comparative characters that you need to learn in PHP… EVERYTHING goes in brackets or parenthesis and Lord help you if you missed one out because you’ll never find it.
At Microsoft though, the wonderful people who work day and night to deliver the high standard applications and services we have come to expect from the multi-billion dollar empire, have made Visual Basic as near to english as possible, so it’s really easy to read through and learn.

Eventually after getting my hands on Visual Studio 2005, I found Beth Massi’s Visual Basic Forms over Data video series and am currently going through it when I’ve got time.
I suggest that if you want to find top-notch training aids and tools, check out her blog, you WONT be disappointed.