Archive for the ‘Programming’ Category

Reading from the Registry in Visual Basic

Thursday, December 30th, 2004 | Programming, Tech

In a previous article I showed you how to save settings in the registry. Now I’m going to show you how to get them back out again.

The basic syntax is as follows.

GetSetting("MyApp", "Category", "InfoName", "DefaultValue")

So lets look at the article on saving information in the registry. I used this example to save a username.

SaveSetting "My App", "Users", "Username", Name1.Text

Now, we’re going to pull this information out and and display the username in the title of the application. This code goes in the Load sub in your application. The name of the form we are working on is irrelevant because I used the term “me” which refers to the current form the code is on.

Me.Caption = "Weclcome " + GetSetting("MyApp", "Users", "Username", "To MyApp")

If no value is found in the registery, the default value is used so if no username was present, the applications title would be.

Welcome To MyApp

If the username in the register was “Jimbo” the applications title would be.

Welcome Jimbo

When using GetSettings you can’t use it on its own. You must use as as part of an equasion such as the example below.

A = GetSettings

You can also do the following.

If GetSettings = a Then do b

It simply supplies one piece of information from the Registry just like a variable.

Trapping errors in Visual Basic

Thursday, December 30th, 2004 | Programming, Tech

If you keep coming up with problems in your applications and you don’t want error messages to be popping up when the user causes an error then all you need to do is add an error handler. In fact, you should be doing this anyway, just in case errors come up.

On Error

There are two options from here. You can either get it to ignore the error or do something else that sorts the error out. If you just want the error to be ignored use this.

On Error Resume Next

This will simply execute the next line of code after one with the error on. This could stop your application doing something important but lets face it, however there are times when you legitimately want to stop an error and ignore it. Usually it is just used then there is a problem such as when you are using the web browser control and a user clicks back when there is no page to go back to. This would normally bring up an error box but by adding in the code it stops this from happening.

Your other alternative is to add in a GOTO command to send the code to do something else if it finds an error. Take a look at this example.

On Error Goto 10
WebBrowser1.GoBack
Exit Sub
10 ' error bit
MsgBox ("Error!")
' some code to sort it out
End Sub

Turning a form button into a link using JavaScript

Thursday, December 30th, 2004 | Programming, Tech

Bored of ordinary links? Then try using buttons. This can work well if there are a series of them lined up in a navigation bar especially if you using image backgrounds or CSS styles to make them look good.

First of all, there is the script that goes into the head of your page.

<script language="JavaScript">
<!--
function goToURL() { window.location = "http://www.hardwaretutorials.com/"; }
-->
</script>

Amazingly simple. Your normal JavaScript tags with a link function. Now for the button which goes in your pages body tag:

<input type=button value="New JavaScripts" onClick="goToURL()" />

Of course, you should never use buttons, or JavaScript links, because they create usability problems. Also, this is also invalid HTML. But it will work in almost all browsers.

Suppressing JavaScript errors

Thursday, December 30th, 2004 | Programming, Tech

What is the most annoying thing you cant think of? Well ok, JavaScript error aren’t that annoying but nobody likes them. What we need is a simple script that stops all the JavaScript erros from appearing. This is a pretty simple script which is short so lets dive straight into the code.

<script>
function stoperror(){
return true
}
window.onerror=stoperror
</script>

Just stick the script into the head tag. Although the above alert method is invalid (no closing quotations), no errors will be generated. This script will suppress all potential errors in a page, so be sure to turn it off while test running a script.

Of course, a much better solution, is to actually write JavaScript that works.

A simple permissions system in ASP

Wednesday, December 29th, 2004 | Programming, Tech

Building an admin log in system is pretty simple for s small site. You don’t need a username so a password is acceptable for log in and you can writee your password into the code. However because it is an admin section it needs to be fairly secure – no having the password available for any old joe to find in the source code.

The solution – a simple server side script. The password will be in the code but because it is server side is will never reach the end user and so they cannot get hold of it.

For this you will need three pages. A main page, a log in and page and log out page.

index.asp
login.asp
logout.asp

Because we need it to be fairly secure I am going to use a session cookie for the password. Let’s start with the main page.

<%
If Session("adminpassword") <> "dog" Then
Response.Redirect ("login.asp")
End If
%>

<html>
<head>
<title>Admin Homepage</title>
</head>

<body>
<p>Welcome to the admin secction.</p>
</body>
</html>

For this I have chosen the pasword “dog.” If this is not present in a session cookie called adminpassword, the user will be redirected to login.aso. Lets look at that now.

<html>
<head>
<title>Admin Log In</title>
</head>
<p>Please enter the admin password:</p>
<form action="login.asp" method="post" name="login_form" id="login_form">
<input name="password" type="password" id="password" size="40">
<input type="submit" name="Submit" value="Log In">
</form>
</body>
</html>

The first thing I have done is to add a form called “login_form” to allow the user to log in. In the form I have placed a text field called “password” and a submit button so they can type in the password and click submit to log in. This sends the user and the form variable, “password” to login.asp (the same page but reloaded). Now we need to add some server side scripting to the top of the game above the <html> tag.

<%
' checks to see if the password has been submitted
If Request.Form ("password") <> "" Then
' it has so writes in the session cookie
Session ("adminpassword") = Request.Form("password")
' if the user's password is correct they should now be able
' to gain access to the main page
' if they entered an incorrect password they will be
' redirected back here. Because the form variable
' is not sent when they are redirected back here
' they will not be redirected back to index.asp
Response.Redirect ("index.asp")
%>

If the password is incorrect, eg, they entered a password that is different from “dog” eg they entered “cat” it will still be saved in the session variable and the user will still be redirected to index.asp, but because the password is not “dog” they will be redirected back here again.

The fact that the incorrect password is saved in the session cookie allows us to give the user some more information when they are redirected back to login.asp because index.asp won’t give them access.

<%
' if the user is on login.asp but still has a password
' in the session cookie, they must have entered
' and incorrect password
If Session ("adminpassword") <> "" Then
%>
<p>You entered an incorrect password.</p>
<%
End If
%>

You can then insert the script that we placed at the top of index.asp to all the pages you want protecting. To save yourself having to change the script on every protected page when you want to change the password, you could also save the script, by itself, in a separate file and use file include to all the pages you want protecting.

<!--#include file="passwordcheck.asp" -->

You can then just update the script in passwordcheck.asp and all the protected pages would now use the new password.

Finally we need to create a log out page for the user to logout, to stop anyone else getting in after the user is done. This maybe not be needed if you are on a home pc which nobody else has access to but you might want to build one anyway. The log out page is amazingly simple.

<%
Session.Abandon ()
Response.Redirect ("index.asp")
%>

This should log the user out. If the user has not been logged out for some reason they will know because they will gain access to index.asp when they are redirected to it. If the user has been logged out successfully, index.asp will redirect them to login.asp and so they will know they have been logged out.

Now just o make it easier on you I will include the full source code including links, html and asp code, ready for you to copy and paste into your text editor and save as the appropriate files.

index.asp

<%
If Session("adminpassword") <> "dog" Then
Response.Redirect ("login.asp")
End If
%>

<html>
<head>
<title>Admin Homepage</title>
</head>

<body>
<p>Welcome to the admin secction.</p>
<p><a href="logout.asp">Click here to log out.</a></p>
</body>
</html>

login.asp

<%
' checks to see if the password has been submitted
If Request.Form ("password") <> "" Then
' it has so writes in the session cookie
Session ("adminpassword") = Request.Form("password")
' if the user's password is correct they should now be able
' to gain access to the main page
' if they entered an incorrect password they will be
' redirected back here. Because the form variable
' is not sent when they are redirected back here
' they will not be redirected back to index.asp
Response.Redirect ("index.asp")
%>

<html>
<head>
<title>Admin Log In</title>
</head>
<p>Please enter the admin password:</p>
<form action="login.asp" method="post" name="login_form" id="login_form">
<input name="password" type="password" id="password" size="40">
<input type="submit" name="Submit" value="Log In">
</form>
</body>
</html>

logout.asp

<%
Session.Abandon ()
Response.Redirect ("index.asp")
%>

A simple hit counter in ASP

Wednesday, December 29th, 2004 | Programming, Tech

This tutorial will show you how to build a simple hit counter. It does not use any SQL or databases; it stores the hits in a text file.

Allou need to create for this script is your ASP file and a text file. In the text file, simply enter the number 0 and save it in the same directory as count.txt. Take a look at the basic source code.

<%@ Language="VBScript" %>
<% Response.Expires= -1
Response.AddHeader "Cache-Control", "no-cache"
Response.AddHeader "Pragma", "no-cache" %>
<%
if Session("ct") = "" then
fp = Server.MapPath("db\count.txt")
Set fs = CreateObject("Scripting.FileSystemObject")
Set a = fs.OpenTextFile(fp)
ct = Clng(a.ReadLine)
ct = ct + 1
Session("ct") = ct
a.close
Set a = fs.CreateTextFile(fp, True)
a.WriteLine(ct)
a.Close
Set a = Nothing
Set fs = Nothing
else
ct = Clng(Session("ct"))
end if 
%>

Now lets break it down into three sections.

<%@ Language="VBScript" %>

This just states that the page is a VB script page.

<% Response.Expires= -1
Response.AddHeader "Cache-Control", "no-cache"
Response.AddHeader "Pragma", "no-cache" %>

This section stops the user refreshing the page to clock up hits.

<%
if Session("ct") = "" then
fp = Server.MapPath("count.txt")
Set fs = CreateObject("Scripting.FileSystemObject")
Set a = fs.OpenTextFile(fp)
ct = Clng(a.ReadLine)
ct = ct + 1
Session("ct") = ct
a.close
Set a = fs.CreateTextFile(fp, True)
a.WriteLine(ct)
a.Close
Set a = Nothing
Set fs = Nothing
else
ct = Clng(Session("ct"))
end if 
%>

This is the main section which adds the hits.

fp = Server.MapPath("count.txt")

This tells the server where to find the file. You can modify the file location by changing count.txt. So for instance if you wanted to to be called hitcounter.txt and in the directory db you would use:

fp = Server.MapPath("db\hitcounter.txt")

All you have to do is alter the file path in the quote marks.

Set fs = CreateObject("Scripting.FileSystemObject")
Set a = fs.OpenTextFile(fp)
ct = Clng(a.ReadLine)

This section opens the file using FileSystemObject and reads the first line. It then sets the variable ct to the amount of hits it has already had.

ct = ct + 1

This line adds one hit to the total number of visitors.

Session("ct") = ct
a.close

This part saves a session variable as the new click through with the new amount of visitors and closes the text file.

Set a = fs.CreateTextFile(fp, True)
a.WriteLine(ct)
a.Close

This code creates a new text file over the old one and adds in the new amount of visitors to it. Then it closes the text file.

Now you have a working hit counter. All you need to do is add the hit counter into your page:

You are a visitor number <%=ct%>!

This would display the amount of visitors. Now to save confusion, here is the full source code for the page:

<%@ Language="VBScript" %>
<% Response.Expires= -1
Response.AddHeader "Cache-Control", "no-cache"
Response.AddHeader "Pragma", "no-cache" %>
<%
if Session("ct") = "" then
fp = Server.MapPath("db\count.txt")
Set fs = CreateObject("Scripting.FileSystemObject")
Set a = fs.OpenTextFile(fp)
ct = Clng(a.ReadLine)
ct = ct + 1
Session("ct") = ct
a.close
Set a = fs.CreateTextFile(fp, True)
a.WriteLine(ct)
a.Close
Set a = Nothing
Set fs = Nothing
else
ct = Clng(Session("ct"))
end if 
%>
<html>
<body>
You are a visitor number <%=ct%>!
</body>
</html>

ASP Request function

Wednesday, December 29th, 2004 | Programming, Tech

The request function, surprisingly, requests a value. This could be a URL variable, form variable, or some other value. For example if you were at the url.

http://www.somepage.com/home.asp?ID=23

You would use the following code in your script.

Request.QueryString("ID")

The line would then return the value 23.

An example of where this can be used is on the M World News channel. The news is stored dynamically in a database so when you click on a link to the full story from the news homepage you are taken to a dynamic page which selects the story based on the ID of the story you want passed to the page as a url variable. For example the link could be as follows.

http://www.mworld.us/news/story.asp?ID=52

Examples of use

Request.QueryString("SomeURLVariable")
Request.Form("SomeFormElement")
Request.Cookies("SomeCookie")

Using Server.MapPath in ASP

Wednesday, December 29th, 2004 | Programming, Tech

Server.MapPath is used to create a file path from a virtual path.

Here’s a typical DNS-less database connection:

Connection = "Driver={Microsoft Access Driver (*.mdb)}; DBQ=C:\wwwroot\users\someaddress\db\data.mdb"

This isn’t much good though if you don’t know the full file path and if you are using a web host the chances are that you won’t know it. So you can use Server.MapPath instead.

Lets say that database is on the internet at the following address. Not that it is a good idea to have your database web accessible of course.

http://www.someaddress.com/db/data.mdb

Instead of having to use the file path as the top you could use a virtual path:

Connection = "Driver={Microsoft Access Driver (*.mdb)}; DBQ=" + Server.MapPath("/db/data.mdb")

This would get the server to “map” a file path to the database from the virtual path you give it. Notice that after DBQ= the tag (“) is closed as you don’t want the server to think + Sever.Map… is part of the file path.

Accessing MySQL with ASP

Tuesday, December 30th, 2003 | Programming, Tech

Being an active server page coder by nature, all my sites are in ASP. So eventually I hit a problem – two sites want to use the same Access database but they are on different hosts. Therefore I decided it would be best to use a MySQL database that they could share by making remote connections.

Why use MySQL?

The main advantage is as I have already mentioned, having a central MySQL database allows you to connect all your sites directly to it and access the information. There are ways to do this in Microsoft Access but they are patchy at best. The other option would be to use MS SQL server although this doesn’t come cheap from any host.

Changing the code

Let’s say for example I have a MySQL database on a linux hosting account at www.examplelinux.com. And I have a website at www.examplewindows.com that I want to connect with. Luckily connecting to MySQL is similar to any other connection except we just need to make a few changes.

The first is obvious; the connection script needs to be changed as we are accessing MySQL rather than an Access database. The second are certain changes in the scripts to make sure we don’t end up with any MySQL errors.

A typical DNS less connection would be something like:

Driver={Microsoft Access Driver (*.mdb)}; DBQ=" + Server.MapPath("/Conndb/springer1.mdb")

Whereas a connection to MySQL would look more like:

Driver={MySQL ODBC 3.51 Driver}; Server=examplelinux.com; Database=dbname; UID=username; PASS=password

To do this your server needs to have the MySQL driver on it. You can download it from http://www.mysql.com/downloads/index.html. You can also use a DNS connection if you have one which makes things considerably simpler:

DSN=linuxexampledns

All you need to do is replace the connection line you currently use with the new one modifying the username, password and name of the database you are going to use on your target server.

Further modifications

To make the ASP code work with MySQL there are a few other modifications you need to make with your code. The problem arises from the use of the ‘ character. Where Access is ok with it, MySQL will bring up a nice big error message.

Luckily a bit of PHP style code can come to the rescue. If you are familiar with PHP, you will know you can remove the significance of a character using \ before it. Therefore a quick replace function does the trick

Replace(string, "'", "\'")

So for instance a select command would go from:

SELECT * FROM hobbies WHERE firstname = '" + (users.Fields.Item("firstname").Value) + "' ORDER BY name ASC

And changed to:

SELECT * FROM hobbies WHERE firstname = '" + Replace((users.Fields.Item("firstname").Value) ,"'","\'") + "' ORDER BY name ASC

Setting up the server

Once the modifications to the code have been made you can get on with setting up the server to accept the requests. First of all you need to allow the scripts to access the database.

In CPanel goto MySQL Database and scroll down to access hosts: then add in the IP address of www.windowsexample.com. If you can’t find it out, simply run the scripts and it will bring you up an access denied message containing the IP address you are trying to access the database from.

In Direct Admin goto MySQL Databases, click on the database and then you can enter the IP address in to the access hosts form near the bottom. If you can access the privileges section in phpMyAdmin directly you can also do it from there as you can set for each user what access host the user can use.

The only other problem is getting the contents of your Access database to your MySQL server. The easiest way I found to do this way to set up a DNS connection to the MySQL server on my local machine, though you may be able to do this directly to the server providing you grant yourself access, and then going into Access and Exporting it.

File > Export then open the drop down menu at the bottom and and scroll to the bottom of the list until you see ODBC Databases (). This will close the export window and prompt you to enter the name of what you want to call it when you export it. Most likely it will be best to leave the default here.

Then it will come up with a box asking you to select a data source. Select the machine data source tab and find your DNS connection on the list then click ok and your done.

Conclusion

Switching your database from Access to MySQL is a hassle – you need a Linux server, code changes and connection scripts. However if your sites need to share a database its a far cheaper option that using MS SQL.

Printer friendly pages

Saturday, October 18th, 2003 | Programming, Tech

There is nothing like reading an article on the website and finding it one of the best you have ever read – you immediately want to show to it other people. You flick the switch on your printer to on, hit Control + P and prepare for it to emerge. But what do you get? A mess of DHTML, adverts or half the text missed off the edge of the page.

You could always hope the visitor turns their page to landscape but with the length web pages usually turn out like it is not very likely. Save them the trouble of having to print selection or copy and paste into a word processing package by making your pages printer friendly for them to print straight from.

Making them friendly in the first place
There are two main ways to allow visitors to print the pages easily. The first is to make the original web page with the article or content on, the right size to be able to print. For liquid width sites this is ok as long as they can condense down although for fixed width sites this is not as easy.

Generally you have a width of about 600 pixels, which the users printer will print. This is good if you have a navigation or sky scraper advert down the site taking the last 200 pixels of your page as the user does not need these printing. Although if your article goes all the way to the edge its time to rethink the design.

One way of getting round this would be to have a link, which chances the width of the page. The user clicks a link to say somepage.php?mode=printer. Then you could have something, which says if the mode is set to printer the page width is altered to 600 rather than 800 pixels using server side scripting. This could also be done to a certain extent using JavaScript so the page will not always have to be reloaded although in some browsers it may have to be and there is more chance of it going wrong.

The printer friendly page

This is a more common solution to the problem of visitors not being able to print. All you have to do is set up a separate page without all your adverts, logos and navigation, which is less wide or uses a liquid width so that the user can print this.

Generally you wont want to include adverts on this page, otherwise visitors may not use it at all as they can remove the ads themselves using print selection or copy and pasting the text. However you may want to include your logo and visitors won’t mind and it increases branding when the article is passed around.

If your articles are static then you may end up creating a separate page for each of these but if your articles are dynamic, most likely stored in a database you will simply be able to make a dynamic page just like your main article page for the printer friendly page and link them together.

Making it usable

Whatever solution you use you may want to include a print link to. This will encourage users to print the article simply by clicking the link, as their finger will already be on the mouse button, so users who would not normally print the article may give it a click.

Another good point about users printing the whole page rather than copy and pasting the text into a word processor is that the URL of the page will be at the bottom so other people who read it will see it and when the visitor looks at it later they will remember your website.