Tag Archives: visual basic

Should you convert your Visual Basic .NET project to C#? Why and why not…

When Microsoft first started talking about Roslyn, the .NET compiler platform, one of the features described was the ability to take some Visual Basic code and “paste as C#”, or vice versa.

Some years later, I wondered how easy it is to convert a VB project to C# using Roslyn. The SharpDevelop team has a nice tool for this, CodeConverter, which promises to “Convert code from C# to VB.NET and vice versa using Roslyn”. You can also find this on the Visual Studio marketplace. I installed it to try out.

image

Why would you do this though? There are several reasons, the foremost of which is cross-platform support. The Xamarin framework can use VB to some extent, but it is primarily a C# framework. .NET Core was developed first for C#. Microsoft has stated that “with regard to the cloud and mobile, development beyond Visual Studio on Windows and for non-Windows platforms, and bleeding edge technologies we are leading with C#.”

Note though that Visual Basic is still under active development and history suggests that your Windows VB.NET project will continue running almost forever (in IT terms that is). Even Visual Basic 6.0 applications still run, though you might find it convenient to keep an old version of Windows running for the IDE.

Still, if converting a project is just a right-click in Visual Studio, you might as well do it, right?

image

I tried it, on a moderately-size VB DLL project. Based on my experience, I advise caution – though acknowledging that the converter does an amazing job, and is free and open source. There were thousands of errors which will take several days of effort to fix, and the generated code is not as elegant as code written for C#. In fact, I was surprised at how many things went wrong. Here are some of the issues:

The tool makes use of the Microsoft.VisualBasic namespace to simplify the conversion. This namespace provides handy VB features like DateDiff, which calculates the difference between two dates. The generated project failed to set a reference to this assembly, generating lots of errors about unknown objects called Information, Strings and so on. This is quick to fix. Less good is that statements using this assembly tend to be more convoluted, making maintenance harder. You can often simplify the code and remove the reference; but of course you might introduce a bug with careless typing. It is probably a good idea to remove this dependency, but it is not a problem if you want the quickest possible port.

Moving from a case-insensitive language to a case-sensitive language is a problem. Visual Studio does a good job of making your VB code mostly consistent with regard to case, but that is not a fix. The converter was unable to fix case-sensitivity issues, and introduced some of its own (Imports System.Text became using System.text and threw an error). There were problems with inheritance, and even subtle bugs. Consider the following, admittedly ugly and contrived, code:

image

Here, the VB coder has used different case for a parameter and for referencing the parameter in the body of the method. Unfortunately another variable with the different case is also accessible. The VB code and the converted C# code both compile but return different results. Incidentally, the VB editor will work very hard to prevent you writing this code! However it does illustrate the kind of thing that can go wrong and similar issues can arise in less contrived cases.

C# is more strict than VB which causes errors in conversion. In most cases this is not a bad thing, but can cause headaches. For example, VB will let you pass object members ByRef but C# will not. In fact, VB will let you pass anything ByRef, even literal values, which is a puzzle! So this compiles and runs:

image

Another example is that in VB you can use an existing variable as the iteration variable, but in C# foreach you cannot.

Collections often go wrong. In VB you use an Item property to access the members of a collection like a DataReader. In C# this is omitted, but the converter does not pick this up.

Overloading sometimes goes wrong. The converter does not always successfully convert overloaded methods. Sometimes parameters get stripped away and a spurious new modifier is added.

Bitwise operators are not correctly converted.

VB allows indexed properties and properties with parameters. C# does not. The converter simply strips out the parameters so you need to fix this by hand. See https://stackoverflow.com/questions/2806894/why-c-sharp-doesnt-implement-indexed-properties if the language choices interest you.

There is more, but the above gives some idea about why this kind of conversion may not be straightforward.

It is probably true that the higher the standard of coding in the original project, the more straightforward the conversion is likely to be, the caveat being that more advanced language features are perhaps more likely to go wrong.

Null strings behave differently

Another oddity is that VB treats a String set to null (Nothing) as equivalent to an empty string:

Dim s As String = Nothing

If (s = String.Empty) Then ‘TRUE in VB
     MsgBox(“TRUE!”)
End If

C# does not:

String s = null;

   if (s == String.Empty) //FALSE in C#
    {
        //won’t run
    }

Same code, different result, which can have unfortunate consequences.

Worth it?

So is it worth it? It depends on the rationale. If you do not need cross-platform, it is doubtful. The VB code will continue to work fine, and you can always add C# projects to a VB solution if you want to write most new code in C#.

If you do need to move outside Windows though, conversion is worthwhile, and automated conversion will save you a ton of manual work even if you have to fix up some errors.

There are two things to bear in mind though.

First, have lots of unit tests. Strange things can happen when you port from one language to another. Porting a project well covered by tests is much safer.

Second, be prepared for lots of refactoring after the conversion. Aim to get rid of the Microsoft.VisualBasic dependency, and use the stricter standards of C# as an opportunity to improve the code.

Microsoft Project Siena: another go at the spirit of Visual Basic

Remember Visual Basic? By which I mean, not the current language that is a case-insensitive alternative to C# that does much the same thing, but the original rapid app development tool that democratised Windows development back in 1991. At the time, Windows development was a sought-after skill but rather difficult. VB meant anyone could create an application; pros could build excellent ones, amateurs something ugly and unmaintainable, but nevertheless something that worked. The transition to .NET brought many benefits, but also more complexity. The latest evolution of the Windows client, the Windows Runtime, is also challenging to get right (I am currently writing a simple C# game on the platform).

Microsoft has been looking for a new “VB” for years. 2007: Popfly (now abandoned). 2011: Lightswitch. Now we have Project Siena.

image

Siena is an app for building apps. An app is a Siena document with a .siena extension. Here is what Microsoft’s Bryan Group says:

Microsoft Project Siena (code name) is the beta release of a new technology for business experts, business analysts, consultants, and other app imagineers. Now, without any programming, you can create powerful apps for the device-first and cloud-connected world, with the potential to transform today’s business processes.

Building Siena apps is as easy as editing a document. Place some visuals on a canvas. Hook them up to your data. Customize how your app looks and works. Then, if you need special logic and intelligence, write Excel-like expressions. You can use your app immediately, or share it with colleagues or the world.

This sounds great to me. I installed it and set about building an app. I decided to create the same app I have used to try out dozens of programming tools over the years: a to-do list with the ability to add and remove tasks

image

Building the user interface went OK, but how do I add and remove items from the list? I have got as far as figuring out that I need to type the right magic into the OnSelect property of a button:

image

I will let you know when I have worked out what to do next. I will observe that the environment is geared towards data binding, rather than directly updating the user interface, and remote data, such as binding to tables in Azure Mobile Services, a REST API, an RSS feed or a SharePoint list. However you can also bind to an Excel spreadsheet for local data.

Unfortunately there is no “Run” button. You can preview your Siena app by pressing F5 or tapping the Run button in the top app bar.

To deploy your Siena app, you hit Publish:

image 

This creates a package of files, including InstallApp.exe. Siena generates HTML and JavaScript so you can learn a lot about the environment by poking around in the generated files.

image

Run InstallApp.exe and the app installs into your local PC. Mine runs fine, it just does not work yet.

Siena, as is usual for this type of release, suffers from lack of documentation. There is a function reference and a few sketchy help topics. There are also some sample apps. Here is what the Personnel Manager has in the OnSelect of its Add button; perhaps this is a clue:

UpdateIf(Assoc,ID = ThisItem!ID,{AssignedTo:SelectedDepartment, Time:Now()}); RemoveIf(SelectedAssociates, ID = ThisItem!ID)

While it is great to have a genuinely easy visual interface builder, the development features of Visual Studio are greatly missed; the code editor as far as I can tell is limited to a single line in a text input field, though you do get a squiggly underline if you do it wrong, and a bit of code completion.

How is the average “business expert, business analyst, consultant, and other app imagineer” going to get on with Project Siena? That is the question; and in the current preview I’d guess they will be flummoxed and go straight back to Excel or Access, though I would love to be proved wrong.

It looks like a lot of work has gone into this though, and no doubt better documentation and enhanced features are on the way.

Hands On with Visual Studio LightSwitch – but what is it for?

Visual Studio LightSwitch, currently in public beta, is Microsoft’s most intriguing development tool for years. It is, I think, widely misunderstood, or not understood; but there is some brilliant work lurking underneath it. That does not mean it will succeed. The difficulty Microsoft is having in positioning it, together with inevitable version one limitations, may mean that it never receives the attention it deserves.

Let’s start with what Microsoft says LightSwitch is all about. Here is a slide from its Beta 2 presentation to the press:

image

Get the idea? This is development for the rest of us, "a simple tool to solve their problems” as another slide puts it.

OK, so it is an application builder, where the focus is on forms over data. That makes me think of Access and Excel, or going beyond Microsoft, FileMaker. This being 2011 though, the emphasis is not so much on single user or even networked Windows apps, but rather on rich internet clients backed by internet-hosted services. With this in mind, LightSwitch builds three-tier applications with database and server tiers hosted on Windows server and IIS, or optionally on Windows Azure, and a client built in Silverlight that runs either out of browser on Windows – in which case it gets features like export to Excel – or in-browser as a web application.

There is a significant issue with this approach. There is no mobile client. Although Windows Phone runs Silverlight, LightSwitch does not create Windows Phone applications; and the only mobile that runs Silverlight is Windows Phone.

LightSwitch apps should run on a Mac with Silverlight installed, though Microsoft never seems to mention this. It is presented as a tool for Windows. On the Mac, desktop applications will not be able to export to Excel since this is a Windows-only capability in Silverlight.

Silverlight MVP Michael Washington has figured out how to make a standard ASP.NET web application that accesses a LightSwitch back end. I think this should have been an option from the beginning.

I digress though. I decided to have a go with LightSwitch to see if I can work out how the supposed target market is likely to get on with it. The project I set myself was a an index of magazine articles; you may recognize some of the names. With LightSwitch you are insulated from the complexities of data connections and can just get on with defining data. Behind the scenes it is SQL Server. I created tables for Articles, Authors and Magazines, where magazines are composed of articles, and each article has an author.

The LightSwitch data designer is brilliant. It has common-sense data types and an easy relationship builder. I created my three tables and set the relationships.

image

Then I created a screen for entering articles. When you add a screen you have to say what kind of screen you want:

image

I chose an Editable Grid Screen for my three tables. LightSwitch is smart about including fields from related tables. So my Articles grid automatically included columns for Author and for Magazine. I did notice that the the author column only showed the firstname of the author – not good. I discovered how to fix it. Go into the Authors table definition, create a new calculated field called FullName, click Edit Method, and write some code:

partial void FullName_Compute(ref string result)
{
    // Set result to the desired field value
   result = this.Firstname + " " + this.Lastname;

}

Then you set FullName as the “Summary” field for the table.

Have we lost our non-developer developer? I don’t think so, this is easier than a formula in Excel once you work out the steps. I was interested to see the result variable in the generated code; echoes of Delphi and Object Pascal.

I did discover though that my app has a usability problem. In LightSwitch, the user interface is generated for you. Each screen becomes a Task in a menu on the left, and double-clicking opens it. The screen layout is also generated for you. My problem: when I tried entering a new article, I had to specify the Author from a drop-down list. If the author did not yet exist, I had to open an Authors editable grid, enter the new author, save it, then go back to the Articles grid to select the new author.

I set myself the task of creating a more user-friendly screen for new articles. It took me a while to figure out how, because the documentation does not seen to cover my requirement, but after some help from LightSwitch experts I arrived at a solution.

First, I created a New Data Screen based on the Article table. Then I clicked Add Data Item and selected a local property of type Author, which I called propAuthor.

image

Next, I added two groups to the screen designer. Screen designs in LightSwitch are not like any screen designs you have seen before. They are a hierarchical list of elements, with properties that affect their appearance. I added two new groups, Group Button and GroupAuthor, and set GroupAuthor to be invisible. Then I dragged fields from propAuthor into the Author group. Then I added two buttons, one called NewAuthor and one called SaveAuthor. Here is the dialog for adding a button:

image

and here is my screen design:

image

So the idea is that when I enter a new article, I can select the author from a drop down list; but if the author does not exist, I click New Author, enter the author details, and click Save. Nicer than having to navigate to a new screen.

In order to complete this I have to write some more code. Here is the code for NewAuthor:

partial void NewAuthor_Execute()
{
     // Write your code here.
     this.propAuthor = new Author();
     this.FindControl("GroupAuthor").IsVisible = true;
}

Note the use of FindControl. I am not sure if there is an easier way, but for some reason the group control does not show up as a property of the screen.

Here is the code for SaveAuthor:

partial void SaveAuthor_Execute()
{
    // Write your code here.
    this.ArticleProperty.Author = propAuthor;
    this.Save();
}

image

This works perfectly. When I click Save Author, the new author is added to the article, and both are saved. Admittedly the screen layout leaves something to be desired; when I have worked out what Weighted Row Height is all about I will try and improve it.

image

Before I finish, I must mention the LightSwitch Publish Wizard, which is clearly the result of a lot of work on Microsoft’s part. First, you choose between a desktop or web application. Next you choose an option for where the services are hosted, which can be local, or on an IIS server, or on Windows Azure.

image

Something I like very much: when you deploy, there is an option to create a new database, but to export the data you have already entered while creating the app. Thoughtful.

image

As you can see from the screens, LightSwitch handles security and access control as well as data management.

What do I think of LightSwitch after this brief exercise? Well, I am impressed by the way it abstracts difficult things. Considered as an easy to use tool for model-driven development, it is excellent.

At the same time, I found it frustrating and sometimes obscure. The local property concept is a critical one if you want to build an application that goes beyond what is generated automatically, but the documentation does not make this clear. I also have not yet found a guide or reference to writing code, which would tell me whether my use of FindControl was sensible or not.

The generated applications are functional rather than beautiful, and the screen layout designer is far from intuitive.

How is the target non-developer developer going to get on with this? I think they will retreat back to the safety of Access or FileMaker in no time. The product this reminds me of more is FoxPro, which was mainly used by professionals.

Making sense of LightSwitch

So what is LightSwitch all about? I think this is a bold effort to create a Visual Basic for Azure, an easy to use tool that would bring multi-tier, cloud-hosted development to a wide group of developers. It could even fit in with the yet-to-be-unveiled app store and Appx application model for Windows 8. But it is the Visual Basic or FoxPro type of developer which Microsoft should be targeting, not professionals in other domains who need to knock together a database app in their spare time.

There are lots of good things here, such as the visual database designer, the Publish Application wizard, and the whole model-driven approach. I suspect though that confused marketing, the Silverlight dependency, and the initial strangeness of the whole package, will combine to make it a hard sell for Microsoft. I would like to be wrong though, as a LightSwitch version 2 which generates HTML 5 instead of Silverlight could be really interesting.

Why Windows Installer pops up when you run an application

Warning: this post is about old Windows hassles; I’ve written it partly because some of us still need to run old versions of Windows and apps, and partly because it reminds me that Windows has in fact improved so that this sort of thing is less common, though there is still immense complexity under its surface which can leak out to cause you grief – especially for people like reviewers and developers who install lots of stuff.

I’ve been retreating to Windows XP recently, in order to tweak an old Visual Basic 6 application. VB6 can be persuaded to run on later versions of Windows, but it is not really happy there. I have an old XP installation that I migrated from a physical machine to a VM on Hyper-V.

I was annoyed to find that when I fired up VB 6, the Windows Installer would pop up – not for VB 6, but for Visual Studio 2005, which was also installed.

image

Worse still, after thrashing away for a bit it decided that it needed the original DVD:

image

I actually found the DVD and stuck it in. The installer ground away for ages with its deceptive progress bars – “20 seconds remaining” sitting there for 10 minutes – repeated what looked like a loop several times, then finally let me in to VB. All was well for the rest of that session; but after restarting the machine, if I started VB 6 the very same thing would happen again.

This annoyance is not confined to VB 6; it used to happen a lot in XP days, though in my experience it is much less common with Vista and Windows 7.

I investigated further. This article explains what happens:

What you see is the auto-repair feature of Windows Installer. When an application is launched, Windows Installer performs a health check in order to restore files or registry entries that may have been deleted. Such a health check is not only triggered by clicking a shortcut but also by other events, such as activation of a COM server. The events triggering a health check depend on the operating system.

When you see this auto-repair problem this means that Windows Installer came to the conclusion that some application is broken and needs to be repaired.

A good concept, but in practice one that often fails and causes frustration. The worst part of it is the lack of information. Look at the dialog above, which refers to “the feature you are trying to use”. But which feature? In my case, how can my VB 6 depend on a feature of Visual Studio 2005, which came later and does not include VB 6? In any case, it is a lie, since VB 6 works fine even after the installer fails to fix its missing feature.

Fortunately, the article explains how to troubleshoot. You go to the event viewer, application tab, and MsiInstaller entries will tell you which product and component raised the repair attempt. Unfortunately the component is identified by a GUID. What is it?

To find out, you can try Google, or you can use a utility that queries the Windows Installer database. The best I’ve found is a tool called msiinv; the script mentioned in the post above did not work. You can find msiinv described by Aaron Stebner here, with a download link. Note how Stebner had to change the download locations because they kept breaking; a constant frustration with troubleshooting Windows, as Microsoft regularly moves or removes articles and downloads even when they are still useful.

Running msiinv with its verbose option (which you will need) seems to pretty much dump the entire msi installer database to a text file. You can then search for these GUIDs and find out what they are. You may find even products listed that are not in Control Panel’s Add/Remove programs. You can remove these from the command line like this:

msiexec /x {GUID}

where GUID identifies the product to remove.

In my case I found beta versions of WinFX (which became .NET 3.0). I said this was old stuff! I removed them, restarted Windows, and VB6 started cleanly.

That still does not explain how they got hooked to VB6; the answer is probably somewhere in the msiinv output, but having fixed the issue I’m not inclined to spend more time on it.