Wednesday, May 30, 2007

Now for something different!

How are you protecting your PC?


Basic SQL Syntax Troubleshooting

Developing dynamic web and/or desktop applications often involve querying the database for the desired data. One of the problems new programmers often run into is troubleshooting SQL syntax.

Here's a simple tip to help you troubleshoot your SQL syntax:

1. Write the SQL statement out to screen
2. Copy the SQL statement
3. Open the Access database
4. Create a new query
5. View the query text
6. Paste the SQL statement in the query window
7. Try to run the SQL statement

This should give you more info about the error you are running into.

But I am using SQL Server instead of Access database...

Don't worry, if you are running SQL Server or other databases, you can use Access and created linked tables to your database and take it from there.

OSPF - Wild Card Mask

Open Shortest Path First (OSPF) is an open standard, internal routing protocol, capable of supporting large network spanning multiple sites. Routers running OSPF are aware of their network topology; they get update of changes in the network through HELLO packets.

Some of OSPF's strengths include:

It converges quickly, compared to distance-vector protocol.
Routing update packets are small, and only reflect the change (it doesn't send the whole routing table).
It's not prone to routing loops.
It scales very well for large networks.
Bandwidth is taken into account when it selects a link to install in the routing table.
It support Variable-Length Subnet Masks (VLSM)

While many people get confused by the Wild Card Mask that is required in the Network statement, I find it's not that difficult at all.

Let's say you need to advertise the network 172.30.105.84 255.255.255.252 and wants to find the wild card mask. All you have to do is take 255 and subtract each octet of the subnet mask. So in this case you would advertise the network as:

Router(config)# router ospf {process number}
Router(config-router)# network 172.30.105.84 0.0.0.3 area 0


Where do you get the 0.0.0.3? Using the rule above, you take 255 - 255 = 0 (in the first 3 octets) and 255 - 252 = 3 (in the last octet). See, it's not that hard to find the wild card mask at all.

Where do I get 255 from, you ask? Each octet is made up of 8 bits and 255 is the maximum value that 8 bits can hold.

Here are some common OSPF commands that are very useful in checking the status of OSPF configuration:

show ip ospf
show ip ospf neighbor
show ip ospf interface
show ip route ospf


Further readings:
http://www.cisco.com/univercd/cc/td/doc/product/software/ios124/124cr/hirp_r/rte_osph.htm#wp1001842
http://en.wikipedia.org/wiki/Open_Shortest_Path_First

Updating IOS on ProCurve Switches

Updating IOS software on HP's ProCurve switches are pretty simple and straight forward. All you need to do is run a TFTP server, log into the switch, add an IP to the switch, specified a default gateway so the switch can talk to the TFTP server and download the new IOS.

SwitchA# vlan 1
SwitchA# ip address 192.168.1.9 255.255.255.0
SwitchA# exit
SwitchA# ip default-gateway 192.168.1.1
SwitchA# copy tftp flash 192.168.1.8 filename.swi

Note that when you do this the switch will download the new software and reboots itself when it's done processing the file. If you need to update both primary and secondary flash then you should find out whether the switch boots from primary flash or secondary flash and copy the other one first.

Let's say the switch boots from primary flash then the sequence of commands should be:

SwitchA# copy tftp flash 192.168.1.8 filename.swi secondary
SwitchA# y
SwitchA# copy tftp flash 192.168.1.8 filename.swi
SwitchA# y

This will let you update the IOS on both primary and secondary flashes before the switch reboots itself and save you some time. Plus you can script this and cut down the update time. If you do it otherwise, the switch will update primary flash, reboot and then you have to manually update the secondary flash.

Routing Information Protocol (RIP)

Routing Information Protocol (RIP) at one time was one of the most commonly used routing protocols on small, internal network. With the availability of other routing protocol such as IGRP, EIGRP, OSPF, IS-IS, BGP... plus the lack of support for large network the usage of RIP has been decreased and it is considered obsolete. For this reason, it's often referred to as "Rest In Peace" protocol.

Nonetheless, Cisco and other networking vendors are still making RIP & RIPv2 available today in their IOS models. I like RIP for the fact that it's very simple and easy to setup. You can get a small network running RIP up in just a few minutes. RIP is also a very good choice of protocol to get one familiarized with routing protocols.

Besides its infamous Pros and Cons, one lesser known fact about RIP is that you can also use it to load balance your network. However, beware of the fact that RIP does not take bandwidth into consideration when it installs learned routes into the routing table.

So let's say you have two ways to send a packet from A to B and the first path is going through a 128k line while the second goes through a T1 line; RIP will treat both paths equally as if they have the same bandwidth.

Suggested Readings:

http://en.wikipedia.org/wiki/Routing_Information_Protocol
http://www.cisco.com/univercd/cc/td/doc/cisintwk/ito_doc/rip.htm

Programmatically Ping A Networking Device

I would say Ping is one of the most popular software tool used to troubleshoot network issue. When a networking device or server goes down, one of the first things network engineers or system admininistrator do is try to ping it and see if it can be reached.

This blog will show you two ways to ping a device so you can integrate the ping feature into your application.

The first and easiest way to issue a ping command is to call the Ping method in the My.Computer.Network class:

If my.Computer.Network.Ping("www.google.com") Then
MsgBox("device up")
Else
MsgBox("device down")
End If

The drawback of this method is that it only gives you a boolean as the result to indicate whether the device is up or down.

The second way is to call the Ping.Send() method in the System.Net.NetworkInformation namespace which returns a PingReply through which you could get more detailed information about the ping:

Dim myPing As New System.Net.NetworkInformation.Ping
Dim PR As System.Net.NetworkInformation.PingReply
PR = myPing.Send("www.yahoo.com
")
If PR.Status = IPStatus.Success Then
MsgBox("Reply from " & PR.Address.ToString & ": BYTES=" & PR.Buffer.Length & " TIME<" & PR.RoundtripTime & "ms TTL=" & PR.Options.Ttl)
Else
MsgBox(PR.Status.ToString)
End If

There you have it. Two ways of pinging a networking device. I recommend that you further study the PingReply object to get more information from the ping reply.

Parsing Text File

I often come across various postings in different forums asking for simple things like reading information from text file and parsing data from the text. Well, I get kind of tired of answering those question so I decided to write a blog about it and then point them to the blog. So here it is.

Now the text file named C:\Test.txt I have two simple line:

Firstname: Brian
Lastname: Dao

and I want to grab "Brian" & "Dao" out to use for some other purpose. The code is listed below:

Dim mySR As System.IO.StreamReader
Dim myFirstName, myLastName, myTempStr As String
mySR = System.IO.File.OpenText("C:\Test.txt")
If Not mySR.EndOfStream Then
myTempStr = mySR.ReadLine
myFirstName = Mid(myTempStr, InStr(myTempStr, "Firstname:", CompareMethod.Text) + 10)
myTempStr = mySR.ReadLine myLastName = Mid(myTempStr, InStr(myTempStr, "Lastname:", CompareMethod.Text) + 9)
End If
txtOutput.Text = myFirstName & vbCrLf & myLastName
mySR.Close()mySR = Nothing

Note that this doesn't take care of the leading space which could be trimmed by:

myTempStr.Trim

or

myTempStr = Trim(myTemStr)

Another way of accomplishing the same thing would be to call the Replace method and pass in the required parameters. The code sample below show two different ways you can call the Replace medhod.

myFirstName = Replace(myTempStr, "FirstName:", "", , , CompareMethod.Text)
myFirstName = myTempStr.Replace("FirstName:", "")

For those who are new to all this, be sure to look up the following string processing methods: InStr, InStrRev, Replace, Mid.

Adding Attributes To An Existing XML Document

In the previous blog, I've demonstrated how to add a node or an XML element to an existing document. In this blog, I'll introduce two ways to add an attribute to an existing node.

The first way we will use the SetAttributeNode method of the DocumentElement object to add an XMLAttribute as seen below:

Dim objDocument As New XmlDocument
objDocument.LoadXml("<Cars><Make>Toyota</Make></Cars>")
Dim objAttribute1 As XmlAttribute
objAttribute1 = objDocument.CreateAttribute("Type")
objAttribute1.InnerText = "Foreign"
objDocument.DocumentElement.SetAttributeNode(objAttribute1)

The second way is to add an attribute is to call the Append method of the Attributes collection class:

Dim objAttribute2 as XmlAttribute
objAttribute2 = objDocument.CreateAttribute("Body")
objAttribute2.Value = "Sedan"
objDocument.DocumentElement.FirstChild.Attributes.Append(objAttribute2)

and finally we can show the output to the textbox with the statement:

txtOutput.Text = objDocument.InnerXml

In the end, if you run these two code blocks together, your output should look something like this:

<Cars Type="Foreign"><Make Body="Sedan">Toyota</Make></Cars>

Tuesday, May 29, 2007

Adding Nodes using InnerText Property and CreateTextNode Method

In this blog, I'll discuss two simple ways of adding a node to an existing XML document.

Before we do anything, we will need to declare an XMLDocument and call the LoadXML method which takes an XML string as the parameter to populate the document

Dim objDocument As New System.Xml.XmlDocument
objDocument.LoadXML("<Cars></Cars")

Doing this, we will obtain a document with the root node as Cars and no child element.

In the first method, we will create the element using the CreateElement method, then create an XMLText object and set the value using CreateTextNode method, add the text object to the XML element before adding it to the document as follow:

Dim objElement As System.Xml.XmlElement
Dim objText As System.Xml.XmlText
objElement = objDocument.CreateElement("Make")
objText = objDocument.CreateTextNode("Honda")
objElement.AppendChild(objText)
objDocument.DocumentElement.AppendChild(objElement)

'these last too lines produce the same result as the previous two
'objDocument.DocumentElement.AppendChild(objElement)
'objDocument.DocumentElement.LastChild.AppendChild(objText)

The second method is much simpler. We create an element using the CreateElement method of the XMLElement object, set its value in the InnerText property and add it to the document using AppendChild method:

Dim objElement As System.Xml.XmlElement
objElement = objDocument.CreateElement("Make")
objElement.InnerText = "Toyota"
objDocument.DocumentElement.AppendChild(objElement)

There you have two ways of adding a new element to an existing XML document. I prefer the second method as it is much simpler, less coding and easier to understand.

TIPS: You can quickly show the content of the XML document by sending its content to a textbox using the following statement:

txtOutput.Text = objDocument.InnerXml

Introduction to XML

For those of you just starting out with XML, I highly recommend that you check out the video tutorial(s) below:

VB

Working with XML & VB.net

C#

Working with XML & C#

Friday, May 25, 2007

Optimize Your Website For Performance

Performance can affect the number of visitors come to your site. The faster the site load, the better experience the visitors will get and the chances of them coming back will also be higher.

Network latency, congestion, packet drops... are already reducing your application performance. If you, the developer, can do anything to speed up content delivery, by all means, you should do it.

Unfortunately, most developers often neglect to pay attention to this are since it's not something they can really visually see and fix because there is no error that will popup and say "Hey, I am slow... fix me..." or something like that.

Here are a few tips that any developer can use to help speed up their web pages:

Put CSS code at the top of the page: if you put CSS at the top of the page, the browser will read it first. When the browser renders a web page, it doesn't have to search up and down looking for the style rules.

Move JavaScript code down to the bottom of the page: JavaScript’s are mostly run on the client side AFTER the page has been rendered. Moving them to the bottom of the page will allow the browser to render other markup tags first and present the UI to the client faster.

Compress java scripts & remove white space: The browser doesn't care if you name your function with a single character nor does it care if the name is 50 characters as long as they are valid. White spaces might make your code look good but will not help when it comes to speed. The less data your server has to spit out the faster your page will be delivered over the wire.

Remove duplicate and/or unused scripts: If it's not being used, remove it. If anything, it will cause more load on your network and create more confusion having it there when it comes time to troubleshoot some problems.

Do not mix Javascripts and HTML markups: Sometimes, you will need to use Javascripts to produce HTML markups. But try to reduce this to a minimum and let the browser finish one thing before it starts the next one (ie: complete HTML render before executing javascript...)

Move CSS & Javascripts out of HTML markups: Don't make the browser go back and forth between HTML markups and javascripts when it renders the page as there is a performance cost to this.

Add expires header: The browser save the pages onto the hard disk so that it can load the same site faster next time around. If there isn't a need for this, add expires header to it doesn't write the pages to disk.

Disable viewstates: ASP.net pages have viewstate enabled by default which adds a bunch of encrypted code to the page. If viewstate is not required, disable it and it will improve the page performance.
These tips will not significantly improve the performance of your web site as that will also depend upon how you compose your application but it will definitely improve the delivery of the page to the visitors. This is especially true if you have high traffic on your site.

If you get the opportunity, you should examine the HTML output for well known sites like Yahoo or Google and see how they optimize their site for performance. Chances are you will see these tips in action.

Thursday, May 24, 2007

Smurf Attack

A smurf attack is a Denial of Service (DoS) attacked that uses spoofed broadcast ping messages to flood the target system with ping replies. The attack method gets its name after its exploit program.

In this attack, an attacker sends out a large number of ICMP Echo Request packets to IP broadcast addresses with all requests having a spoofed source address of the intended victim. Once the routing device receives this type of request, it will broadcast it to all hosts on its network. When the hosts reply, they will overwhelm the targeted's network with so much traffic that it will effectively shut out the network from the rest of the world.

Using a Cisco router, one can issue the command:

no ip directed-broadcast

to secure their network from this type of attack.

Note that this does not prevent a network from becoming the target of a smurf attack; it just prevent the network from taking part in an attack agains other networks.

Ping Flood Attack

A ping flood is a simple Denial of Service (DoS) attack where the attacker sends a massive number of ICMP Echo Request (ping) packets to the victim in hope of overwhelming the victim and consuming both outgoing and incoming bandwidth on the victim's network. An effective attack could render the victim's network useless.

This type of attack only succeeds if the attacker has more available bandwidth than the victim (like a T3 versus and DSL line) which is very unlikely. To get around this, the attacker normally use an army of computers (a network of computers that attacker has control called zombies or bots) numbered in the hundreds or thousands to attack the victim with their combined bandwidth power.

Defense Your Network

To reduce the effects of ping flood attack, one can use a firewall to inspect the traffic and filter ICMP Echo Request packets. However, doing this can also have its side effects such that it prevents legistimate users from pinging their hosts. For this reason, we can use firewall to authorize ICMP Echo Request packets from legistimate source only.

Reading Text File Into Combo Box

In the previous blog (Reading Text File Using StreamReader Class), I demonstrated the use of StreadReader class to read text file. The System.IO.File class also provide us with a couple of ways to read text file as well.

We will use it's capability in this blog to read the data from text file and load it directly into a combo box.

Code sample:

string[] theStates;
theStates=System.IO.File.ReadAllLines(txtFilename.Text);
cboStates.Items.AddRange(theStates);


A sample application is available here.

Load text file into combobox

Reading Text File Using StreamReader Class

The namespace System.IO has a class called StreamReader which can be used for reading text files.

The StreamReader class provides us with a couple of methods and a property as listed below:

Close: Closes the StreamReader object and the underlying stream, and releases any system resources associated with the reader.

Peek: Returns the next available character but does not consume it.

Read: Reads the next character or next set of characters from the input stream.

ReadLine: Reads a line of characters from the current stream and returns the data as a string.

ReadToEnd: Reads the stream from the current position to the end of the stream.

To read a text file, we need to open it using System.IO.File.OpenText method which returns a StreamReader object. Once we obtain the StreamReader object, just call the appropriate method to pull the data.

C#

System.IO.StreamReader oSR;
oSR = System.IO.File.OpenText(sFilename);
txtOutput.Text = oSR.ReadToEnd();


VB

Dim oSR As System.IO.StreamReader
oSR = System.IO.File.OpenText(sFileName)
txtOutput.Text = oSR.ReadToEnd()


For further reading, please visit the this link.

Sample applications can be downloaded here: VB.net or C#

Monday, May 21, 2007

ViewState and Postback

I see a lot of people having problem preserving the controls's state when they perform postback. Most of these due to the fact they that don't quite understand how the form is processed on postback as seen in the following questions:

http://www.vbdotnetforums.com/showthread.php?t=18985
http://www.vbdotnetforums.com/showthread.php?t=19534

Have a look at this code snippet:

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

If Not IsPostBack Then

....

End If

LoadComboBoxes()

End Sub

IsPostBack will yield a True value if the page was posted back. You can use this to see whether this is the page load or refresh versus a post back and take appropriate action.

Let's say in the method LoadComboBoxes() you query the data from SQL and load that into the combo boxes. If you don't check for postback using IsPostBack, one of two things will happen:

1. If data binding is used on the controls or the Clear() method is called, all the state information gets wiped out and the controls will not retain their values.

2. If the Clear() method is not called then the combo boxes might have duplicate items added everytime you do a post back.

The recommended way for doing this is to move LoadComboBoxes inside the If statement that way it gets called once and also preserves postback data.

Sunday, May 20, 2007

Access IIS application from computers on the same network

A user was having problem accessing his website on the network. The site is working fine from the local machine. However, when he tries to access the same site from a computer on the network, it's not working.

The problem and attempted answers can be viewed in this post. You should read the posts in that forum before continuing on this blog so things would make sense when you read the paragraphs below.

Let's logically work through the posts and try to sort out the problems:

1. Setting up a new website, IP address and port number is not necessary as the original site already working on the machine IIS is running from. Since all the computers are on the same network, you should be able to access it by computer name as well.

2. On Win XP, you can actually host more than one sites and running more than one IP on the same computer. But this won't be discussed in this blog. On top of that, it's not even relevant to the problem we are trying to solve.

3. This shouldn't be security issue also since IIS applications typically run on anonymous account by default and permission is granted when the site is set up; unless you specifically make change to it.

The true answer to this lies in Windows XP Pro SP2's built-in Firewall. Open port 80 in Windows Firewall to allow web traffic should solve this issue. If there are other software firewall running, check and open port 80 as well.

Brian Dao

Short Circuit Evaluation

What is Short Circuit? In the simplest terms, Short Circuit is a control structure put in place to allow the control of the program to be passed onto a different set of instructions while minimizing the evaluation of the code. It operates on booleans or boolean expressions in which the second boolean or boolean expression is only evaluated if the first one does not suffice to determine the value of the entire expression.

Consider the following example:

bool hasMoney = false;
double totalMoney = 0;
if (hasMoney && totalMoney > 5)
{
MessageBox.Show("Buy burger.");
}

If we have no money (hasMoney=false) then there is no need to check and see if the amount of money we have is greater than 5 bucks so the boolean expression on the right hand side of boolean operator "&&" will not be evaluated in this case.

You can really appreciate short circuiting in the following example:

bool hasMoney = false;
double totalMoney = 0;
if (hasMoney && checkTotalMoney())
{
MessageBox.Show("Buy burger.");
}


As you can see, this is just a simple example to demonstrate how short circuit evaluation works but what if in the method checkTotalMoney() you have some lengthy code that goes on to evaluate if you have enough money to pay for the burger and the taxes as well?

Things just get a little bit more complicated and you can see all of that work is skipped if the boolean expression on the left of the operation becomes false. This is important to consider because if you have checkTotalMoney() on the left, the method will be evaluated to determine its value before it can move on to the second expression on the right hand side.

Knowing how short circuit evaluation works and carefully design expressions that use conditional logical operators you can greatly improve your code and boost the performance of your applications by avoiding unnecessary work. You can read more about short-circuit evaluation here.

Friday, May 18, 2007

Converting from Decimal to binary and back

This project was written in C# to demonstrate how to convert data from Decimal to Binary and from Binary back to Decimal number.

Simple Binary Converter

There are a number of ways to convert Decimal to Binary. Here, I used a small function to basically loop through and use division by 2 to convert the decimal number to binary format. Here's the code for the function:

private static string Dec2Bin(Int64 nDecimal)
{
Int64 nBinaryDigit;
string sBinaryNumber = "";
while (nDecimal > 0)
{
nBinaryDigit = nDecimal % 2;
sBinaryNumber = nBinaryDigit + sBinaryNumber;
nDecimal = nDecimal / 2;
}
return sBinaryNumber;
}


To convert Binary number back to Decimal, we can use the built-in function called Convert as seen in the code snippet below:

txtToDecimal.Text = Convert.ToInt64(txtFromBinary.Text, 2).ToString();

You can download the C# project sample here.

Thursday, May 17, 2007

More on Remote Desktop

You can make your HDs available on the RDPed target by going to Options - Local Resources - check Disk Drives option. This will allows you to copy files between your machine and the RDPed machine.

Windows XP SP2 & Windows Server 2003 SP1 has Firewall built in. This will block RDP traffic and on Remote Desktop is disabled by default. When troubleshoot RDP look in these areas first.

RDP runs on port 3389 by default. Most companies deploy firewall to protect their servers. In order to RDP to them, you would need to open traffic on this port (or which ever you choose to run RDP on) to the servers.

Remote Desktop and then some

By default, RDP only allows you to have 2 people login remotely at the same time to work on the server (with Remote Desktop for Administration setting). You can also have another person logon at the console so that makes 3 people can work on the server at the same time.

Here's a little known tip: You can emulate the console login so you don't have to be right in front of the console to login as the 3rd person and have 3 people RDPing at the same time.

To emulate console login, use the following Command line syntax:

mstsc /v:servernameorip /console

You can also shorten /console to /c to save some typing.

If you have to RDP into your servers, it's a good security practice to always try to VPN in and then RDP to the machines if you can. Otherwise, if firewall or router permits, then only allows RPD from known location (your office, your home IPs...). And as the last resort, open RDP port for access from any where.

Centering content on a web page

This is a very simple technique but if you take advantage of it, you could create very attractive web pages with it.

What you need to do is to create a table to wrap the content of your webpage in and set both the width and height properties of the table to "100%". For the horizontal alignment property of the cell, make it "center". You should also set the vertical property to "middle". By default, the browser will set this value to "middle" but it wouldn't hurt to explicitly set it yourself. If anything at all it would only make the code clearer and easier to understand.

Here's the sample code:

<table border="0" width="100%" height="100%">
<tr>
<td align="center" valign="middle">
Your content goes here.
</td>
</tr>
</table>


With this code in place, when you resize the browser, the table size will be updated and the content will be re-render to center it within the page.

Wednesday, May 16, 2007

Using Master Pages in ASP.net Web Applications

Master page helps you to create a consistent look and feel to your site while minimizing the amount of work you have to do. With the introduction ASP.net 2.0 Master Pages, you no longer have to use server side includes to keep the site consistent among different pages. To be able to use and apply master page to your site you first need to create a master page:

1. Right click on the Project
2. Click Add New Item
3. Change the filename as appropriate then click OK to accept
4. Design the layout of the page as you wish and save it

Note that the design in the master page will be applied to all pages that use it except for the content part.

Now that we have a master page, we can start using it. Let's create a web page that would use the master page.

1. Right click on the Project
2. Click Add New Item
3. Select Web Form
4. Check the box called Select Master Page
5. Select the master page you just created and hit OK.

At this point, the code window will open up for you to edit. The new web page doesn't look like a typical web form but instead it will look something like this:

<%@ Page Language="VB" MasterPageFile="~/MasterPage.master" Title="Untitled Page" %><asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
your code goes here
your code goes here
</asp:Content>

When you run the application and/or browsing to the web form, IIS will merge both the master page and the web form to produce the finale code and send it to the browser.

Now that you know how to use master page, you might want to take a look at this blog to learn how to dynamically change master page at run time

Dynamically changing master page on your website

If you notice, you will see that a lot of blog sites out there allow you to create and use different site template. With a click of a button, you can completely change the look and feel of the entire site; including the theme, layout, navigation...

While this can certainly be done using classic ASP, ASP.net master pages have made it extremely easy to set this up. All you have to do is define a couple of master pages before and change MasterPageFile property at run time.

Protected Sub Page_PreInit(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreInit
Page.MasterPageFile = "NewMasterPage.master"
End Sub

In this code snippet, I just assign a new master page to the MasterPageFile property of the Page object during the preinit stage and the site gets a new look.

If you are new to master pages, please have a look at this blog: Using Master Pages in ASP.net Applications.

Sunday, May 13, 2007

Create View Source Link

This blog will show you how to create a hyperlink on a Web page that displays the source code for the current page or another page when the hyperlink is clicked.

The normal Anchor tag when associate with the HREF parameter will cause the browser to pull the URL and display the page when the anchor link is clicked on. However, if you add the "view-source" prefix in front of the link, it will cause the browser to display the HTML source for the page instead of the rendered page itself.

Being able to display the source code of a web page is extremely valuable especially if you want to be able to show your site visitors how to do certain things or teach beginners how to compose HTML documents.

Keep in mind that "view-source" works only on absolute links. Also, if you are trying to access an HTML file through the FILE protocol, you must fully qualify the URL which means you have to include the full path to the file.

Here's the source code to create view source link:

<a href="view-source:http://yoursite.com/FileName.htm">Source Code</a>

Adding Your Logo to a Bookmark

Ever wonder how you could add your logo or icon to your website's URL so that when people bookmark it, they will see the logo along with the URL itself?

It's actually pretty simple to do this. What you need is a 16x16 icon in 16 colors and make a link to it in your webpage.

Here's the sample code for it:

<HEAD>
<LINK REL="SHORTCUT ICON" HREF="http://www.yoursite.com/favicon.ico">
</HEAD>

http://www.yoursite.com/ is the URL to your website and favicon.ico is the name of your icon. You could, of course, use a different name if you want. But keep in mind that even though this might looks good, it is an Internet Explorer specific feature so it won't work on other browsers (or at least at the time this was written)

Saturday, May 12, 2007

Add Multithreading to your VB.NET Applications

VB.NET natively supports free threaded applications. In plain English, this means you can split up your application into multiple threads so that it can do different things at the same time.

There are many situations in which spawning a new thread to run in the background will make your application more responsive and increase its usability. Consider the following example:

Public Class Form1
Private sMessage As String

Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
CountUp()
End Sub

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
MsgBox(sMessage)
End Sub

Private Sub CountUp()
Dim I As Integer
For I = 1 To 10
sMessage = "Iteration #: " & I
System.Threading.Thread.Sleep(2000)
Next
End Sub
End Class

In this simple example, we are just counting from 1 to 10. Note that when each counter is increamented the computer would wait 2 seconds before process the next instruction. So when the routine CountUp is invoked, it would run for approximately 20 seconds. During that time, your application can't do anything else thus you can't click on Button1 to see the message.

To execute code in a thread, we need to use the Thread object that is a part of the System.Threading namespace in the .NET framework classes. The first thing we need to do is to instantiate a new Thread object and pass to it the address of the code block we want to run under the thread and then invoke the Start method.

The example above could be modified as below:

Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim myThread As System.Threading.Thread
myThread = New System.Threading.Thread(AddressOf CountUp)
myThread.Start()
End Sub

Now when you run the application again, it will be more responsive and if you keep clicking on Button1, you will see the message changes as the application runs.

Redirect user to another pager after x seconds using Meta tag

In this blog you will learn how to redirect the users to another page/site after a number of seconds using meta tag.

Sometimes to be able to redirect your site visitors to another page automatically will come in handy, especially when you want to inform them that your site has been "moved" to a different URL so they can update their bookmarks.

To redirect the visitors to another page after a specified number of seconds, all you have to do is add the meta tag <META HTTP-EQUIV=" REFRESH" CONTENT="xxx; URL=newpage.htm"> to the header section of your page where xxx is the number of seconds to delay and newpage.htm is the URL of the page you want the visitors to go to.

Here's the code for it:

<html>
<head>
<META HTTP-EQUIV="REFRESH" CONTENT="3; URL=newpage.htm">
</head>
</html>


In this example, the browser will send the user to newpage.htm after 3 seconds.

Making a window focus - Javascript

At times, you will want to make a page active or re-gain focus after it has been loaded. You probably have seen a lot of these already while surfing the internet, especially from sites that has a lot of pop up ads.

One simple line of Javascript code window.focus(); will make the loading window gain focus. Alternatively, you might want to wait for the window to completely finish loading before you making it gain focus. To do so, simply add window.focus(); in the tag of the document along with the onload event.

Here's the code:

<HTML>
<Body onload="window.focus();">
</HTML>


Another way is to put the script at the very last line of code, just before tag as seen in the code below:

<HTML>
<Body>
...
...
<script language=javascript>
window.focus();
</script>
</Body>
</HTML>

Friday, May 11, 2007

Obtain all IP Addresses

System.Net namespace provides some functions that I find really useful when it comes to networking. You can use the GetHostName method to retrieve the computer name and GetHostEntry to get all IPs assigned to that computer.

Both Visual Basic.net & C Sharp examples are provided below.

VB.net

Private Function GetIPs() As String

Dim strHostName As String = Dns.GetHostName
Dim myipaddress As IPAddress
Dim strTemp As String = "Host Name: " & strHostName & vbCrLf & "IPs: "
Dim ipHostEntry As IPHostEntry = Dns.GetHostEntry(strHostName)

For Each myipaddress In ipHostEntry.AddressList
strTemp += myipaddress.ToString & ","
Next

Return strTemp.Substring(1, strTemp.Length - 2)

End Function

C#

private string GetIPs()
{
string strHostName = Dns.GetHostName();
string strTemp = "Host Name: " + strHostName + "\r\n" + "IPs: ";

IPHostEntry ipHostEntry = Dns.GetHostEntry(strHostName);
foreach (IPAddress myipaddress in ipHostEntry.AddressList)
{
strTemp = strTemp + myipaddress + ",";
}
return strTemp.Substring(1, (strTemp.Length - 2));
}

Failed to access IIS metabase

I got a new laptop recently and tried to setup IIS and transfer existing sites to it. The laptop had typical Windows XP Pro setup with IIS 5.1, Visual Web Developer 2005 Express Edition and Microsoft .NET Framework 2.0 installed.

The sites were copied over and set to use ASP.NET version 2.0.50707 but when launched IIS generated the "Failed to access IIS metabase" error. Poking around on the internet I found some articles referring to things like granting permission to specific user accounts and re-registering ASP.NET... but none of these worked.

I even tried setting up a brand new website and still got the same problem. The only thing that worked was running the web apps as File System but that's not how I want it done.

While poking around with installed components (in Add/Remove Programs) and IIS settings, I suspected that the Microsoft .NET Framework 2.0 got corrupted so I reinstalled it.

Once the framework got repaired, all websites functioned the way they were supposed to. Hope this tip will help you solve problem.

Brian