Showing posts with label .net framework. Show all posts
Showing posts with label .net framework. Show all posts

Wednesday, June 20, 2007

IComparer vs. IComparable

Why does the .NET framework insist on being sooooo.... complicated?

Sorting In The .NET Framework

Friday, June 15, 2007

Tuesday, June 12, 2007

Trees... Trees... & MORE Trees...

Source: vbCity

The Basics of a TreeView


You'll be familiar with the look and feel of a treeview from the Windows Explorer. Its name of course refers to a regular tree, that has one trunk and many branches and where each branch can have smaller branches. The stem is the treeview object itself, the "branches" are called nodes. The main difference between a branch and a node is that the thickness of a node doesn't need to decrease; on the contrary: the 'ends' can easily be the thickest part of the whole: that is contain the most items.

In principle the number of items and childnodes is unlimited (read: a number you will not easily reach wink ) Each node can contain an item collection (child nodes) and has a parent. Using the item collection and the parent property, you can go through all branches. If you go 'down', you will know you have reached the end when there are no more childitems (GetNodeCount = 0) and you have reached a toplevel node when the parent is the listview object itself.

Populating the treeview during runtime is very easy: just go to the Collection property and press the "..." button. You can play around with the possibilities. To populate during runtime:

Code:
Dim N As TreeNode

'Method 1: straightforward adding of nodes
With Me.TreeView1.Nodes
'add text
.Add("AddByText")
'since with..end with is used: read TreeView1.Nodes.Add ....

'every add method returns the newly created node. You can use
'this concept set the result to a variable or to directly add
'a childnode:
.Add("AddByText2").Nodes.Add("ChildOfAddByText")

'this, you can take as far as you want
.Add("AddByText3").Nodes.Add("ChildOfAddByText").Nodes.Add("Another child")

'--
N = .Add("AddByText, Attach To Variable")
N.Nodes.Add("Child one")
N.Nodes.Add("Child two")
' --
With .Add("AddByText Use WithTo Add ChildNodes").Nodes
.Add("Child 1")
.Add("Child 2")
.Add("Child 3").Nodes.Add("Subchild 1")
End With
End With

'for clarity, from here on, the treeview1 name will be added.
'In everyday use, you'll probably find the use of with..end with
'a lot easier (I know I do..)

'Method 2: adding by node
'Like virtually every .Net method you can directly assign an object:
Me.TreeView1.Nodes.Add(New TreeNode("AddByNode"))

'check out the overloading possibilities of using New()
'Another advantage of this method is that you can add a complete branch.
'(N is already declared as TreeNode above)
N = New TreeNode("MainNodeToAdd")
N.Nodes.Add("Child 1")
N.Nodes.Add("Child 2")

'you can for instance add this newly created node to all main branches:
Dim enumNode As TreeNode
For Each enumNode In TreeView1.Nodes
enumNode.Nodes.Add(N.Clone) '<- the clone() method is needed
Next

'Adding will always add the the node at the end of the collection.
'Of course you can also insert at a specified location:
Me.TreeView1.Nodes.Insert(2, New TreeNode("I am inserted at the 3th position"))

'removing is done much in the same way:
N = TreeView1.Nodes.Add("I need to be removed").Nodes.Add("and all children too")
TreeView1.Nodes.Remove(N)

'to clear all branches of any node you can use clear()
N.Nodes.Add("This child you will not see")
N.Nodes.Clear()

'if you use Clear on the treeview nodes itself, you
' would once again have an empty treeview

'once an item has been added, it is part of the item collection in nodes
'this means you can access it by its index
TreeView1.Nodes(0).Text = "I have index 0"

'the behaviour of the treenode can be controlled completely in code.
'you can make it expand
TreeView1.Nodes(0).Expand()

'and retract again
TreeView1.Nodes(0).Collapse()

This is just the basic functionality. There are a lot more properties on a treeview. Some are inherited, some are specific to the treeview object. The sample above should give enough information to create your own treeview. Have fun thumb up!

To finish: an example
Code:

'this example will fill a treeview with the hours of the day.
'the hours will be divided in 15 minute blocks and the blocks
'will be divided in minutes
Sub Example()
Dim N As New TreeNode(), I As Integer, J As Integer

'create a 15 minute block
For I = 0 To 3
With N.Nodes.Add((I * 15).ToString & "-" & ((I + 1) * 15 - 1).ToString)
'add the minutes
For J = 0 To 14
.Nodes.Add((J + I * 15).ToString)
Next
End With
Next

'add the hours and immediately add the blocks to the hours as well
Dim NodeToAdd As TreeNode
For I = 1 To 24
NodeToAdd = N.Clone
NodeToAdd.Text = I.ToString
TreeView1.Nodes.Add(NodeToAdd)
Next
End Sub

'the sub when a time has been chosen
Private Sub ItemChosen(ByVal sender As Object, ByVal e As System.EventArgs) Handles TreeView1.DoubleClick
Dim N As TreeNode = CType(sender, Windows.Forms.TreeView).SelectedNode
If N.GetNodeCount(False) = 0 Then 'it is 'last' in the line
Dim S As String = N.Text
If S.Length = 1 Then S = S.Insert(0, "0")
S = N.Parent.Parent.Text & ":" & S
MessageBox.Show("You have selected: " & S)
End If
End Sub

Thursday, June 7, 2007

Shorties

I'm learning new stuff every day...

Use F7 key for bringing up the code window in VB.NET 2005. F5 for running/testing/debugging the program.

#Region "Name of Region" for categorising your blocks of code into separate expandable & collapsible nodes.

Use For Each loops to run through lists or classes or dictionaries & the like.

Whenever a particular section of code keeps getting reused a considerable number of times, it warrants making it into a separate subprocedure or function of its own.

Put short comment lines into parts of conditional blocks of code where nothing is done/executed. This is for future purposes, to prevent you thinking it's an error of sorts & waste time tweaking the code unnecessarily.

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!

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