.net.devcity.weekly ---
If you are unable to see the message, visit http://www.devcity.net/newsletter/archive/devcity/devcity20050310.htm

Advertisement

AdvertisementAdvertisement

The newsletter is compiled by DevCity.NET NewsMasters Ged Mead and Mike McIntyre

Advertisement

Table Of Content:

Advertisement

This month's competition just got easier!

We are very pleased to announce that we have teamed up with Olvio IT to bring you our latest competition, and a chance for you to win one of three valuable prizes.

PlusDock is a great tool for developers, offering an easy to use advanced windows docking system. Its range of features includes custom docking panels, floating forms, autohide panels and redockable windows. It also boasts Office2003 theme support and integrated WYSIWYG designer support.

Three full developer licences are on offer for three lucky winners.
And it is easy to enter and win. Simply download the free evaluation version of PlusDock from Olvio

Once you have the trial version installed, you will see that several useful samples are included. Take a look at the one named "VisualStudioClone".
One of the options in the menu is "Save/Restore layout". Once you have checked out this sample, identify the answer to the following question and send it to answers@devcity.net

Which member of the RestoreLayoutStepEventArgs is used in the handler for the RestoreLayoutStep Event to determine which type of item is currently being restored?
Is it:

  1. Items
  2. ItemType
  3. Typeof.Item
  4. TypedItem

Hint: The event handler is called "dockModel1_RestoreLayoutStep".

That's all there is to it! Simply send your answer - a, b, c or d - to the email address given above.

On the closing date of March 31st 2005, the names of three contestants who have sent in correct answers will be drawn. Each of the winners will receive a full developers license for PlusDock 1.0.

Remember: Closing Date is 31st March, so check out the Olvio Website and the Competition Info now!

http://www.olvio.com/devcitycompetition.aspx
Thanks for voting for vbCity.com!

Vote for vbCity!

Support vbCity in the .NET Developer's Journal 2004 Readers' Choice Awards Voting Ballot.

We've worked hard to make vbCity the best VB and .NET Community on the Net. Show your support by casting your vote in the .NET Developer's Journal Readers Choice Awards.

Click here to cast your vote for vbCity in the "Best .NET Web Sites" Section.

Thank you!
DevCity.NET Team

http://sys-con.com/dotnet/readerschoice2004/vote.cfm

by Dries Neyrinck

A colleague of mine called last week. One of our applications was creating huge log files because of a problem. When I say huge, I mean HUGE. Talk about Gigabytes...

Ever tried to open a text file of 2 GB with Notepad? Probably not, and you can easily imagine that doing so would lock up your system quickly. But we had to find the problem, and the problem was logged to our log file...

I decided to build a text reader application which could read some lines of the text file without blocking the system.

Thanks to the StreamReader class of .NET this could be done in no more than five minutes. Within 30 minutes the application was built and sent to the customer, the log file was analysed, the problem isolated and finally solved!

OK are you ready?

1. Create a new Windows Forms application.

2. Create two Buttons
    - btnInit. Set the Text to "Init"
    - btnReadLines. Set the Enabled property of this button to False and the Text to "Read Lines"

3. Create a NumericUpDown control
    - nudNrOfLines

4. Create a Textbox
    - txtLines. Set the MultiLine property to true.

First of all we need to define two private variables: our StreamReader and the filename of our text file.

Private FsFileName As String
Private Fsr As IO.StreamReader

By clicking the Init button we initialise our Streamreader and select a textfile.

Private Sub btnInit_Click( _
    ByVal sender As System.Object, _
    ByVal e As System.EventArgs) _
    Handles btnInit.Click

    'Create a new open file dialog
    Dim OfdLogFile As New OpenFileDialog

    'Show the open file dialog.
    'If we select a file, continue with the selected file
    If OfdLogFile.ShowDialog = DialogResult.OK Then
        Me.btnReadLines.Enabled = True
        FsFileName = OfdLogFile.FileName
        Fsr = New IO.StreamReader(FsFileName)
    End If

End Sub

Every time we click on the Read Lines button we want to read a defined number of lines from the text file. We can alter this number of lines by using our numeric up down control.

Private Sub btnReadLines_Click( _
    ByVal sender As System.Object, _
    ByVal e As System.EventArgs) _
    Handles btnReadLines.Click

    'Clear the textbox
    Me.txtLines.Text = ""

    'Read a number of lines from the textfile and show them on the textbox
    For LineCounter As Int16 = 0 To Me.nudNrOfLines.Value - 1

        'As long as we haven't reached the end of the file
        If Fsr.Peek <> -1 Then
            Me.txtLines.Text &= Fsr.ReadLine() & ControlChars.CrLf
        Else
            Fsr.Close()
        End If
     Next

End Sub

Finally, add some code to close the handle round the file properly when the application is closed:

Private Sub Form1_Closing( _
    ByVal sender As Object, _
    ByVal e As System.ComponentModel.CancelEventArgs) _
    Handles MyBase.Closing

    'If necessary close the streamreader,
    'so the textfile is released
    If Not Fsr Is Nothing Then

        Fsr.Close()

    End If

End Sub

That's it! Build your application, create a huge textfile (copy paste is a powerful tool to do this), and select it via the application.

Diary of a .NET Newbie: Losing Time

by Ged Mead

Here's another Gotcha! I learned the hard way. I had been fiddling around with a piece of code that simply wouldn't behave as I wanted it to. I know, I know , the Golden Rule is that the code always does exactly what you tell it to do - which isn't always exactly what you think you are telling it to do.

By a process of elimination, I was trying to track down a bug that kept causing an "Invalid Parameters Used" exception . I can't bear to think how many hours I spent chasing that one down, researching, Googling for causes and answers, trying alternatives, shouting at the computer ... all the usual fixes! But at some stage, I took it into my head that maybe it was the Timer control that was causing the problem.

So, I deleted the Timer Control from the form and commented out the code line that turned it on

Timer1.Enabled = True

And I also commented out some of the code in the Tick event of the Timer.

I ran a few more tests and eliminated the Timer as a possible culprit. Happy with its newly established innocence, I dragged a Timer control from the toolbox, made a couple more tweaks elsewhere, and ran the project again. Oh dear, not only had I failed to find the cause of the original bug, I now found that the timer's Tick event code wouldn't work either.

So, already halfway down a negative thoughts spiral, I grumbled my way through yet another battery of tests to see why the Timer now wasn't behaving. Of course, when I did finally find the cause it was such a basic Newbies error that I should have spotted it from the other side of the room (metaphorically speaking, that is - although I suppose I could have seen it when I'd walked over there to pick up the pen I'd flung away in one of my debugging tantrums.).

As I mentioned earlier, when I removed the Timer, I commented out all the references in the code to that Timer. And there's the key to it all. I commented out the code in the Timer1_Tick event to sidestep the build error messages that would appear because I had deleted the Timer control itself. Fair enough. But I didn't delete the complete code block of the Tick event, just the parts of the code that would cause an error at build time.

Having later created a replacement Timer1, I cheerfully uncommented the code in the Timer_Tick event, thinking that everything would be back on track and available. But of course, when I had deleted the Timer and then built the solution by running it, the compiler - clever little chap that he is - automatically deleted the handles clause in that Timer Tick event. Quite right too ! No Timer1; No reason to have a block of code that handles its non-existent events.

The result was that I could "see" the Timer's Tick event code there right in front of me, plain as day ... It just took a bit of nail chewing and coffee-drinking time to figure out that it was an orphan code block. Typing back in the magic words

. . . .Handles Timer1.Tick

At the end of the line was all it took to get things working again.

Like so many of these manholes lying in wait for you fall down, it's blindingly obvious once you've spotted it. The problem is that sometimes you're so busy looking elsewhere you just don't see what's right in front of you.! And the worst thing is that you can't even sue the Council for damages for your sore head and bruised ego - it's a self-inflicted injury!

- Junior (Ged Mead aka XTab, xtab@vbcity.com)

by Mike McIntyre

This article provides sample code and an explanation of how to combine delegates to make it possible to call more than one method at the same time.

One of the types we as VB.NET programmers can define ourselves is a MulticastDelegate class. We define a MulticastDelegate class so our code can instantiate a MulticastDelegate object that points to static method(s) or to a class instance and instance method(s) of that class.

VB.NET implements the Delegate keyword for defining Multicast delegates. The Delegate keyword provides the way you derive from the MulticastDelegate class. This is different than the standard way we define a class with a Class...End Class statement. Here is an example that defines a MulticastDelegate class:

Delegate Sub MessageDelegate(ByVal message As String)

The line of code is the full definition of a MulticastDelegate class. The keyword Delegate informs the compiler you are defining a MulticastDelegate class. The words following the Delegate keyword define a MulticastDelegate class named MessageDelegate.

The declaration of a delegate type establishes a contract that specifies the signature of one or more methods.

To instantiate a MessageDelegate we use the New keyword. The example below instantiates a MessageDelegate object which points to a method named DisplayMessage.

Private _Display As New MessageDelegate(AddressOf DisplayMessage)

A MulticastDelegate can link a list of delegates, called an invocation list, consisting of one or more elements. When a multicast delegate is invoked, the delegates in the invocation list are called synchronously in the order in which they appear. If an error occurs during execution of the list then an exception is thrown.

So how do we link MulticastDelegate objects to create an invocation list? We use the MulticastDelegate's Combine method:

Example Code - Dispatcher class to call three methods at the same time.

Public Class Dispatcher

    '  Define a delegate type named MessageDelegate with a
    '  signature of: (ByVal message As String)
    Delegate Sub MessageDelegate(ByVal message As String)

    ' Declare a variable of type MessageDelegate named _Display
    ' which points to the DisplayMessage method in this class.
    ' Instantiate a MessageDelegate object and assign it to the variable.
    Private _Display As New MessageDelegate(AddressOf DisplayMessage)

    ' Declare a variable of type MessageDelegate named _Write
    ' which points to the WriteMessage method in this class.
    ' Instantiate a MessageDelegate object and assign it to the variable.
    Private _Write As New MessageDelegate(AddressOf WriteMessage)

    ' Declare a variable of type MessageDelegate named _Log
    ' which points to the LogMessage method in this class.
    ' Instantiate a MessageDelegate object and assign it to the variable.
    Private _Log As New MessageDelegate(AddressOf LogMessage)

    ' Declare a variable of type MessageDelegate named BroadCast.
    Public Broadcast As MessageDelegate

    Public Sub New()
        ' Combine the _Display, _Write, and _Log delegates into
        ' the Broadcast MessageDelegate.
        Broadcast = CType(Broadcast.Combine(Broadcast, _Display), _
        MessageDelegate)

        Broadcast = CType(Broadcast.Combine(Broadcast, _Write), _
        MessageDelegate)
        Broadcast = CType(Broadcast.Combine(Broadcast, _Log), _
        MessageDelegate)
    End Sub

    Public Sub DisplayMessage(ByVal message As String)
        MessageBox.Show("Displaying: " & message)
    End Sub

    Public Sub WriteMessage(ByVal message As String)
        MessageBox.Show("Writing: " & message)
        Console.WriteLine(message)
    End Sub

    Public Sub LogMessage(ByVal message As String)
        MessageBox.Show("Loging: " & message)
        ' Code to write to log file goes
    End Sub

End Class

Use the Dispatcher Class

Now we can use the Dispatcher class in another class, for example in a System.Windows.Forms Form class. Here is a demonstration.

' Declare a variable named theDispatcher of type Dispatcher.
' Instantiate a Dispatcher object and assign it to the variable.
Dim theDispatcher As New Dispatcher()
' Call theDispatcher's BroadCast delegate passing it a string to dispatch.
theDispatcher.Broadcast("Test Message")

When theDispatcher's Broadcast delegate is called, it calls the _Display, _Write, and _Log methods in theDispatcher object, passing "Test Message" into each method as it calls it.

Learn more at the links below:

Delegate Class
EventHandlerList Class

Advertisement

The DevCity article Content Management System has been overhauled during the past few months and you may have noticed a drop in the number of articles being published. We are pleased to announce that things are back up and running again and several new articles have been published in the past few weeks.

Here are some details of the latest ones:-

Mike McIntyre revisits the ANTS Profiler now that Version 2.0 is available. Having used it extensively, he finds much to recommend it. link

Weighing in for the C# developers, Chas Profitt has published the first two parts of a planned series of articles entitled Business Mate. The goal of Chas's series will be to create step by step a small database application that is a working functional piece of software.
Check out the first two parts
Part 1 link
Part 2 link

If web programming is your area of interest, then you should take a look at the article How to create dynamic doorway pages in ASP.NET written by Yousuf Baqir. link

Scott Rutherford has published two articles of general interest recently. In Windows never forgets a file: Using the CreationTime attribute of Windows Files he highlights a problem with file date stamping, and very helpfully provides the fix. link
And on the subject of problems, Scott has written a guide which highlights best practices for Exception Handling in Enterprise Applications. link

An introduction to some of the tools available in the Graphics Class is made in the first article in a series being written by Ged Mead. In Chart Success: GDI+ Graphics at work. Part 1, the built in method for drawing a pie chart is used as a way of introducing some Graphics Class basics. link

http://www.devcity.net/
Advertisement

We encourage you to pass this issue of
.net.devcity.weekly on to anyone you know with an interest in .NET technology and News You Can Compile

Manage Your Subscription Here.

You are currently subscribed as '*EMAIL*' to .net.devcity.weekly.

Click here to unsubscribe.

Thanks for reading!

Contact:
vbCity.com, LLC
4957 Lakemont Blvd SE C4 #331
Bellevue, WA 98006


DevCity.NET is hosted by FullControl.NET

Copyright vbCity.com, LLC 2003. All Rights Reserved.