Archive for the ‘Programming’ Category

.Net HowTo - Database Connection Errorhandling

Tuesday, July 12th, 2005

When connection to a database, or even when executing queries, inserts, updates, and so forth, one should ALWAYS attempt to catch the SQL exceptions apart from the regular catching. This provides more detailed feedback than the regular exception handling:

        Try           'SQL processing here       Catch objError As SqlException           'this will catch all errors on the SQL side (SELECT, INSERT, UPDATE, etc.)           'note that this does not handle errors opening and closing the database           MessageBox.Show(objError.Number + ": " + objerror.Message)       Catch objError As Exception           'errors when opening and closing the database are handled here           MessageBox.Show(objError.ToString + ":" + objError.Message)       End Try

.Net HowTo - Connection Events

Tuesday, July 12th, 2005

Weirdly enough, in the new .Net it’s OK to close a closed connection (can’t close anything you haven’t opened?!), but it raises an error if you try to open an open connection! In my opinion you shouldn’t rely on being able to close a closed connection in your programming,

    Private Sub btnOpen_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOpen.Click        Try            If (objConn.State <> ConnectionState.Open) Then                objConn.Open()            End If        Catch objError As Exception            MessageBox.Show(objError.Message)        End Try    End Sub

    Private Sub btnClose_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClose.Click        Try            If (objConn.State <> ConnectionState.Closed) Then                objConn.Close()            End If        Catch objError As Exception            MessageBox.Show(objError.Message)        End Try    End Sub

Here objConn is a SQLConnection object from the toolbar dragged onto a webform. The two functions are fired by two buttons on the windows from denoting an open event and a close event.

.Net HowTo - Making the right Connectionstring

Tuesday, July 12th, 2005

In order to correctly connect to your database, you’ll need a connectionstring. There are so many different types of connections you can create, that you might be stumped for a bit if you’re required to create a strange connection. Well, here’s the solution to all that: this website lists all (or very nearly) of the possible connection strings you could ever want: http://www.carlprothman.net/Default.aspx?tabid=81 or http://www.connectionstrings.com. All you need to do now is look up what you need to connect to, and this site provides how you need to create your connection string! Nifty!

.Net HowTo - Saving Query results as XML

Tuesday, July 12th, 2005

A very powerful and extremely simple tool to convert your SQL results into an XML file is the following:

    Dim objDS As New DataSet

    Private Sub btnLoad_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnLoad.Click        Dim objConn As New SqlConnection        Dim objDA As SqlDataAdapter

        Try            objConn.ConnectionString = "server=(local);database=northwind;integrated security=SSPI"            objConn.Open()            objDA = New SqlDataAdapter("SELECT * FROM customers ORDER BY companyname", objConn)            objDA.Fill(objDS, "customers")            objConn.Close()            dgData.DataSource = objDS.Tables("customers")        Catch objError As Exception            MessageBox.Show(objError.Message)        End Try    End Sub

    Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click        Try            objDS.WriteXml("c:projectscustomers.xml")        Catch objError As Exception            MessageBox.Show(objError.Message)        End Try

Using this method you can save any table in your dataset to an XML file. This can come in handy when transfering data to clients, or even to coworkers. Not to mention to make a backup of your data before making changes.

.Net HowTo - Using Disconnected Data from a Database

Tuesday, July 12th, 2005

In order to use data while disconnected from a database, it needs to be loaded in one form or other from the database and kept in memory or stored into a different object. The following code illustrates how to do this by using a datagrid on a windows form. This takes the previous connection how-to a step further, because we are closing the connection after the info is loaded, then allowing for changes to the data in the dataset, and afterwards we can save the newly changed data after opening a new connection again. This example is using a windows form with a datagrid (dgData), a button to load the data (btnLoad) and a button to save the data (btnSave):

    Dim objDS As New DataSet

    Private Sub btnLoad_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnLoad.Click        Dim objConn As New SqlConnection        Dim objDA As SqlDataAdapter

        Try            objConn.ConnectionString = "server=(local);database=northwind;integrated security=SSPI"            objConn.Open()            objDA = New SqlDataAdapter("SELECT * FROM customers ORDER BY companyname", objConn)            objDA.Fill(objDS, "customers")            objConn.Close()            dgData.DataSource = objDS.Tables("customers")        Catch objError As Exception            MessageBox.Show(objError.Message)        End Try    End Sub

    Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click        Dim objConn As New SqlConnection        Dim objDA As SqlDataAdapter        Dim objBuilder As SqlCommandBuilder

        Try            objConn.ConnectionString = "server=(local);database=northwind;integrated security=SSPI"            objConn.Open()            'the following is being used as a template to create the update, delete, and instert commands            objDA = New SqlDataAdapter("SELECT * FROM customers ORDER BY companyname", objConn)            objDA.Fill(objDS, "customers")            objBuilder = New SqlCommandBuilder(objDA)            objDA.DeleteCommand = objBuilder.GetDeleteCommand            objDA.InsertCommand = objBuilder.GetInsertCommand            objDA.UpdateCommand = objBuilder.GetUpdateCommand

            objDA.Update(objDS, "customers")            objConn.Close()        Catch objError As Exception            MessageBox.Show(objError.Message)        End Try    End Sub

This scenario comes in handy when developing applications that remote users may use. However, the inherent complexity comes into play when the user connects again and attempts to update records that have been changed since they were originally downloaded by this user.

.Net Howto - Connecting to a Database

Tuesday, July 12th, 2005

The following example illustrates how to connect to a database using a connectionstring. We’re also using a datareader to access multiple rows, and a scalar to access a single value.

        Dim objConn As New SqlConnection        Dim objComm As New SqlCommand        Dim objReader As SqlDataReader        Dim strText As String

        Try            objConn.ConnectionString = "server=(local);database=northwind;integrated security=SSPI"            objConn.Open()            MessageBox.Show("Connection Success!")            objComm.Connection = objConn            objComm.CommandType = CommandType.Text            objComm.CommandText = "SELECT @@VERSION"            MessageBox.Show(objComm.ExecuteScalar())            objComm.CommandText = "SELECT companyname FROM customers ORDER BY companyname"            objReader = objComm.ExecuteReader            'read must be done first to prime the data reader.             'if trying to access item(0) prior to doing a read an exceptionwill occur!            While objReader.Read                strText += objReader.Item(0) + NewLine            End While            MessageBox.Show(strText)        Catch objError As Exception            MessageBox.Show(objError.Message)        End Try

As you can see this is a fairly simple example using the Northwind database. More info will be soon to come on creating your own connectionstrings, etc.

Windows Non-Form / Console .NET Application - Sub Main()

Saturday, July 2nd, 2005

While working on my latest .NET project I ran into the problem of how to specify the program to use Sub main() as the startup procedure. I had originally created my project as a Windows Form application, so the sub main() settings were not set by defeault.

The first thing I did was to change the project preferences (Project > Properties > General) settings Startup Object to Sub Main. This was a given. Next I created a new class containing my Sub Main(). I could not get the program to start up in this manner.

After some googling I found that the Sub Main() needs to be placed inside a module in the following manner:

ModuleSub Main()        [...]End SubEnd Module

After that everything worked like a charm.

PHP - File Uploading How-To

Tuesday, March 22nd, 2005

Use the following code in your target page from the file upload form to handle saving the file on the server:

//set the destination directory$uploaddir = '/var/www/uploads/';//set the destination file name$uploadfile = $uploaddir . $_FILES['userfile']['name'];print('');//move file to designated directory, then test if successfulif (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)){    print('File is valid, and was successfully uploaded. ');    print('Here's some more debugging info:n');    print_r($_FILES);}//show if problems occurelse{    print('Possible file upload attack! Debugging info:n');    print_r($_FILES);}print('');

Link: http://www.php.net/features.file-upload

Cross-Plattform Versioning System: In the search for an alternative to VSS!

Tuesday, March 22nd, 2005

In a cross-plattform development environment, something that only works in windows is terribly restrictive. Its even worse, if there are no Linux clients available. In this case the dilema is Visual Source Safe. While a good package overall, I have identified the following shortcomings:
- No good rollout process.
- Server application is Windows only.
- Client application is Windows only. I haven’t been able to find a Linux client for this.
- In order to access the VSS database on a remote computer, you need to have VSS installed locally.

What I am looking for:
- A cross-plattform solution that provides clients for at least Windows and Linux.
- The server application itself can run on a windows box, but a solution that caters to at least Linux and Windows is preferrable.
- A system that supports incremental rollouts and patches, concurrent versioning, multi-checkout capable, …

So far I’ve come accross the following:
- JEDI CVS
- CVSGUI: graphical frontends for various CVS-based systems.
- TortoiseCVS: a windows client for CVS.
- GNU CVS: opensource CVS system.

Research to be continued on the various available packages…