Francesco's blog

 Friday, January 11, 2008

Many readers asked whether I was about to release a book about VB 2008 and, more in general, how come I have reduced my writing activity so dramatically. The answer is in this post.

Immediately after publishing my C# 2005 book I started working on a very ambitious software project. Now, after exactly two years of hard work, VB Migration Partner is in beta test stage and is quickly approaching the public release.

The name of this tool says it all: in a nutshell, it is a converter of VB6 applications to VB.NET. I won’t waste your time trying to emphasize how weak the Upgrade Wizard that comes with Visual Studio is: if you’ve never tried it out, just google for “vb6 migration” and read what developers and bloggers have to say about it. Our goal at Code Architects was to build a better mouse trap than that.

A word on the migration-vs-rewriting debate: Many industry experts suggest that you should rewrite your VB6 from scratch rather than trying to port it to .NET automatically using a conversion tool, because the two environments are just too different. In theory this argument makes a lot of sense; in practice, however, when you have a real-world business app with some hundreds thousands lines of code – or even millions of lines! – a rewrite from scratch is simply too expensive, especially when the developers who wrote it originally aren’t working with the company any longer, the documentation is poor, remarks are scarce, etc. When facing the perspective of investing many years/man in this daunting task, it’s no surprise that many companies have postponed the migration to “some other time.” Now they are realizing, however, that the migration step can’t be postponed any longer, either because a few VB6 apps don’t work under Microsoft Vista – possibly because they use 3rd-party controls that are incompatible with the new Microsoft operating system – or, above all, because Microsoft declared that VB6 support ends on March 2008.

The problem is, automatic code converters don’t have a good reputation and rarely keep their promises, regardless of the language you are migrating from/to. In most cases, they manage to convert 95% of existing code, or less. With a 100,000 line application – a medium-size application of average complexity, then – having to manually fix the remaining 5% means that you have to fix about five thousand lines. It doesn’t sound too bad, until you realize that most of these “fixes” might take hours or even days. For example, consider that VB6 and VB.NET have two vastly different (and incompatible) programming models for drag-and-drop. Therefore one OLEDrag method counts as an individual problematic statement, yet it forces you to rewrite a large portion of your code. Drag-and-drop isn’t the only example, because the same concept applies to graphic statements, printing, data-binding, object finalization, component initialization, and many others.

We tested our VB Migration Partner on hundreds of VB6 apps – for well over one million lines – and found out that it delivers code that compiles and runs correctly most of the times, with an average of one compilation error every 1,100 lines of code. This corresponds to an accuracy higher than 99.9%. Not bad, uh? Of course the actual accuracy depends on how well the VB6 code is and on the features that the application uses, thus you can get a better idea of how good our tool is by having a look at the VB6 features that itsupports ...and that are out of reach for most other conversion tool on the market:

  • arrays with nonzero LBound
  • Gosub, On...Goto, and On ...Gosub
  • auto-instancing variables (Dim x As New Person), which keep their lazy-instantiation feature even under VB.NET
  • As Any parameters and callback addresses in Declare parameters (e.g. EnumWindows)
  • default properties resolved correctly even for late-bound variables
  • deterministic finalization for objects such as Connection and Recordset, to ensure that the connection is correctly closed when the variable is set to Nothing or the current scope is exited
  • (limited) support for Variant variable and null propagation in expressions
  • all 60+ controls in the VB6 toolbox, with the only exceptions of OLE container and Repeater, plus the support for common ActiveX controls and components such as WebBrowser, ScriptControl, Scripting runtime, and the MSWLess library
  • control arrays, including arrays of 3-rd party controls
  • popup menus
  • the Controls.Add method and the VBControlExtender object, to dynamically create data-entry forms
  • graphic methods (Line, Circle, PSet, PaintPicture, etc.), with support for any ScaleMode, including custom user modes
  • the Printer object and the Printers collection
  • OLE drag-and-drop
  • UserControl classes, with support for advanced features such as the Ambient and Extender objects
  • data-binding to DAO, RDO, and ADO Data controls, ADO recordsets, DataEnvironment objects
  • non-hierarchical DataEnvironment objects
  • ADO data source and simple data consumer classes and user controls (e.g. custom ADO Data controls)
  • MultiUse, PublicNotCreatable, GlobalMultiUse classes
  • persistable classes, MTS/COM+ classes

The number of supported features is so high that it is simpler to list the features that are not supported: UserDocument, PropertyPage, WebClass and DHTML Page components; undocumented methods (VarPtr, ObjPtr, StrPtr); “classic” drag-and-drop, and little else.

VB Migration Partner can convert an entire VB6 project group in one operation, in which case it typically delivers better quality code because it can see “inside” a DLL that belongs to the group. The tool also includes a very sophisticated code analyzer that can spot unused members: a large project that has evolved over many years can easily include 5-10% of “dead code”, thus this feature alone can save you a lot of precious time because it allows you to focus on just the code that is really important.

One of the secrets for such high error-free conversion factor is the support for migration pragmas. A migration pragma is a special remark that you can add to the original VB6 code and that teaches VB Migration Partner how a given portion of code must be translated, if many alternatives exist. For example, the following ArrayBounds pragma tells VB Migration Partner that all the arrays in the current projects must have their lower bound index forced to zero:
          '##project:ArrayBounds ForceZero
Pragmas can have project, class, method, or variable scope. A pragma scoped at the variable- or method-level always have higher priority than pragmas scoped at the project- or class-level. For example, you can override the previous pragma inside a method, and then override this latter pragma for a given array variable:
          Sub Test()
             '## ArrayBounds Shift
             '## arr.ArrayBounds ForceZero
             '## names.ShiftIndexes 1
             Dim names(1 To 10) As String
             Dim values(1 To 10) As Long
             Dim arr(1 To 10) As Integer
             names(1) = "John": names(2) = "Ann"
             '...
          End Sub

The Shift option tells VB Migration Partner that the LBound and UBound indexes must be shifted towards zero, so that the total number of elements in the array is preserved. The ShiftIndexes pragma –applied only to the names array – ensures that constant indexes are correctly shifted too:
          Sub Test()
             Dim names(9) As String
             Dim values(9) As Integer
             Dim arr(0 To 10) As Short
             names(0) = "John": names(1) = "Ann"
          End Sub

VB Migration Partner supports over 50 pragmas. For example, the SetName pragma changes the name of a control or variable during the migration, SetType changes its type, AutoNew implements the auto-instancing behavior of As New variables, AutoDispose implements the deterministic finalization when the variable is set to Nothing or the current scope is exited, and so forth.

One of the main defects of a “traditional” conversion tool is that – after the first migration – there is no relationship between the original VB6 project and the new VB.NET project. If the migration process takes weeks or months – which is common for large projects – and if the VB6 application must evolve in the meantime with new features and bug fixing, then at the end of the migration process the VB.NET code is already outdated and must be manually patched. The margin for mistakes in this phase is very high.

VB Migration Partner allows you to work around this issue, by means of pragmas and what we call the convert-text-fix cycle methodology. In a nutshell, you can iteratively migrate a given VB6 project by reaching the zero compilation errors stage and then the zero runtime error stage by simply inserting pragmas in the original project, but without modifying any VB6 executable statement. Thanks to the convert-test-fix cycle you can face complex migration tasks and keep the VB6 and VB.NET versions of your app always in sync.

I am especially proud of VB Migration Partner’s refactoring engine, which is able to apply many optimization techniques the result of the “raw” conversion. For example, it can merge variable declarations and the initializations, to generate Return statements, and to leverage the compound assignment operators (e.g. +=), and more:

    Function GetValue() As Long     =>     Function GetValue() As Integer
       Dim x As Long                          Dim x As Integer = 123
       x = 123                                ...
       ...                                    If x > 0 Then
       If x > 0 Then                             Return x
          GetValue = x                        ElseIf x = 0 Then
          Exit Function                          Return -1
       ElseIf x = 0 Then                      End If
          GetValue = -1                       ...
          Exit Function                       x += 1
       End If                                 ...
       ...                                 End Function
       x = x + 1
       ...
    End Function

Other refactoring techniques can be achieved by means of pragmas. For example, you can move the declaration of a variable inside a For or For Each method, as in this example:

    Dim i As Integer                =>     For i As Integer = 1 To 100
    For i = 1 To 100                          ...
       ...                                 Next
    Next

On top of the cake: in spite of all these features, VB Migration Partner is up to 8 times faster than the Upgrade Wizard that comes with Visual Studio!

You can learn all about VB Migration Partner on our new site www.vbmigration.com. The web site hosts a Resource section where we dissect each and every difference between VB6 and VB.NET – most of which have never been documented anywhere – thus you can find many useful tips even if you don’t plan to use our tool. I also opened a new blog, entirely devoted to migration techniques.

That's it for now. Stay tuned!

1/11/2008 11:00:33 PM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |  Comments [4]  | 
 Wednesday, April 11, 2007

I like the ability to extend the power of my applications by simply adding a reference to an assembly that contains the functions or the controls that I need. I like much less, however, the need to distribute and deploy many DLLs together with my executables. In this post I show a technique that I use to compress (nearly) all the DLLs of a Windows Forms application and "merge" them with the main EXE.

All the files you need are in this ZIP archive, which contains the AsmZip.exe utility (which you run from the command prompt) and two source files, Unzipper.cs and Unzipper.vb. I suggest that you copy the AsmZip utility in a directory listed on the system path, to run it easily.

Step-by-step
These are the steps you must follow to implement the technique.

1) Add either the Unzipper.vb or the Unzipper.cs file to the main project of your application, depending on the language you've used.

2) In the Main method, add a statement that initializes the AssemblyUnzipper class (which is defined in the Unzipper file you added in step 1).
       ' (Visual Basic 2005)
       CodeArchitects.AssemblyUnzipper.Initialize()
       // Visual C# 2005
       CodeArchitects.AssemblyUnzipper.Initialize();
It is essential that this statement runs before any other statement in the application, particularly before showing a form that contains a control implemented in one of the DLLs you want to compress. If you are working with VB and the application has a startup form (and therefore you don't have a Sub Main method), you should initialize the AssemblyUnzipper class from inside the startup form's static constructor:
      Shared Sub New()
         CodeArchitects.AssemblyUnzipper.Initialize()
      End Sub

3) compile the project, obviously in Release mode. (You should use this technique just before delivering the executable to your customer(s).

4) open a command prompt window from inside the application's \bin directory, and run the AsmZip utility as follows:
             AsmZip main.exe *.dll
where main.exe is the name of the main executable. The above command compresses *all* the DLLs in the directory and appends the compressed data to the main.exe file. If you want to compress just a subset of the DLLs that the application uses, you should specify their names, as in this example:
             AsmZip main.exe CodeArchitects*.dll Microsoft*.dll
There can be a few good reasons not to compress some of the DLLs used by the applications, as I'll explain shortly.

5) You can now delete all the DLLs that you have compressed, because the application - thanks to the AssemblyUnzipper class - is able to find them at the end of its executable file, to decompress them, and to load them in memory.

Pros
Before proceeding with an explaination of the technique's inner details, let's summarize its advantages:

a) simpliefied deployment: you need to distribute fewer files (often just the main EXE)
b) more robust applications: end users can't break the application by accidentally deleting one of its DLLs
c) fewer bytes on disk: all DLLs are compressed and appended to the main EXE file
d) the ability to "hide" some of your trade secrets, for example which 3rd party controls you've used
e) a slightly better protection of your intellectual property: compressed DLLs can't be decompiled, at least not as easily as uncompressed DLLs .

The last two points aren't a real protection against even unexperienced malicious hackers, if he or she is determined to peek into your application. To do so he would just need to decompile the main EXE, understand how the AssemblyZipper class works, and write a short programma that works similarly but saves the uncompressed assemblies to disk. In other words, don't rely on this technique to protect your code from reverse engineering.

The AsmZip tool relies on the GZipStream class to compress the original DLLs, therefore the compression factor that you achieve with this technique is lower than the one you can obtain with WinZip or WinRar, but it is usually more than adequate, as the following figure shows.


How it works
This technique relies on the AssemblyResolve event of the AppDomain object. This event fires when the CLR loads an assembly referenced by the running application. By handling this event you can perform some nice tricks that wouldn't be possible otherwise. For example, you might load satellite assemblies from a network share or from a binary field in a database.

The AssemblyUnzippere class uses this event to search the required assembly from a compressed stream that has been appended to the application's main EXE file:
      // the handler for AssemblyResolve event
      static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs e)
      {
         // find the assembly with given name, cause error if not found
         AssemblyInfo info = null;
         if ( AsmInfos.TryGetValue(e.Name, out info) )
            return ExtractAssembly(info);
         // signal error
         Debug.WriteLine("Failed to uncompress assembly " + info.Name);
         return null;
      }
Each AssemblyInfo object keeps track of where, in the main EXE file, the compressed data for each DLL is located. The AsmInfos dictionary enables the code to quickly locate the information associated with a DLL with given name. This dictionary is created inside the Initialize method, when the application is launched, and is then used each time the application attempts to load an assembly. For more details, see comments in either the VB or the C# source code.

Limitations
I tried this technique with several Windows Forms apps, without any problem. The main issue is that compressed assemblies loaded programmatically have their Location property set to null/Nothing, but if you don't use reflection to explore the assembly's feature you might never realize that the assembly was loaded in a nonstandard way. For example, if your app dynamically loads all the assemblies in a given directory, for example to explore their attributes, it is evident that it won't work as intended if these DLLs have been compressed and then deleted. In such cases, you should exclude these DLLs from compression.

The AssemblyZipper class works only with Windows Forms applications. For what I know, it is possible to use the AssemblyResolve event inside ASP.NET applications, but it isn't possible to use the AssemblyUnzipper in that context. However, the problems that this technique solves aren't considered as real issues under ASP.NET, therefore I don't think it makes sense to use it in web applications.

The only other limitation is that this technique works with DLLs but not with the main EXE. If you have a large EXE that uses some small DLLs, you won't achieve an interesting compression factor. In such a case, you might want to move your forms from the main EXE into a DLL and then compress the DLL with AsmZip. Even better, the main EXE might contain only the splash screen (if you have one) and it should load the startup form from the DLL that contains the actual application. Using this approach it is often possible to achieve an overall compression factor near or above 60 percent.

Note: in the first implementation of this technique I managed to successfully compress even the main EXE and used a small “stub” executable whose only job was to decompress and launch the actual EXE. After some tests, however, I found that the technique wasn’t very stable and I fell back to the technique described in this article.

4/11/2007 5:07:41 PM (GMT Daylight Time, UTC+01:00)  #    Disclaimer  |  Comments [6]  | 
 Tuesday, August 29, 2006

I know, I know, there are soooo many regular expression tester tools available on the 'Net, but I couldn't help creating my own. It's very simple, yet it supports all the basic features you'd espect from a tool of its kind, including code generation (VB and C#) and compilation to stand-alone assemblies. Best of all, it comes with source code. You can download it from the home page of my Visual Basic 2005 book (together with all other code samples in the book) or directly from here:

Executable (requires .NET Framework 2.0): RegexTester.zip (75.57 KB)
Source code (VB2005): RegexTester source.zip (88.15 KB)

Using the tool is quite simple. The main window is divided in three panes: (a) the pane where you enter the regex, (b) the pane where you load the text the regex must be applied to, (c) the result pane. A fourth pane appears when you select the Replace item from the Commands menu, and it's where you enter the replace pattern. As you can see in the image below, you can enter most regex patterns by selecting them from the context menu:

You select the kind of command (Find, replace, Split) from the Commands menu and you select one or more regex options from the Options menu:

After selecting the proper options, you press the F5 key (the Run item in the Commands menu) to execute the regex. Results are displayed in the bottom pane in a variety of formats and sort orders, which you can select from the Results menu, and the status bar displays the number of matches, the execution time, and the properties of the result currently highlighted in the result pane:

Alternatively, you can set all these options from the Properties dialog box (the Properties command in the File menu, or just press the F4 key):

Assigning a name to the current regex is important because you can save it on disk in a file with .regex extension, for later retrieval.

The Commands menu contains a couple of other interesting items. First, you can generate the C# or VB code for the current regular expression and copy it to the Clipboard:

Second, and more interesting, you can compile one or more regular expressions (including saved .regex projects) into a compiled assembly, which you can later reference from any .NET application. Using such compiled regexes is obviously faster than defining them in code, because you skip the parsing step:

 

That's it. You can use the YART tool for your own use, study its source code, modify and expands it as you like. If you find any major problems or add some noteworthy feature, just let me know.

C# | Regex | Tools | Visual Basic
8/29/2006 8:00:02 PM (GMT Daylight Time, UTC+01:00)  #    Disclaimer  |  Comments [1]  | 
 Monday, March 06, 2006

I am reorganizing my MP3 collection and found that I needed to rename a large quantity of files. Of course, there are many free utilities that allow this operation - and that can use MP3 tags in the process - but I thought that I might write one myself. Thanks to regular expressions, the task shouldn't be that hard. In fact, in a few minutes I came up with the following console application. As you see, most of the code is used to extract and validate arguments on the command line:

Imports System.Text.RegularExpressions
Imports System.IO

Module Renx

  
Function Main(ByVal args() As String) As Integer
     
Console.WriteLine("RENX (C) Francesco Balena / Code Architects Srl")

      Dim recurse As Boolean = False
     
Dim renameMode As Boolean = False
     
Dim oldNamePattern As String = Nothing
     
Dim newNamePattern As String = Nothing

      ' analyze each argument
     
For Each arg As String In args
        
Select Case arg.ToLower()
           
Case "/s", "-s"
              
recurse = True
            
Case "/r", "-r"
              
renameMode = True
           
Case "/h", "-h"
              
Return ShowHelp(0)
           
Case Else
              
If oldNamePattern Is Nothing Then
                 
oldNamePattern = "^" & arg & "$"
              
ElseIf newNamePattern Is Nothing Then
                 
newNamePattern = arg
              
Else
                 
Return ShowHelp(1)
              
End If
        
End Select
     
Next

      ' check that we have both mandatory arguments
     
If oldNamePattern Is Nothing OrElse newNamePattern Is Nothing Then
        
Return ShowHelp(1)
     
End If
     
' create the regex and check that pattern syntax is ok
     
Dim reSearch As Regex
     
Try
        
reSearch = New Regex(oldNamePattern, RegexOptions.IgnoreCase)
        
' test the replace pattern as well
        
Dim tmp As String = reSearch.Replace("a dummy string", newNamePattern)
      
Catch ex As Exception
         Console.WriteLine(
"SYNTAX ERROR: {0}", ex.Message)
        
Return 3
     
End Try
     
Console.WriteLine()

      ' iterate over all files in current directory (and its subdirectories, if recurse mode)
     
Dim searchOpt As SearchOption = SearchOption.TopDirectoryOnly
     
If recurse Then searchOpt = SearchOption.AllDirectories

      Dim parsedFilesCount As Integer = 0
     
Dim renamedFilesCount As Integer = 0
     
Dim errorsCount As Integer = 0
     
For Each oldFile As String In Directory.GetFiles(Directory.GetCurrentDirectory(), "*.*", searchOpt)
         parsedFilesCount += 1
        
' the regex applies to name only
        
Dim oldName As String = Path.GetFileName(oldFile)
        
Dim ma As Match = reSearch.Match(oldName)
        
If ma.Success Then
           
' this is the new name
           
Dim newName As String = ma.Result(newNamePattern)
            Console.WriteLine(oldFile)
            Console.Write(
" => {0}", newName)
            renamedFilesCount += 1
           
' proceed with rename only if not in simulation mode
           
If renameMode Then
              
Try
                 
Dim dirName As String = Path.GetDirectoryName(oldFile)
                 
Dim newFile As String = Path.Combine(dirName, newName)
                  File.Move(oldFile, newFile)
              
Catch ex As Exception
                  Console.Write(
" -- ERROR: {0}", ex.Message)
                  errorsCount += 1
              
End Try
           
End If
           
Console.WriteLine()
        
End If
     
Next

      ' Display a report
     
If renameMode Then
        
Console.WriteLine("Summary: {0} parsed files, {1} renamed files, {2} errors", parsedFilesCount, renamedFilesCount, errorsCount)
     
Else
        
Console.WriteLine("Summary: {0} parsed files, {1} files affected", parsedFilesCount, renamedFilesCount)
         Console.WriteLine()
         Console.WriteLine(
"NOTE: Running in simulation mode. Specify the /R option to actually rename files.")
     
End If
     
' Return an error code
     
If errorsCount = 0 Then
        
Return 0
     
Else
        
Return 2
     
End If
  
End Function

   Function ShowHelp(ByVal exitCode As Integer) As Integer
     
Console.WriteLine()
      Console.WriteLine(
"Syntax: RENX <oldnamepattern> <newnamepattern> [/R] [/S] [/H]")
      Console.WriteLine(
" oldnamepattern : regex that selects the files to be renamed")
      Console.WriteLine(
" newnamepattern : regex that specifies how files must be renamed")
      Console.WriteLine(
" /R : rename files")
      Console.WriteLine(
" /S : iterate over subdirectories")
      Console.WriteLine(
" /H : display this help")
      Console.WriteLine(
"NOTE: By default the program runs in simulation mode, and just displays how files would be renamed.")
      Console.WriteLine(
" You must specify the /R option to actually rename the files.")
     
Return exitCode
  
End Function

End Module

At the very minimum, the RENX utility requires two arguments: a regex that specifies which files in the current directory (and its subdirectories, if you add the /S option) must be renamed, and a second regex that specifies how to rename the files that are matched by the first regex. The power of RENX is the fact that the first regex can (actually, must) specify one or more groups of characters, and these groups are then referenced in the second regex. For example, let's suppose that I have a folder with the following files:

        01 Speak to Me.mp3
        02 On the Run.mp3
        03 Time.mp3
        04 The Great Gig in the Sky.vb3
        05 Money.mp3
        06 Us and Them.mp3
        07 Any Colour You Like.vbr
        08 Brain Damage.mp3
        09 Eclipse.vb3

and that I want to rename them as follows:

        01 - Speak to Me - The Dark Side of the Moon.mp3
        02 - On the Run - The Dark Side of the Moon.mp3
        03 - Time - The Dark Side of the Moon.mp3
        04 - The Great Gig in the Sky - The Dark Side of the Moon.vbr
        05 - Money - The Dark Side of the Moon.mp3
        06 - Us and Them - The Dark Side of the Moon.mp3
        07 - Any Colour You Like - The Dark Side of the Moon.vb3
        08 - Brain Damage - The Dark Side of the Moon.mp3
        09 - Eclipse - The Dark Side of the Moon.vbr

Here's the RENX command that does it:

        RENX "(\d\d) (.+?)(\..+)"    "${1} - ${2} - The Dark Side of the Moon.${3}"

Notice that the first regex creates three groups by enclosing them in parenthesis: (\d\d) matches the song number, (.+?) matches the song title, and (\..+) matches the file extension, dot included. The second argument can then reorder these three groups, using the ${N}, where N is the position of the group as specified in the first regex. It is therefore to insert a dash after the song number, and the albumname after the song title.

Because the RENX utility is quite dangerous, by default it doe NOT rename the files, and it just lists how files would be renamed. To actually proceed with the rename operation, you must specify the /R option:

        RENX "(\d\d) (.+?)(\..+)"    "${1} - ${2} - The Dark Side of the Moon${3}" /R

That's all. You can play with the source code to extend the RENX utility as you prefer, and maybe turn it into a Windows Form application, or you can download the binary version from this link: Renx.zip (5.51 KB)

3/6/2006 5:30:10 PM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |  Comments [0]  | 
 Wednesday, December 14, 2005

In a previous post I introduced a tiny utility to clean up Visual Studio projects. I have introduced minor fixes to it since then, so this is the most recent version, which also deletes *.suo and *.user files and produces a report of all the files and folders that couldn't be deleted for any reason:

Imports System.IO

Module Module1
  
Sub Main(ByVal args() As String)
      Console.WriteLine(
"VSProjCleaner tool (C) 2005 Francesco Balena, Code Archirects")
     
If args.Length = 0 Then
        
Console.WriteLine("Removes BIN and OBJ folders, .suo and .user files from Visual Studio projects")
         Console.WriteLine()
         Console.WriteLine(
" SYNTAX: VSProjCleaner dirname")
         Console.WriteLine()
        
Return
     
End If
     
Console.WriteLine()

      ' Use current directory if no argument has been specified
     
Dim rootDir As String = Directory.GetCurrentDirectory()
     
If args.Length > 0 Then rootDir = args(0)
     
' Read all the folder names in the specified directory tree
     
Dim dirNames() As String = Directory.GetDirectories(rootDir, "*.*", SearchOption.AllDirectories)
     
Dim errorsList As New List(Of String)

      ' delete any .suo and vbproj.user file
     
For Each dir As String In dirNames
        
Dim files As New List(Of String)
         files.AddRange(Directory.GetFiles(dir,
"*.suo"))
         files.AddRange(Directory.GetFiles(dir,
"*.user"))
        
For Each fileName As String In files
           
Try
              
Console.Write("Deleting {0} ...", fileName)
               File.Delete(fileName)
               Console.WriteLine(
"DONE")
            Catch ex As Exception
               Console.WriteLine()
               Console.WriteLine(
" ERROR: {0}", ex.Message)
               errorsList.Add(fileName &
": " & ex.Message)
            
End Try
         
Next
      
Next

      ' Delete all the BIN and OBJ subdirectories
      
For Each dir As String In dirNames
         
Dim dirName As String = Path.GetFileName(dir).ToLower()
         
If dirName = "bin" OrElse dirName = "obj" Then
            
Try
               
Console.Write("Deleting {0} ...", dir)
               Directory.Delete(dir,
True)
               Console.WriteLine(
"DONE")
            
Catch ex As Exception
               Console.WriteLine()
               Console.WriteLine(
" ERROR: {0}", ex.Message)
               errorsList.Add(dir &
": " & ex.Message)
            
End Try
         
End If
      
Next
      
Console.WriteLine()
      Console.WriteLine(
New String("-"c, 60))
      
If errorsList.Count = 0 Then
         
Console.WriteLine("All directories and files were removed successfully")
      
Else
         
Console.WriteLine("{0} directories or directories couldn't be removed", errorsList.Count)
         Console.WriteLine(
New String("-"c, 60))
         
For Each msg As String In errorsList
            Console.WriteLine(msg)
         
Next
      
End If
   
End Sub
End
Module

You can download the binary version here: VSProjCleaner.exe (24 KB) 
or the complete solution here: VSProjCleaner_Source.zip (15.08 KB)

Using this tool couldn't be simpler: just run it from the command window and pass a folder name as an argument, enclosing it in double quotes if it contains spaces:
                            VSPROJCLEARNER "c:\my projects\testproj"
The tool recursively visits all the folders and deletes all BIN and OBJ directories, and deletes *.suo and *.user files. At the end of the process it lists all the folders and files that couldn't be removed, if any.

DISCLAIMER: I have tested this code against my own projects and it always worked correctly, but I don't should be held responsible for any loss of important files (for example, a .user file that has nothing to do with a Visual Studio project.). For this reason, I urge you to apply this tool only to a COPY of your projects

12/14/2005 9:58:58 AM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |  Comments [0]  | 
 Monday, November 21, 2005

I am back from the Windows Professional Conference (Milan, Italy), for which I also server as the chairman for two of the four tracks. The conference touched virtually all the new features of Visual Studio and SQL Server 2005, plus tons of other topics. But that's another story.

When preparing the material for the conference I had to pack all my code samples in a zip file. Even after zipping them, I came up with a 7-8M file, which is a bit too much. So I was about to manually delete all the files that could be recreated by recompiling the projects. It's the same old story, that repeat itself with all conferences, books, articles for magazines and blog posts.

Instead of using the manual approach, this time I decided to write a tiny utility that does the work for me. It took (literally) two minutes to write a console utility that takes the path as an argument and recurses over that directory tree to remove all the folders named "bin" and "obj". If a delete operation fails, a message error is displayed. (This happens when an executable is running and is therefore locked by the operating system.) The code is especially concise thanks to an overload of the Directory.GetDirectories method (added in .NET 2.0) that returns all the directory in a tree.

Imports System.IO

Module Module1
  
Sub Main(ByVal args() As String)
      ' Use current directory if no argument has been specified
     
Dim rootDir As String = Directory.GetCurrentDirectory()
     
If args.Length > 0 Then rootDir = args(0)
     
' Read all the folder names in the specified directory tree
     
Dim dirNames() As String = Directory.GetDirectories(rootDir, "*.*", SearchOption.AllDirectories)
     
Dim errors As Integer = 0

      ' Delete all the BIN and OBJ subdirectories
     
For Each dir As String In dirNames
        
Dim dirName As String = Path.GetFileName(dir).ToLower()
           
If dirName = "bin" OrElse dirName = "obj" Then
              
Try
                 
Console.Write("Deleting {0} ...", dir)
                  Directory.Delete(dir,
True)
                  Console.WriteLine(
"DONE")
              
Catch ex As Exception
                  Console.WriteLine()
                  Console.WriteLine(
" ERROR: {0}", ex.Message)
                  errors += 1
              
End Try
           
End If
        
Next

         Console.WriteLine()
        
If errors = 0 Then
           
Console.WriteLine("All directories were removed successfully")
        
Else
           
Console.WriteLine("{0} directories couldn't be removed")
        
End If
    
End Sub
End
Module

In addition to using this tool from the command line, you can add it to the Tools menu, so that you can quickly delete all the files produced by compiling the current solution, by using this command:

               DELETEBINPATH $(SolutionDir)

where of course DeleteBinPath is the name you used when compiling the utility.

UPDATE: I have posted a new version of this utility in a more recent post.

11/21/2005 9:23:28 AM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |  Comments [0]  | 
 
Get RSS/Atom Feed
RSS 2.0 | Atom 1.0
Search in the blog
Archive
<May 2008>
SunMonTueWedThuFriSat
27282930123
45678910
11121314151617
18192021222324
25262728293031
1234567
Categories

Powered by: newtelligence dasBlog 1.8.5223.1