Posts filed under 'Tip Sheets'

What You Should Know About Rounding in VB.NET

RoundingRounding, the process of reducing the number of significant digits in a number, should be a simple enough but there are actually several ways of doing this that we need to be concerned about. In this article, I’ll go over the different types of rounding found in VB.NET.

Simple Rounding

This form of rounding is simple truncation of the number where any digits after the point of precision are dropped. VB.NET provides two functions for doing this to get an integer result, Int and Fix. However these two functions are slightly different. Both remove the fractional part of a number but, when a number is negative, Int returns the nearest negative integer less than or equal to the number while Fix does the opposite. For example, Fix(-10.4) returns a -10 while Int(-10.4) returns -11.

The way the Fix function works is called symmetric rounding since it affects positive and negative numbers the same way. The Int function is considered asymmetric rounding because it affects positive and negative numbers differently.

You can also do truncation rounding using the Format function, like so:

Format(48.15162342, "#.00")

This is method doesn’t take the trailing numbers into account at all so care should be exercised when using it to avoid skewing results.

It is better to use Math functions for rounding rather than using these methods, particularly if statistical precision is required.

Arithmetic Rounding

When you use simple rounding, always going up or down, you run into the problem about what to do with numbers that are right at the midpoint. What should 1.5 be rounded to? 1 or 2?

By mathematical convention, numbers at the midpoint are rounded up symmetrically although you will see examples of asymmetric rounding in some math libraries, most notably some Java/Javascript implementations.

In VB.NET we can do this kind of rounding using the Math Namespace, like so:

Math.Round(48.15162342, 2, MidpointRounding.AwayFromZero)

Note the last parameter. This tells the function to perform arithmetic symmetric rounding instead of the default bankers rounding.

Bankers Rounding

This is the kind of rounding used by default in the .NET Math library and by built-in VB.NET functions such as CInt(). In this type of rounding, .5 rounds to the nearest even number. This means that both 1.5 and 2.5 round to 2, and 3.5 and 4.5 both round to 4. The idea behind this method is that it prevents a round up or down bias from entering into a large series of numbers.

This method has caused a lot of confusion over the years because in previous versions of VB this method of rounding was the only one available. Since some project sponsors didn’t like it and some did it often made rounding in a program a pain. Fortunately with the .NET Framework 2.0 we can implement rounding either way in the Math.Round function so that we can please everybody.

I would strongly recommend that you have rounding methods spelled out in your requirements. If you don’t, expect headaches down the road. Also, you should use Math.Round instead of built-in functions that perform rounding so that if there is a last minute change in rounding technique, it’s easier to change.

Stochastic or Statistical Rounding

One last method of rounding we should look at is Stochastic or statistical rounding. In this method, when a number to be rounded falls at the midpoint, the decision to round up or down is determined randomly. In theory, this method prevents large totals from becoming skewed. However, using this method will make statistical analysis hard to replicate and requires more computational time. You can implement this using the .NET Random functions. This method is good for certain types of statistics but is probably overkill for most rounding implementations.

Hopefully this article has helped you gain a better understanding of rounding in VB.NET. If you have any questions or ideas about rounding, please feel free to leave me a comment.

Share This Article: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • del.icio.us
  • Reddit
  • StumbleUpon
  • Technorati
  • DotNetKicks
  • DZone

1 comment July 31st, 2007

How To Make Debugging .NET Windows Services Easier

elementaryAs you may know, Windows Services developed in .NET can’t be run with the Visual Studio .NET environment. Instead, you have to install the application as a service, so that it can run under the Windows Services Control Manager, and attach the Visual Studio debugger to the process. The catch is that the service has to be running before you can debug it and this makes it difficult for you to debug your start-up routines.

In this article I’ll examine some techniques you can use to make debugging your Windows Service apps easier

The first technique I like to use is scaffolding. This means that I first develop the app as a standard Windows application, either WinForms or Console, and develop a substantial portion of the program without having to deal with the baggage of the service environment. I use very simple code for the scaffold that essentially emulates the standard service, such as the Start, Stop, Pause, and Continue commands. Each part of the program can be tested as it is written this way as long as you’re using a good design.

Unfortunately, not every service application can be built up this way since some need to run as a service in order to do what they need to do properly. Also, you need to be mindful that your scaffold app will be running under your user account, not the NETWORK or LOCAL services accounts, so the rights are very likely to be different. Security issues are a common stumbling block when it come to running as a service.

Once the units of your program are in place you’re ready to deploy it and run it as a service. However, you will probably still need to debug it. To do this, you install and start the service and attach to it using the Attach To Process dialog from the Visual Studio Debug menu. Now you’re ready to set your breakpoints and debug the app but there are still some challenges involved in debugging a .NET service application.

First, the service has to be running for you to attach to it. This means that by the time you can hook into it the startup code has already been executed. If you have a problem in the startup code, code that executes in either the Main or OnStart methods, this can be difficult to debug. Also, since the attachment process doesn’t stop or pause the service but suspends the service thread, this can cause some odd effects on some code. Also, you can’t use pausing techniques to have the program wait on you because Windows only provides a 30 second stretch of time for a service to start. If it hasn’t completed its start during that time, it program won’t start. You can use logging to disk to capture some of these errors but that can be difficult and tedious to manage.

My method for getting around this problem is to have very little code in the startup routines themselves, like so:

Protected Overrides Sub OnStart(ByVal args() As String)
    ServiceStartUp()
    MyBase.OnStart(args)
End Sub

Then, to enable debugging, I move this call, ServiceStartUp(), to the OnContinue method and comment it out in OnStart. That way I can start the service without any code being executed, pause the service, set breakpoints and attach to it from within Visual Studio, and click to allow it to continue. I can then debug the startup code of the application.

Make sure that you uncomment the startup line in the OnStart method when you’re ready to deploy though!

One other tip is how to find your app in the Attach To Process Window. This can be confusing at first. The default setting of the dialog only shows processes for the currently logged in user so your service, which is mostly likely running under a system service ID, won’t be visible although you’ll see a grayed out copy of the matching project in the list. Check on the “Show processes from all users” box to see the process you want. Don’t let the similarly named “vshost” file confuse you.

If you have any questions or ideas about debugging .NET Windows Service applications, please leave a comment here.

Share This Article: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • del.icio.us
  • Reddit
  • StumbleUpon
  • Technorati
  • DotNetKicks
  • DZone

5 comments July 24th, 2007

Free VB.NET Resources From Microsoft

Free VB.NET Stuff From Microsoft!Microsoft often makes books, videos, code example and other media available online to developers in the MSDN library. Here are a few you should take advantage of if you’re making the move from VB6 to VB.NET or if you just want to improve your knowledge and productivity. It’s surprising that many developers simply don’t bother to check out all the freebies Microsoft makes available to us.

The first book is one written with the VB6 programmer in mind, Upgrading Microsoft Visual Basic 6.0 to Microsoft Visual Basic .NET. It goes into ways to fix the inevitable upgrade issues, outlines the differences between VB6 and VB.NET, and provides some architectural and design advice. The appendix sections have a cross-reference of function and control differences that is quite valuable. Unfortunately, you’ll have to buy the book to get the code on the CD though.

Another book that’s available for download is Introducing Microsoft Visual Basic 2005 for Developers. The introductory chapters are quite helpful to a VB6′er who’s going straight to VB 2005. The rest of the book covers a lot of the changes in VB 2005, usually in a lot of helpful detail.

Next, let’s take a look at VB At The Movies. This is a set of instructional videos on a wide range of topics such as deployment, using XML, and many others. While the ‘movie posters’ promise an exciting ‘Hollywood’ video they’re actually pretty plain instructional videos. It’s good info though and it’s well worth your time to view them.

If you’re just getting started learning VB in general, check out the Beginner Developer Learning Center. You can use it to go at your own pace to learn VB on a well laid out learning path.

If you want to hop right into code, have a look at the Visual Basic Starter Kits & Power Packs. Here you’ll find template code for such useful things as Shareware licensing, PayPal integration, eBay auction management, web log analysis, time tracking, RSS management and many others. There’s even an example of how to program Lego Mindstorms robots. You will also want to download the Samples for Visual Studio 2005. These sets of examples cover the basics of coding for a wide range of topics. Most of the code in these samples can be easily moved to your applications so it’s not only of great instructional value but can be a timesaver as well.

If you have a LCD monitor, you might want to download the Consolas Font Pack. The letters of this monotype font are easier on the eyes than the usual Courier New but they only work well on a ClearType enabled LCD monitor.

The last freebie I’ll cover here is Refactor!. This is a handy tool to have since it assist you in reordering parameters, encapsulating property values, creating overloads and more. Since it operates modelessly it doesn’t get in your way as you code but it’s always there to help you if you want it to.

Share This Article: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • del.icio.us
  • Reddit
  • StumbleUpon
  • Technorati
  • DotNetKicks
  • DZone

Add comment June 12th, 2007

Beware of the Byte Order Mark

Beware! This dog will byteVS 2005 includes several new file management wrappers in the My.Computer.FileSystem namespace, including WriteAllText. This method is a quick and handy way to write small sized strings to disk but this method has a ‘gotcha’ in it. It uses UTF-8 encoding with a Byte Order Mark by default. This mark can easily confuse programs that aren’t expecting it.

What is a Byte Order Mark? Simply put, it’s a set of characters at the beginning of a Unicode text file that denote how the file is encoded. For UTF-8, the characters are the byte sequence EF BB BF, which appears as the characters “”.

Many Windows programs and .NET functions handle this transparently for you so you never see these characters. For example, if you open a UTF-8 encoded file in Notepad, you won’t see these characters at all. This ‘helpfulness’ can make it difficult to spot a that the encoding of the file is a problem.

How can it be a problem? The problems come up when a program that expects ASCII encoding tries to read the file. For example, you might be sending files you create to a third party program. It loads the file and sees the Byte Order Mark and assumes that the file isn’t in the correct format and rejects it. If you load the file into Notepad it looks OK to you but the target program can’t read it. It can be a frustrating problem to track down.

WriteAllText is different from similar methods, System.IO.StreamWriter and System.IO.File.WriteAllText. They do write UTF-8 encoding by default but they do not include the Byte Order Mark. So, if you were using StreamWriter in VS 2002/2003 or used System.IO.File.WriteAllText elsewhere and switched to My.Computer.FileSystem.WriteAllText there is a difference in the output files you’re producing.

So, to avoid this kind of problem, use the overload for My.Computer.FileSystem.WriteAllText that includes encoding and avoid the one that doesn’t. In fact, my recommendation is to always specify the right encoding method no matter which method you use.

Use:

My.Computer.FileSystem.WriteAllText(MyFilename, MyString, False, System.Text.Encoding.ASCII)

System.IO.File.WriteAllText(MyFilename, MyString, False, System.Text.Encoding.ASCII)

Using sw As New StreamWriter(MyFilename, False, System.Text.Encoding.ASCII)
    'writing code here
End Using

OK (but not recommended):

System.IO.File.WriteAllText(MyFilename, MyString, False)

Using sw As New StreamWriter(MyFilename, False)
    'writing code here
End Using

Avoid:

My.Computer.FileSystem.WriteAllText(MyFilename, MyString, False)
Share This Article: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • del.icio.us
  • Reddit
  • StumbleUpon
  • Technorati
  • DotNetKicks
  • DZone

4 comments May 26th, 2007

Avoid Using Dynamic SQL Statements

Mind if I look through your database?Most programmers who’ve developed Web-centric database applications know about SQL injections attacks where a malicious hacker can insert commands into your dynamically built queries to retrieve passwords, infiltrate systems, drop tables or do other harm. However, desktop application developers should also be aware of the security risks and complications involved when you use dynamically built SQL statements in your applications.

The bottom line is that building SQL statements in your application code is asking for trouble. Not only does it leave you open for malicious attacks but it also makes your code harder to maintain and can cause it to behave in unexpected ways.

First, lets look at SQL Injection. If you haven’t read it already, read Stop SQL Injection Attacks Before They Stop You by Paul Litwin. He gets into some detail on how this kind of attack can happen. You may think that this is an Internet only threat but it’s not. It would be easy for a disgruntled employee or other internal hacker to gain access to data they weren’t supposed to have or even delete tables if they weren’t secured well. Remember, the “How To” for it is only a Google search away.

Secondly, if you need to make changes to the query, even a small one, this means a recompile and redeployment of your executable. Making a change to a stored procedure is much simpler and reliable. Another bonus of using a stored procedure with parameters is that you don’t have to worry about matching up or escaping embedded quotation marks. All this error prone and costly string manipulation code is handled for you. Plus, using stored procedures means that your query is optimized to run on the server, thus improving the performance of the query and your application.

Our last reason are unintended results from queries causing problems. These can also affect stored procedures. A good example would be a search criteria field. The value the user enters is used in the WHERE clause to narrow the data returned. But what if the user doesn’t enter any criteria. You may end up trying to populate a control with 1000’s of rows of data or you might have a query that runs several minutes. Another might be if a user enters a wildcard ‘%’ and uses it to gain access to records they shouldn’t have access to. To avoid these kinds of problems you should always validate user input, even if you’re loading a parameter object for a stored procedure. As Paul Litwin mentions in his article, all user input should be considered suspect and validated.

So, when you’re developing database queries for you application, think stored procedures with validated input and you’ll greatly improve the security and stability of your application on both the front and back ends.

Share This Article: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • del.icio.us
  • Reddit
  • StumbleUpon
  • Technorati
  • DotNetKicks
  • DZone

Add comment May 24th, 2007

Next Posts Previous Posts


Most Popular Articles

Highest Rated Articles

Categories

Most Recent Articles

Feeds

 Subscribe in a reader

To subscribe by e-mail
Enter your address here

Delivered by FeedBurner

VB Opportunities

Archives