Back to the beginning (sort of)

The last time I coded an advanced GridView, which was once called Datagrid, was in 2005.

So I’m picking up GridView, and I realise that I’ve forgotten alot more than I first thought.
For instance, in this current project I’m working on, I have two tables with the following:

table 1
sid, schedule, stime, splace, stourid

table 2
tourid, tourname

Basically I wanted to display table 1 in a GridView, but with field stourid I want tourname from table 2 to be displayed instead of stourid.

I forgot that I could join up the two tables using a join, and just display the columns that I wanted in the GridView. Shock! Horror!
Only when I was told this on a forum, the memories of doing it before flooded back. Damn, it hits your self esteem.

Still it’s been many years, I should have kept using the skills, then I wouldn’t have lost it.

I’m going to come across many more situations like this over the coming months.

Using ‘Using’ to Populate a DropDownList

Found a new way to populate a DropDownList using the ‘using’ statement.

DataTable dtTour = new DataTable();
string strConnection = ConfigurationManager.ConnectionStrings["ChinatowndbConnString"].ConnectionString;

using (SqlConnection con = new SqlConnection(strConnection))
{

try
{
SqlDataAdapter adapter = new SqlDataAdapter("SELECT TourId, TName FROM Chinatowndb.dbo.Tour", con);
adapter.Fill(dtTour);

ddlTour.DataSource = dtTour;
ddlTour.DataValueField = "TourId";
ddlTour.DataTextField = "TName";
ddlTour.DataBind();
}
catch (Exception ex)
{
// Handle the error
}

}

// Add the initial item
ddlTour.Items.Insert(0, new ListItem("", "0"));

You can find out more about ‘Using’ here.

Problems with a new install of SQL Server 2008

So it’s been just over a year since my last post in this journal.  To be honest, I haven’t touch a piece of ASP.NET / C# code for a while now, probably not a good thing seeing I spent 7 years of my employed life as a .NET developer.  Still, during the past year or so I was learning some Java (hiss I can hear from your mouths) for a mobile project I wanted to do.  I shelved that around 4 months ago.  Anyhow, back to the topic.

My old Win laptop died on me 3 weeks ago, funny just as I was about to play with .Net.  My new laptop arrived last week, and today I set aside an afternoon to look at the last piece of .Net code I wrote, a C# diary program.  Late last week I rejoined Microsoft Web Sparks programme so to obtain a free copy of Visual Studio 2010 Professional.  That installed fine with a copy of SQL Server 2008 Express.  Today I loaded the diary program, run it, and tried to write a diary entry into the database.  That’s when this funky error message appeared:

DB cannot be opened because it is version 655. This server supports version 649 and earlier. A downgrade path is not supported.

Hang on, this is the same SQL Server 2008 Express I used on my last laptop.  I decided to do a windows update.  The result being that their was a new service pack that was queued to being installed.  So I installed the pack, and tried once more.  No luck, same error message.  A quick web search, I found a post from a user who had a similar error message, just a difference version.  The fix?  To remove all of SQL Server 2008 Express and reinstall.  Okay, I did that.  Installed.  Reboot.  Run diary program again.  This produced a new error message:

Failed to generate a user instance of SQL Server due to a failure in starting the process for the user instance. The connection will be closed.

Right away I thought of my connection string.  But the setup was the same as my old Win laptop, so it should work fine.  A search on StackOverFlow.com lead me to an article that pointed here.

A quick read and executing of the two points listed, run the program, and database connection was successful.

Unfortunately the article doesn’t give a good reason why the second error occurred, I’ve yet to look further into it.  Really my diary program should have run properly without errors of this kind.  Still, it gave me something to write about.

Using SqlParameters()

In my last post I showed you my first ASP.NET code that I programmed, a first for many years.  I also talked about why the code isn’t very friendly, and quite basic which could provide hackers with a way to manipulate the SQL.

Well as promised I’ve rewritten the code and included a SqlParameter to thwart any hacking.

Here is the new code from the code behind:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;

namespace Diary
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Datebox.Text = System.DateTime.Now.ToString();
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            SqlConnection conn;
            SqlParameter DateParam;
            SqlParameter NoteParam;

            conn = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\NoteBook.mdf;Integrated Security=True;User Instance=True");

            SqlCommand MyCommand = new SqlCommand();

            MyCommand.CommandText = "Insert NoteBook (Date, Note) Values (@Datep, @Notep)";
            MyCommand.CommandType = CommandType.Text;
            MyCommand.Connection = conn;

            DateParam = new SqlParameter();
            DateParam.ParameterName = "@DateP";
            DateParam.SqlDbType = SqlDbType.DateTime;
            DateParam.Direction = ParameterDirection.Input;
            DateParam.Value = Convert.ToDateTime(Datebox.Text).ToString("yyyy-MM-dd");

            NoteParam = new SqlParameter();
            NoteParam.ParameterName = "@NoteP";
            NoteParam.SqlDbType = SqlDbType.NVarChar;
            NoteParam.Direction = ParameterDirection.Input;
            NoteParam.Value = Notebox.Text;

            MyCommand.Parameters.Add(DateParam);
            MyCommand.Parameters.Add(NoteParam);

            MyCommand.Connection.Open();
            MyCommand.ExecuteNonQuery();
            MyCommand.Connection.Close();
        
        }

    }
}

The additional of MyCommand , DateParam/NoteParam commands.

The plan is to continue with developing this program in the weeks and months ahead.

Looking at ADO.NET and using ASP.NET 4

ADO.NET is still popular today, even if LINQ to SQL or EF are the newer ‘fun’ technologies to be programming in.

Some developers have the pleasure of coding in new technologies every day.  Others are not so lucky and are stuck in ASP.NET 2.0 land.

I thought my first code appearing in this blog would be ADO.NET compiled using framework 4.0, though of course this could be in any framework.

First off, I needed to think up an idea for an application.  I came up with a simple Note Book application, which basically allow the user to type in his daily thoughts.  So what is the simplest quick and dirty way of coding it.  Remember this is my first attempt, I came up with the following:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="Diary.WebForm1" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
        <asp:Label ID="Label1" runat="server" Text="Note Book"></asp:Label>
        <br />
        <br />
        <asp:Label ID="Label2" runat="server" Text="Date: "></asp:Label>
        <asp:TextBox ID="Datebox" runat="server"></asp:TextBox>
        <br />
        <br />
        Note:<br />
        <br />
        <asp:TextBox ID="Notebox" runat="server" Height="300px" 
            TextMode="MultiLine" Width="800px"></asp:TextBox>
        <br />
        <br />
        <asp:Button ID="Button1" runat="server" Text="Post" onclick="Button1_Click" />
        <br />
        <br />
        <br />
    
    </div>
    </form>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;

namespace Diary
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Datebox.Text = System.DateTime.Now.ToString();
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            SqlConnection conn;
            SqlCommand cmd;
            string cmdString = @"Insert NoteBook (Date, Note) Values ('" + Datebox.Text + "', '" + Notebox.Text + "')";
            conn = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\NoteBook.mdf;Integrated Security=True;User Instance=True");
            cmd = new SqlCommand(cmdString, conn);

            conn.Open();
            cmd.ExecuteNonQuery();
            conn.Close();

        }

    }
}

The database:

image

As you can see with the code it’s very ‘naked’.  There are no fancy error checking routines, validation or verification, and the SQL part could lead to a hacker manipulating your program (more on this in a future post).  Remember it’s just raw code here that assumes the user will enter in some data into the Note field and not tamper with the Date textbox.  The date is automatically entered in the Date box.

When you run the program, the following screen appears:

image

Once the user clicks Post button, the screen will flicker, which means the data has been stored in the database.  Simple.  Though I don’t recommend you code this way for a client or your company, the code does what it needs.

So this is the beginnings of a new system.

ASP.NET 4 Learning Week 8

Now that I’m near the end of Beginning ASP.NET in C# and VB book, I’ve decided to jump the gun and start on Professional ASP.NET in C# and VB.

I read the following:

  • Application and Page Frameworks
  • ASP.NET Server Controls and client-side scripts
    I’m currently reading about Web Server Controls. 
    If you compare both books you can notice how more advanced the Pro book is.  The code listings in the Pro book don’t related to one big web site that you build like you do in the Beginners book.

Angry Birds

This game caught my attention while reading Wired Magazine.  I guess I’ve been living under a rock for the past 6 months as this game is a real winner.

To play it, I had to first update my iOS on my iPod Touch, then download the app.

Well worth the money, if you’ve been hiding like I have, go here to download it.  You won’t regret it!

Angry_Birds

Follow

Get every new post delivered to your Inbox.