How To Write an IsValidPath Function

Even works with messy disk drivesA common requirement that you may encounter is to have a way to validate a string to determine if it’s in the proper format for a path. While there are .NET functions that you can use that will tell you if a given path exists on the disk there is no built-in .NET function that will tell you if a path string has a valid format. This was the subject of a recent discussion on VBForums. In this article, we’ll look at the function I built and some other related ideas that were suggested.

Our Requirements

For this example, we want to create a function that will tell us if the path entered by a user is a valid path string or not. We aren’t concerned about it already existing on the disk or if we have the rights to create the folder. We only want to make sure that the path string has a valid format.

What Won’t Work

We can’t use methods that check the disk for existence of the folder because we don’t need it to actually exist yet. This means we can’t use the Directory.Exists functions from the IO Namespace or the My.Computer.FileSystem Namespace. Some other IO.Path functions, such as IsPathRooted (which was my first suggestion) and GetDirectoryName weren’t well suited for validating path names.

We could use a folder browser or the textbox file system autocomplete feature. However, this wouldn’t fulfill our validation requirement.

Two other methods were thought of by forumites were to create the directory temporarily and capture exceptions. The folder would be deleted if it wasn’t used. The problem here are the performance killing exceptions and the risk of leaving junk on a user’s drive. The second was to use System.IO.Path.GetFullPath. This method worked OK in some cases but had its own formatting quirks plus it required exception trapping to deal with incorrectly formatted paths.

Solving the Problem With Regular Expressions

The way I ended up suggesting to deal with the problem was to use regular expressions. Here is the function:

    Private Function IsValidPath(ByVal pathString As String) As Boolean
        Const PathPattern As String = “^(([a-zA-Z]:|\)\)?(((.)|(..)|([^\/:*?”“|<>. ](([^\/:*?”“|<>. ])|([^\/:*?”“|<>]*[^\/:*?”“|<>. ]))?))\)*[^\/:*?”“|<>. ](([^\/:*?”“|<>. ])|([^\/:*?”“|<>]*[^\/:*?”“|<>. ]))?$”
        Dim Results As Boolean
        Try
            If System.Text.RegularExpressions.Regex.IsMatch(pathString , PathPattern) Then
                If IO.Path.GetPathRoot(pathString).Length >= 248 Then
                    Results = False
                Else
                    ‘additional checks could go here if desired
                    Results = True
                End If
            Else
                Results = False
            End If
        Catch ex As Exception
            Results = False
        End Try
        Return Results
    End Function

In this function you’ll notice that I first define a string constant with the regular expression string. I’ve ran several tests with it and it seems to work right but if you throw something at it that it can’t handle correctly, please let me know. Next, we look for a match between the pattern and the passed in string.

After passing the first test there is a second one. We need to determine if the path is too long. Windows paths can’t be longer that 247 characters. If this value is exceeded, a False value is return. Notice that there is room to add additional checks if you need them. For example, you could add a check for a local hard drive vs. a network or removable drive.

To call this function, you would just need to call it from the TextChanged event of the target textbox.

That’s my solution. I want to thank VBForum members stimbo, techgnome TokersBall_CDXX, penguin5000, VBDT, and JuggaloBrotha who participated in this discussion and rjbudz who got the whole thing started. If you have an idea or question on this function, please leave a comment here or in the VBForum thread linked at the top of the article.

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
Not That GoodCould Be BetterOKGoodGreat (No Ratings Yet)
Loading ... Loading ...

3 commentsOctober 12th, 2007

Should You Pursue a Career In Programming?

Predictions are always trickyA question that gets asked often by students trying to decide on a technical career is would programming be a good career choice. In recent tech site columns, like this one by Jason Hiner of TechRepublic, Sanity Check: Is IT still a profession worth recommending to the next generation?, and this one on WindowsITPro, Are IT Pros Steering Their Children Away From IT?, many commenters say that they would not recommend it. Let’s examine why this is a common response and the reasons behind it.

The number of jobs in the US for software development have been declining since 2000. Computer programmer employment has fallen from 530,730 in 2000 to 396,020 in 2006 according to the Labor Department. When inflation is factored in, salaries have also declined by about $850 a year since 2000 and continue to fall. H-1B visas and offshoring have contributed to this trend as have other economic factors. The sad truth is that the US software development industry is on the decline. No wonder there has been a decline in technical degrees, there simply isn’t any money in the field.

Then why do tech moguls complain that they can’t find enough programmers, you might ask. What they’re really complaining about is that they can’t find enough cheap programmers. Many older software developers are forced to work short term, temp, contracts to make ends meet. Rampant ageism in IT and the desire to hire the cheapest programmers possible prevents them from landing a perm position even while many well-heeled corporations lobby Congress for more H-1B visas because they can’t find enough (cheap) programmers.

All in all, the prospects for software developers in the US market isn’t good. If you want an IT career with some durability, then you should look a growth areas like network system administration or plan to quickly move from programming into a more lucrative and stable area such as project management or general IT management. If you have a love for programming, you might find it better financially to pursue it outside of work by contributing to an open source project.

However, in spite of all the negatives, there is one major good reason to pursue a programming career if programming is your passion. One of life’s greatest rewards is being able to enjoy your work because it really isn’t work to you. The best programmers I’ve worked with have had this attitude and are willing to continue programming in spite of career instability, crazy management decisions, brain-dead users and other such banes of a programmer’s life.

What do you think? If you already have a programming career would you do it all over again, knowing what you know about it now? If you’re a student, do you think your passion for programming is strong enough to make it in this field? Leave me a comment and let me know what your thoughts are on this issue.

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
Not That GoodCould Be BetterOKGoodGreat (5 votes, average: 5 out of 5)
Loading ... Loading ...

18 commentsOctober 11th, 2007

Link Round-Up for 10/10/07

Visit OpTempo.com, my other blogI found so many good links this week that my “link bucket” is overloaded so I’m going to publish this week’s Link Round-Up a day earlier than usual.

Web and .NET Development

I don’t talk about web development too often but here are some good articles I found recently that I found helpful.

If you need some ideas on the best ASP.NET practices to follow, Ode To Code has compiled this list of reference sites: Best Practice Resources For ASP.NET.

Unless you’ve been programming under a rock you know that AJAX enabling your Web 2.0 apps is that latest thing. Over at Design Vitality they’ve compiled a list of 43 Exceptionally Useful AJAX Applications.

CSS is almost a black art given the intracities of different browsers and the esoteric methods required sometimes to avoid dull old HTML tables. Design Vitality also has this helpful compilation article on how to Lose the Images: How to Get Rounded Corners, Gradients, Drop Shadows and More Using CSS.

Security is always a worry on the Internet. Sanjeev published this handy article on the Top 5 Application Security Vulnerabilities in Web.config Files. It’s packed with several good tips. Sanjeev should publish more often. He’s got some good stuff.

Mashable is offering a list of good .NET resource sites in this article: .NET TOOLBOX: 25+ Tools and Tips For Working With .NET.

Last up in this category is Joseph Guadagno. He provides us with a list of Database Drivers not provided by Microsoft.

Careers

On the career front, Jeff Atwood of Coding Horror tells the tale of writing a programming book in this article, Do Not Buy This Book. In it he describes why he prefers blogging to book writing.

In short, do not write a book. You’ll put in mountains of effort for precious little reward, tangible or intangible. In the end, all you will have to show for it is an out-of-print dead tree tombstone. The only people who will be impressed by that are the clueless and the irrelevant.

Charles Petzold responded to him in a post of his own, Hard Work, No Pay: What’s the Point?, which is also quite good, particularly considering his long career in authoring programming books.

Basically, the point is that if you want to write a book and make money, write the next Harry Potter. If you want to write a programming book, write a blog instead.

On the lighter side, over at Software Creation Mystery there is this post: Guide to Job Security for Software Developers: 15 Sure-Fire Methods. It gave me a laugh because I’ve worked with a few characters who used these job security methods.

Processes and Methods

James Golick talks about making the case for testing in this article: We don’t write tests. There just isn’t time for luxuries. If you need some good nuts-and-bolts figures to show a boss or project sponsor why testing is important, James has them for you.

Over at Developer.com Robert Bogue has this article on code reviews, Effective Code Reviews Without the Pain. Excellent work.

If you have “magic bullet” proponents in your organization, you’ll appreciate this article by Matt Stephens, Why UML won’t save your project

Pragmatic Jim had this interesting article on Agile Culture. It’s an interesting insight into this methodology.

Lastly, and also on Agile development, is the Q&A session with programming guru Steve McConnell: 5 Questions on Agile Development.

That’s all the links for this week. As always, let me know of any interesting .NET or general software development links by leaving me a comment or dropping me an email.

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
Not That GoodCould Be BetterOKGoodGreat (1 votes, average: 5 out of 5)
Loading ... Loading ...

2 commentsOctober 10th, 2007

How To Create Application Plug-ins In VB.NET

Plugging into an appSooner or later you’ll find that you want to make your application extensible. Perhaps you want to add customer specific processing modules to your backend processes. Maybe you’ll want to offer customers the ability to add their own functionality to your base application. VB.NET and the .NET Framework make this relatively easy to do. Let’s walk through the steps.

Define an Interface

The way to load a .NET assembly dynamically is through reflection. To make this process easier and more controllable within the context of an application I’ve found it best to define a plug-in interface, such as this one:

Public Interface IMyPlugIn

    Function TestFunction(ByVal value As String) As String

    Property MySetting() As String

End Interface

By using the interface this allows us to have a fixed definition for our plug-ins that our main application to work with. This means that we will need less main app code to support our plug-in.

Create A Class

Now we’re ready to create a plug-in class. Here’s the template that gets created:

Public Class CustomerXYZPlugin
    Implements MyPlugIn.IMyPlugIn

    Public Property MySetting() As String Implements MyPlugIn.IMyPlugIn.MySetting
        Get

        End Get
        Set(ByVal value As String)

        End Set
    End Property

    Public Function TestFunction(ByVal value As String) As String Implements MyPlugIn.IMyPlugIn.TestFunction

    End Function

End Class

Now, to complete the plug-in class we will need to add appropriate code it. You can’t define constructors in an interface so you’ll find it best to specify that you’ll either use a parameterless constructor or require that plug-in classes support a specific set of parameters. My preference has been to use parameterless ones and to supply ample properties for the plug-ins.

As for other code, as long as you define the interface you can do just about anything else you want.

Loading The Plug-In

Now we get to the heart of the matter, how to load the plug-in. There are several approaches you can take to this but here’s mine. First, let’s look at the code:

Private Function LoadPlugIn(ByVal LoadPath As String) As MyPlugIn.IMyPlugIn
    Dim NewPlugIn As MyPlugIn.IMyPlugIn
    Try
        Dim PlugInAssembly As Reflection.Assembly = Reflection.Assembly.LoadFrom(LoadPath)
        Dim Types() As Type
        Dim FoundInterface As Type
        Types = PlugInAssembly.GetTypes
        For Each PlugInType As Type In Types
            FoundInterface = PlugInType.GetInterface(“MyPlugIn.IMyPlugIn”)
            If FoundInterface IsNot Nothing Then
                NewPlugIn = DirectCast(PlugInAssembly.CreateInstance(PlugInType.FullName), MyPlugIn.IMyPlugIn)
                Exit For
            End If
        Next
    Catch ex As Exception
        ‘handle exceptions here
    End Try
    Return NewPlugIn
End Function

As you can see, we’re passing in the path to our plug-in and returning a plug-in interface object from the call. After declaring our return value we enter a try block. I recommend putting this loader logic in an exception handling block since you may be dealing with code that’s outside your direct control.

Next, we create a new Reflection.Assembly object from the file location that was passed into our function and extract the types from it. This allows a plug-in to have functionality beyond just the interface. We search for our interface and, when we find it, create a new instance and exit our search loop. Then we pass back the newly created plug-in object back to our main code.

Here’s a simple example of what the main code might look like:

Private Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
    Dim NewPlugIn As MyPlugIn.IMyPlugIn = LoadPlugIn(TextBox1.Text)
    NewPlugIn.MySetting = “Hello World”
    Dim OurTestPlugInValue As String = NewPlugIn.TestFunction(“Try It!”)
End Sub

Those are the steps to adding a simple plug-in to your application. Of course, there are more things you can do with Reflection and I suggest that you investigate them if you’re thinking about implementing this in one of your apps. Remember that there is a performance penalty for using Reflection and there are security considerations as well so make sure you factor them into your design.

If you have any questions or observations about using Reflection to create plug-ins, let me know by leaving 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
Not That GoodCould Be BetterOKGoodGreat (2 votes, average: 4.5 out of 5)
Loading ... Loading ...

6 commentsOctober 9th, 2007

Sacred Cows Make Great Steaks

Some Sacred Cows can disguise themselves quite well.Do you feel like you are in a creative rut either as an individual or a team? How many sacred cows does your organization have? Are they holding you back in developing the best software you can? I started thinking about this after reading the US Navy Monkey Experiment article. Often in software development teams and individual programmers as well, invent sacred cows. These ‘cows’ can be a particular language, tool kit, or methodology. Eventually it gets to the point where the organization, or person, becomes unable and unwilling to adapt to change. Ultimately, it’s a self-defeating paradigm.

I see this a lot in teams and individuals who’re unwilling to move on from VB6. They cling to their sacred cow and refuse to consider alternatives whether it’s VB.NET, C#, Java, or something else. You’ll see this in the fervor some attach to the latest new methodology. The problem is that creative thinking is sacrificed to the cow. People get so locked into the approach they’re using that they’re unable to see the merits of alternative approaches. Like the monkeys in the experiment they attack anyone who tries something out of the norm.

Time for a BBQ?

Is it time that you turn your sacred cows into steaks? Here are some steps you can take.

1. Ask why are we doing things this way?

If you can’t answer this then you might be like the monkeys in the story, simply acting on what someone else told you without really knowing why. But, if you can answer it, then…

2. Ask does this reason still exists?

Maybe you know why you or your team started doing things this way but are the reasons for this still applicable? It may have been a good idea to start a new project in 1998 with VB6 but is it still a good idea in 2007? Perhaps a programming library worked well for Project A but it’s a burden to use it in Project B. Is it really a good idea to use it? Be willing to make some tough choices and stop paying homage to the cow.

3. Ask what are the pluses and minuses of continuing to do things this way?

There could be good reasons to continue doing what you’ve been doing. Are there? Once you’ve reached this point you should prepare yourself to honestly answer if the pluses outweigh the minuses or vice versa. At least by going through the exercise, especially as a team, you should be able to identify where improvement is needed. Sometimes only minor adjustments are needed but other times tougher measures may be required. Sometimes a destructive change, where old ways are discarded, can be helpful. Take the time to evaluate this possibility in yourself or in your team and see if it applies to you.

Let me know if you have made this kind of change or if you think this kind of change isn’t necessary by leaving me a comment. I would like to hear your opinions.

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
Not That GoodCould Be BetterOKGoodGreat (No Ratings Yet)
Loading ... Loading ...

1 commentOctober 8th, 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