Phil posted on November 2, 2009 01:10

I recently had the privilege of working on a contract where the main goal of the project was to port/convert the web project and associated assemblies (business and data layers) from one .NET language to another. The other tasks were around fixing a handful of defects, and adding a few bits of functionality. The project was hard-capped at a set quoted number of hours, so there was little room for error.

The solution consisted of three .NET 3.5 projects:

  • ASP.NET web project – this project had roughly 10 pages and a handful of helper classes in the App_Code directory. This project already had VB as its language.
  • Business Layer Assembly – 6 classes brokering access to the data layer. Very much pass-through code with not a lot of business logic in between the web layer and data layer. There were moderate amounts of looping and updating of the business object properties.
  • Data Layer Assembly – the DL included the matching DL classes for each of the 6 classes above. The most challenging (code for the converter here was the Linq-To-Sql code.

Sizing Up the Task

The largest part of the project for me was the conversion task. All told, the conversion/translation involved:

  • 12 .cs files
  • ~55 methods
  • ~500 lines of code

I had previously figured the smartest way to spend my time was not rewriting code by hand. If there’s anything a developer should be good at, it’s evaluating and choosing to use the right tool for the job. That’s a major part of your job as a developer!

Enter the Telerik Batch Converter Tool

A quick Bing search brought me to a few options: online-in-the-browser-cut-and-paste style, or full file upload.

I first noticed that Telerik had a batch converter tool. This allows the user to upload a handful of source code files, and the converter will do its magic on the server. This was right up my alley, as it meant that I didn’t have to laboriously open each code file, copy, paste, and make a new source code file.

Telerik Batch Code Converter Upload

The initial load of the page shows the user 3 input boxes where you can browse to the location of your code file. Obviously for those ASP.NET web projects needing conversion, you don’t need to upload your .aspx files, but rather your code-behind files. This particular project was using code-behind files, rather than inline <script>.

Aside: It’s amazing to me that some developers are using <script> tags to hold their code which belongs in a code behind  Page.aspx.cs or .vb file. Obviously it’s a style or configuration issue, but to me it just feels wrong. I like the separation of .NET code and HTML markup. Perhaps it’s just a side effect of trawling the web for source code, and people are choosing to format their .aspx to include code within, instead of posting separate files.

Back to the task. The process is easy:

  • Browse one-by-one for the files you need converted. Make sure to remember to pickup your Linq-To-Sql’s .designer.vb or .cs class. That’s the file where your SQL Server tables are mapped to POCO [Plain Old CLR Objects ;) ]
  • Upload, Convert and Download a .zip containing the artifacts of the conversion. Included are all the converted files, and a Report.txt file.

Telerik Batch Code Converter Done

Results & Conversion Report

The real answer you’re looking for is right here: the results of the conversion with the Telerik tool, for me, were 100%. Absolutely no problems were had in compiling a new project with these new files added to it. I can’t believe it was so easy. Here’s the report that Telerik included in the .zip (irrelevant or repetitive bits snipped):

Conversion Error Report (Created [datetime])

Every time a possible conversion problem is located, the file name, problem severity , and problem description are recorded. There are three levels of severity:

    Warning    = code will convert and will likely work, but conversion may need manual improvement
    Minor    = code will convert, but it will likely need manual correction to work
    Major    = code will not convert. It must be modified before used with converter

There are also general issues to remember when converting web sites:
    - Events connected with the Handles syntax in VB will not work in C#. Events must be connected in code or in the control markup.

Report Details:
================================================
1: TEST.designer.cs    Minor    Your region may not convert from C# to VB if quotes have not been used to name the region. Make sure       region name is surrounded in quotes before using code.
2: TEST.designer.cs    Minor    Your region may not convert from C# to VB if quotes have not been used to name the region. Make sure       region name is surrounded in quotes before using code.

End Report (11 total matches)

Easy & Accurate Results

I can’t believe it was so easy to convert the code. It really meant that I could spend more time ADDING VALUE to the project by way of adding features and fixing defects than by the drudgery of converting source between languages. The price to pay for the Telerik online batch tool was the included comments at the bottom of each source file. That’s an easy price to pay! Can I say now a BIG THANK YOU to Telerik, NRefactory & SharpDevelop, and Todd Anglin @ Telerik for making this tool free and available for the world at large!

TelerikBatchCodeConverter_Comments

Stitching your Converted Files Back Into a Project & Solution

The tricky work is to then take the output of the converter and create a new project. For each of the assembly projects, I:

  • copied all the reusable non-.NET files from the old solutions - *.xml, *.config, etc.
  • made new .vbproj projects in Visual Studio
  • for the web project, Add Existing Files –> Select all your converted files.

For those converting a web project, just create a new Web Project. For each of your pages, modify your .aspx  to have its Page directive to have the appropriate configurations:

<%@ Page Language="VB" MasterPageFile="~/SomeMaster.master" CodeFile="SomeFile.aspx.vb"

Then do the same Add Existing Files routine for all your converted .aspx.vb or .cs files.

Quick Online .NET VB and C# Converters

In some cases, you’ll find snippets online (yes, the bathroom wall of code) where you actually like the snippet, but rather want it in the language of your choice. I recently searched for and used both these tools when needing to convert a large snippet of VB to C#.

Try DeveloperFusion’s online code conversion tool - http://www.developerfusion.com/tools/convert/vb-to-csharp/

Telerik’s Code Converter is of course, likely to be mostly used for its quick online code converter - http://converter.telerik.com/


Posted in: linq-to-sql , c# , vb , shortcuts , best practices  Tags:
Actions: E-mail | Permalink | Comments (0) |
Phil posted on October 12, 2009 05:43

Damien Guard was nice enough to blog about changes coming to L2S in VS 2010. Rather, the changes are coming in the .NET Framework 4.0.

The whole rumor within the development community/blogs about "Linq To Sql is being unsupported, Entity Framework is the new coolness" was just plain wrong, I believe. Microsoft is too big, and has too many projects on the go. They'll gauge the momentum of both technologies. Have you heard Damien as a guest on Herding Code Episode 50? In this blog post, Damien says that the focus for Microsoft will be on EF, and that's fine. L2S is definitely not dead!

I still believe that if you're needing an ORM, and working with SQL Server, then use Linq To Sql. I've tried EF, and it worked fine. I've ended up with 4 projects using L2S, and haven't found any real need for EF.

Welcome Defect Fixes in coming in .NET 4.0 for Linq-To-Sql

For me, the most interesting changes within Damien's post are:

* Contains() with enums automatically casts to int or string depending on column type

* String.StartsWith(), EndsWith() and Contains() now correctly handles ~ in the search string (regular & compiled queries) - Here's a small defect. I've not needed to search for tildes very much, but I decided to give it a shot just in case! It's true, the behavior is just as described!

tilde-2

tilde 

 

* Now detects multiple active result sets (MARS) better - I am not the heaviest user of L2S, and definitely haven't needed to specify MARS myself. Here's the MultipleActiveResultSets defect as reported on MS Connect. It's a simple issue where the connection string property "MultipleActiveResultSets" is only picked up when CamelCased exactly as shown above. Any deviation will ignore the option!

* DeleteDatabase no longer fails with case-sensitive database servers - Interesting that this functionality even exists. I had to research this method - DataContext.DeleteDatabase(). I can't recall actually seeing it in the Intellisense method list, but indeed it's there! Most blogpost or articles that I read in that 5 minute span were talking about using this method for tear-down during "Unit Testing". I'd call that integration testing, and ill-informed as well. Unit tests should not include databases!

DeleteDatabase

* VarChar(1) now correctly maps to string and not char - This one has bitten me before. The column was called Gender. Of course it was storing M, F, T, or U for unknown. The core of the problem was that some rows were having a blank stored in this field, rather than null. StackOverflow to the rescue! http://stackoverflow.com/questions/1190328/linq-to-sql-exception-string-must-be-exactly-one-character-long. After some thought, I'd agree that storing this value as char(1) would be semantically more correct, more performant, and consume just one byte per tuple.

varchar

len zero 

* Decimal precision and scale are now emitted correctly in the DbType attributes for stored procedures & computed columns - I couldn't reproduce this defect, and perhaps I misunderstood.  I defined a decimal(18,5) attribute on the table, and L2S brought it back without any problems. Then I realized the key to this defect was probably the 'computed' bit. So I went and created a simple decimal return type. I ran the query, and still no defect.

computeddecimalsOK

Then I clued in - the defect was under the Linq To Sql Designer heading. So upon further inspection, here's the defect in the myL2S.designer.cs. The return type is calculated as decimal(0,0). Ouch! :)

  decimalzero

* Foreign key changes will be picked up when bringing tables back into the designer without a restart - This defect has hit me a few times as well. It appears as such:

  • Edit a FK in SQL Server. If you've got an open L2S file, deleting + dragging and dropping those tables back onto the L2S surface DO NOT show your FK changes.
  • Clicking the Refresh button in Server Explorer doesn't help.
  • The only solution is to close your L2S file, and re-open.

* Changing a FK for a table and re-dragging it to the designer surface will show new FK’s - this is very much related to the item above.

* Opening a DBML file no longer causes it to be checked out of source control - this has appeared to me a few times. Simply opening/viewing the L2S file creates a 'check out'. Nothing earth shattering here, and glad to see this is fixed.

* Can edit the return value type of unidentified stored procedure types - This feature is great! It's very helpful when you've got a sproc that shapes data just the exact perfect way that you'd like to show on a custom report. Perhaps you're binding to an asp:GridView or including as part of an MVC FormViewModel. The normal course of action is:

  • Create your sproc to shape your data as you like

    Sproc-To-Custom-Object

  • Drag a sproc onto the Methods section of the L2S designer.
  • Try change its return type to a class you've created solely for the purpose of binding

  • Oops, it's locked!

    locked

    The work around is a bit time-consuming. You have to:

    • open up the myL2S.designer.cs file

    • find your method marked with the attribute containing your sproc name

    • replace the default return type int with ISingleResult<T> - in my simple example here, it's ISingleResult<CustomerReport>

      modify dbml

    The frustrating bit here is that this behavior isn't predictable (to me at least). I CONSTANTLY have to go through this process to properly set the return type of 2 sprocs in one particular project. This defect fix in particular by Microsoft will be welcome!


Posted in: linq-to-sql , c# , microsoft  Tags:
Actions: E-mail | Permalink | Comments (0) |