Thursday, May 31, 2007

VB.NET: The Number Of Days Between Dates

Yay! My code works...

'Retrieve the earliest & latest date recorded in info.csv to get the range of days covered
Sub GetNumberOfDays()

Dim begDate As DateTime
Dim endDate As DateTime
Dim numRows As Integer
Dim timeDiff As TimeSpan
Dim numDays As Integer

Try
begDate = CDate(dgvReport.Rows(0).Cells(0).Value)
numRows = dgvReport.RowCount
endDate = CDate(dgvReport.Rows(numRows - 2).Cells(0).Value)
timeDiff = endDate.Date - begDate.Date
numDays = timeDiff.Days
Catch ex As Exception
MessageBox.Show(ex.ToString)
End Try

MessageBox.Show(CStr(numDays))

End Sub

My tribute to TechRepublic for passing on the tip. Thanks Irina Medvinskaya!

Tuesday, May 29, 2007

How to set up a static IP address on a Windows XP computer

Source: PortForward.com

It is very important to setup a static ip address, if you are going to use port forwarding. When you have port forwarding setup, your router forwards ports to an ip address that you specify. This will probably work when you initially set it up, but after restarting your computer it may get a different ip address. When this happens the ports will no longer be forwarded to your computer's ip address. So the port forwarding configuration will not work.

What is an ip address?
IP addresses are four sets of numbers separated by periods that allow computers to identify each other. Every computer has at least one ip address, and two computers should never have the same ip address. If they do, neither of them will be able to connect to the internet. There is a lot of information at the following link. You don't need all of it. But if you want to know more about how networks work, you'll find it there. For more information on ip addresses, subnets, and gateways go here

Dynamic vs Static IPs
Most routers assign dynamic IP addresses by default. They do this because dynamic ip address networks require no configuration. The end user can simply plug their computer in, and their network will work. When ip addresses are assigned dynamically, the router is the one that assigns them. Every time a computer reboots it asks the router for an ip address. The router then hands it an ip address that has not already been handed out to another computer. This is important to note. When you set your computer to a static ip address, the router does not know that a computer is using that ip address. So the very same ip address may be handed to another computer later, and that will prevent both computers from connecting to the internet. So when you asign a static IP addresses, it's important to assign an IP address that will not be handed out to other computers by the dynamic IP address server. The dynamic IP address server is generally refered to as the dhcp server.

Setting up a static ip for windows XP.

If you have a printer, before you begin print out this page!
Step 1:
Open up the start menu, and click Run. You should now see the following window.

Step 2:
Type cmd in the Open: box, and click Okay. The will bring up a black command prompt window.


Step 3:

The command prompt may look different on your screen, but it doesn't really matter. Type ipconfig /all in that window, and then press the enter key. This will display a lot of information. If it scrolls off the top you may need to enlarge the window.


Step 4:

I want you to write down some of the information in this window. Take down the IP address, Subnet Mask, Default Gateway, and Name Servers. Make sure to note which is which. We are going to use this information a little bit later.

The name server entries are a bit complicated. Name Server is just another name for DNS(domain name server) server. Some router's act as a proxy between the actual name servers and your computer. You will know when this is the case, because the Default Gateway will list the same ip address as the Name Servers entry. We need to have the correct Name Server IP addresses. If we do not, you will not be able to browse the web. There are a couple ways to get these. The first way is to log into your router's web interface, and look at your router's status page. On that page you should see an entry for DNS Servers, or Name Servers. Write down the ip adresses of your Name Servers. Another way to get the correct Name Servers to use, is to give your ISP a call. They should know the ip addresses of your Name Servers right off. If they ask you why you need them, you can tell them you are trying to setup a static IP address on your computer. If they try to sell you a static external ip address, don't buy it. That's an entirely different thing that what you are trying to setup.

Type exit in this window, then press the enter key to close it.

Step 5:
Once again open the start menu. This time click Control Panel.


Step 6:

Double click Network Connections.


Step 7:

You may have several network connections in this window. I want you to right click on the one you use to connect to the internet. Then click properties.

If you are unsure of which one that is, right click it and then click disable. Open a new copy of your web browser? Did it open a webpage? If you can not, then you've found your internet connection. Close that browser window. Go ahead and right click the network connection again and then click enable. Once again open up a new web browser. You should see a webpage. Close the browser window. Right click on the network connection and click properties at the bottom.


Step 8:

You should now have the above window on your screen. Click the properties button to open up the properties window of this internet connection.


Step 9:

Click Internet Protocol(TCP/IP) and then the Properties button. You will now see the following screen.


Step 10:

Before you make any changes, write down the settings that you see on this page. If something goes wrong you can always change the settings back to what they were! You should see a dot in the Obtain an IP address automatically box. If you do not, your connection is already setup for a static ip. Just close all these windows and you are done.

I realize this guide is fairly difficult to understand, so I've added a new section here that will help you determine exactly what ip address to set your computer to.

Enter your computer's default gateway:
Enter your computer's current IP Address:

First Computer's Static IP:
Second Computer's Static IP:
Third Computer's Static IP:
Forth Computer's Static IP:
Fifth Computer's Static IP:
Click the Use the following IP Address. Now pick one of the static ip addresses listed above and then enter it into the IP Address box in the Internet Protocol TCP/IP Properties page.

Put the subnet mask we previously found in the subnet mask section. The default gateway should go into the Default gateway box. Enter the dns servers we prevoiusly found into the two DNS Server boxes. Click okay all the way out of this menu.

If you find that you can not pull up webpages, the problem is most likely the dns numbers you entered. Give your ISP a call, and they will be able to tell you which dns servers to use. This is a question they answer all of the time. They will be able to tell you what you should use right away.

That's it you should be done! If you can't connect to the internet go back and change your configuration back to what it originally was.

Monday, May 28, 2007

VB.NET: Data Grid View & Reading From CSV File

Oh my goodness. It's really been ages since I did VB programming. I am so so lost! Today's code:

Public Class frmReport

Private Sub btnGenerateReport_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnGenerateReport.Click

'Datagridview dgvReport settings
Me.Controls.Add(dgvReport)

dgvReport.ColumnCount = 5
With dgvReport.ColumnHeadersDefaultCellStyle
.ForeColor = Color.White
.Font = New Font(dgvReport.Font, FontStyle.Bold)
End With

With dgvReport
.Name = "dgvReport"
.Location = New Point(8, 8)
.Size = New Size(500, 250)
.AutoSizeRowsMode = _
DataGridViewAutoSizeRowsMode.DisplayedCellsExceptHeaders
.ColumnHeadersBorderStyle = DataGridViewHeaderBorderStyle.Single
.CellBorderStyle = DataGridViewCellBorderStyle.Single
.GridColor = Color.Black
.RowHeadersVisible = False

'Define top column names in dgvReport
.Columns(0).Name = "Date-Time"
.Columns(1).Name = "Action"
.Columns(2).Name = "Area"
.Columns(3).Name = "Section"
.Columns(4).Name = "Link"
.Columns(4).DefaultCellStyle.Font = _
New Font(Me.dgvReport.DefaultCellStyle.Font, FontStyle.Italic)

.SelectionMode = DataGridViewSelectionMode.FullRowSelect
.MultiSelect = False
.Dock = DockStyle.Fill
End With

'Open file info.csv & read
Using MyReader As New Microsoft.VisualBasic.FileIO.TextFieldParser _
("C:\Susanna's Work Stuff\Projects\DiGi\DiGi MDL\2007_05_28\reports\reports\bin\info.csv")

'Specify that reading from a comma-delimited file
MyReader.TextFieldType = FileIO.FieldType.Delimited
MyReader.SetDelimiters(",")
Dim currentRow As String()
While Not MyReader.EndOfData
Try
currentRow = MyReader.ReadFields()
With Me.dgvReport.Rows
.Add(currentRow) 'Add new row to dgvReport
End With
Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
MsgBox("Line " & ex.Message & _
"is not valid and will be skipped.")
End Try
End While
End Using

End Sub

End Class

Got the chunk off 2 different MSDN pages. Thankfully it worked, after a bit of tweaking! Phew! All in a day's work...

VB.NET Classes

Creating classes in VB.NET:

homeandlearn

vbdotnetheaven

developerfusion

Friday, May 25, 2007

Using Data Readers, SQL Server

http://www.startvbdotnet.com/ado/sqlserver.aspx

http://www.java2s.com/Code/VB/Database-ADO.net/SqlDataReader.htm

Need to find out:
- what ORM is
- difference between SqlDataReader & SqlDataAdapter in VB.NET

VB.NET: Web Methods, Sessions, Database Operations

Some code I wrote that I want to remember:

<webmethod(enablesession:=true,Description="Post feedback on session id, start time, end time")> _
Public Function PostFeedback() As String
Dim sID As String = HttpContext.Current.Session.SessionID
Dim connString As String = System.Web.Configuration.WebConfigurationManager.ConnectionStrings.Item(connStringID).ConnectionString
Dim myConn As SqlConnection = New SqlConnection(connString)
Dim insertCommand, selectCommand, updateCommand As SqlCommand
Dim myReader As SqlDataReader
Dim end_time As DateTime
Const delay As Single = 10
Dim msg As String = "none"

myConn.Open()

'check whether there are any existing session ids in feedback table that matches current session id
selectCommand = New SqlCommand("select feedback_session_id, feedback_end_time from feedback where feedback_session_id = '" & sID & "'", myConn)
myReader = selectCommand.ExecuteReader()

If myReader.HasRows = True Then

myReader.Read()

If myReader("feedback_end_time").Equals(DBNull.Value) Then

myReader.Close()
msg = "1"
'insert end time into feedback_end_time where the feedback_end_time field is empty
updateCommand = New SqlCommand("update feedback set feedback_end_time = " & Now() & "where feedback_session_id = '" & sID & "')", myConn)
updateCommand.ExecuteNonQuery()

Else

msg = "2"
end_time = myReader("feedback_end_time")
myReader.Close()

If (DateTime.Now - end_time).TotalMinutes < delay Then

'if difference between start time & end time less than 10 mins then update feedback_end_time
updateCommand = New SqlCommand("update feedback set feedback_end_time = " & Now() & "where feedback_session_id = '" & sID & "')", myConn)
updateCommand.ExecuteNonQuery()

Else

'if more than 10 mins, insert new row into feedback table with session id & start time
insertCommand = New SqlCommand("insert into feedback(feedback_session_id, feedback_start_time) values('" & sID & "', '" & Now() & "')", myConn)
insertCommand.ExecuteNonQuery()

End If

End If

Else

msg = "3"
myReader.Close()
'insert new row into feedback table with session id & start time
insertCommand = New SqlCommand("insert into feedback(feedback_session_id, feedback_start_time) values('" & sID & "','" & Now() & "')", myConn)
insertCommand.ExecuteNonQuery()

End If

myConn.Close()

Return msg '"Inserted " & sID.ToString

End Function

Wednesday, May 23, 2007

Database Interaction In ADO.NET

http://www.programmersheaven.com/2/Les_VBNET_13_p1

http://www.programmersheaven.com/2/Les_VBNET_13_p2


SQL Command Execution Methods:

ExecuteNonQuery Executes an SQL statement on the connected data source. You can use it for DDL statements, action queries (e.g., INSERT, UPDATE, and DELETE operations), and ad hoc queries. This method returns the number of rows affected but doesn't return output parameters or result sets.
ExecuteReader Executes an SQL SELECT statement on the data source and returns a fast forward-only result.
ExecuteScalar Executes a stored procedure or an SQL statement that returns a single scalar value. It returns the first row of the result set's first column to the calling application and ignores any other returned values.
ExecuteXMLReader Executes a FOR XML SELECT statement that returns an XML data stream from the data source. The ExecuteXMLReader method is compatible only with SQL Server 2000 and later releases.

Source: MSDN

OOP In VB.NET - Building Classes

vbdotnetheaven

developerfusion

Timestamp

Dim s As Long = DateTime.Now.Ticks
MsgBox("Time: " & (s * 10 ^ -9) & " seconds")

*The Ticks property is to get 100 nanosecond intervals since 1 January 1, 00:00:00.

Source: the scripts developer network

Tuesday, May 22, 2007

Heapfuls

Been having an awful lotta new info to absorb into brain. Wahhh. Here's some:

Ping:

A utility to determine whether a specific IP address is accessible. It works by sending a packet to the specified address and waiting for a reply. PING is used primarily to troubleshoot Internet connections. There are many freeware and shareware Ping utilities available for personal computers.

It is often believed that "Ping" is an abbreviation for Packet Internet Groper, but Ping's author has stated that the names comes from the sound that a sonar makes.

Source: Webopedia


Web Service:

The term Web services describes a standardized way of integrating Web-based applications using the XML, SOAP, WSDL and UDDI open standards over an Internet protocol backbone. XML is used to tag the data, SOAP is used to transfer the data, WSDL is used for describing the services available and UDDI is used for listing what services are available. Used primarily as a means for businesses to communicate with each other and with clients, Web services allow organizations to communicate data without intimate knowledge of each other's IT systems behind the firewall.
Unlike traditional client/server models, such as a Web server/Web page system, Web services do not provide the user with a GUI. Web services instead share business logic, data and processes through a programmatic interface across a network. The applications interface, not the users. Developers can then add the Web service to a GUI (such as a Web page or an executable program) to offer specific functionality to users.

Web services allow different applications from different sources to communicate with each other without time-consuming custom coding, and because all communication is in XML, Web services are not tied to any one operating system or programming language. For example, Java can talk with Perl, Windows applications can talk with UNIX applications.

Web services do not require the use of browsers or HTML.

Web services are sometimes called application services.

Source: Webopedia


Serialisation:
http://aspalliance.com/983_Introducing_Serialization_in_NET

Monday, May 21, 2007

Sound Embeds In HTML

Now this is a sure giveaway at what an amateur I am. Nonetheless, the existence of this blog serves as a reminder of lessons learnt, if nothing more.

So here I have some code I got from elsewhere on how to embed sound files in HTML:

<embed src ="your_waveormp3etc_filename" width = "275"height = "24" autostart = "false" loop = "false"></embed >

The src parameter is the source audio file. The autostart determines whether the file plays automatically when the page loads.

Friday, May 18, 2007

Event Browser Compatibility

http://www.quirksmode.org/js/events_compinfo.html

Fedora

Ooh wah wee.

What can I say? I think I like learning new things.

Boss gave instructions to download Fedora & Solaris OS. Eheh. Again, more new stuff I have never before touched in my life...

Here goes.

Downloading Fedora Core

Wednesday, May 16, 2007

Squash That Bug!

Sometimes programming goes awry for the slightest of errors. In our lingo, we call those nasty things bugs.

I just spent maybe half an hour debugging a code that went wrong just because I forgot the "$" in front of a couple of my variable names.

Aargh. That's programming for you...

Anyways, I've learnt quite a bit of stuff on PHP by now. One of which is file operations such as reading & writing to the file.

Here, I'm gonna be awful nice & share...

Reading from a file:

$c_file = "counter.txt";
$check_counter = fopen($c_file, "r");
$curr_counter = fread($check_counter, filesize($c_file));
fclose($check_counter);

The code reads a counter value stored in the file counter.txt. $check_counter is a file handler which opens the file for reading (specified by the parameter "r"). $curr_counter is the variable which is assigned the value of the counter read from the file. The last line quite obviously closes the file after reading.

Writing to a file:

//read counter value from file counter.txt
$counter_file = "counter.txt";
$get_counter = fopen($counter_file, "r");
$counter = fread($get_counter, filesize($counter_file));

//close the counter.txt file
fclose($get_counter);

//open counter.txt file for writing
$alter_counter = fopen($counter_file, "w");

//decrement counter value by 1
$new_counter = $counter-1;

//write new decremented counter value to counter.txt then close the file
fwrite($alter_counter, $new_counter);
fclose($alter_counter);

This code writes a new counter value to the file counter.txt in 2 steps. First the value is read from the file then the file closed, then in the 2nd part minus 1 from $counter & store the new value in the file counter.txt.

I'm sure there are more efficient ways of doing this. If any veteran out there sees this & doesn't mind sparing me a lesson on how, please drop a comment.

& in the meantime, I spent more than half my day trying to figure out how to either call javascript functions from within PHP script or using javascript code to read my counter value from the file. All just to find a way of disabling the form elements when the registration limit is reached (determined by the counter value of zero). Only to talk to my boss later in the evening & realise that he doesn't mind me just echoing a statement in the window to the effect that the user is informed that their registration is rejected because the registration limit has been reached.

Hmmph.

Oh well, at least I am learning new things everyday. I did learn that there is such a thing as server side Javascript. & I did learn those small bits about event handling for stuff that should happen when HTML code loads onto a page. It's done like this:

< onload="check_limit()">

check_limit() being the javascript function, of course. The comment tags are just so that this post gets by the blogger specifications since HTML tags aren't technically allowed on the post :P

Okies, enough rambling. I aim to be home soon.

Event Handling & Forms Forms Forms

The long & short of it is that I'm needing to re-examine Javascript again. Something about it scares me, even though from previous experiences I've seen that it's not anywhere near being an inconquerable giant like say, Java, which I haven't ever touched at all before.

Yet, that is.

In any case, today's task involves looking into how to check a decrementing counter to decide whether a form's elements/controls (am I using the right term here?) should be disabled. Hence the need to read up on event handling.

I'm in a hurry to find code for an on load sorta event thingy, but I'm bookmarking this page to read later... It's pretty interesting:

Introduction To Events

Oh, & this one too:

GET vs. POST

Forms. The simple yet ever enduring pain of web programming...

Tuesday, May 15, 2007

Here We Go

New blog. New adventures.

But this time it's solely about my techie tracks. I am not really a true blue tech person, though I am still trying to be (by means of my current Software Engineer job eheh).

The main purpose of this little blotting corner is basically to dump my tech jargon & to spill any valuable lessons I pick up along the way. So, if you're willing to delve into all this stuff along with me, let's get going...

There's a whole big Internet frontier & beyond to explore, & it doesn't just end at the IE browser. Hehe. Yups yups. Bring a crowd, I expect a quite a spectacle of blunders & victories. Let the trekking begin, & the journey commence!