Phil posted on November 28, 2009 20:32

Just a quick recent thought. As I am watching the PDC09 videos made available free online by Microsoft, I got me thinking more about the recent changes/improvements in VB. A new feature for VB 9 in 2008 was XML Literals. You know, writing/pasting plain old XML into your source code.  Like this simple example:

dim myXML =  <custs>
<cust ID="5" Name="Oscar" />
<cust ID="9" Name="Ernie" />
</custs>

My thoughts went like this:

  • hey, cool! you don’t have to wrap it in strings, thank goodness.
  • hmm, why would you be hardcoding XML anyway?
  • that belongs in a resource file somewhere, really.

I basically have written off this feature as demoware, really, until I saw the video of Lucian Wischik’s session “Code Like the Wind with Microsoft Visual Basic 2010”. There was one really intriguing feature in his demo of a VB Silverlight component.

The key task that lured me in was a fairly simple demo dealing with HTML replacement. Great application of the technology! If you’re being careful to write your HTML as XHTML, then this is a great way to use VB’s XML Literals feature. Here’s the simple use case from the demo:

  • clicking an input button
  • replacing the innerHTML of a div

 Lucian-InnerHTML

The great thing I like about this that you don’t necessarily have to mess around with string.Format() or string.Concat() and all those other small speedbumps. i.e.

myDiv.innerHTML = string.Format("<p><i>Hello {0}</i><hr/><b>Hello everyone, welcome to VB XML Literals</b></p>",customerName)

Perhaps take it a step further and externalize those snippets if you like. My first thought on that snippet was: “document.getElement? WHAT? Get some jQuery in there! Doh - it’s code-behind!” Interesting how it’s declared as an Object while being assigned Browser.HtmlPage.Document. Likely it’s a quick/dirty demo artifact.

Useful in the Real World?

There’s always the balance of demoware vs. actual best practices vs. your development standards. I am leery of hardcoding markup in your compiled app. It’ll take an application redeploy to change that markup to something different.

Of course, in the real world, you’d probably be loading something user-specific here, like a customer’s name, shopping cart, etc. where you’d be wanting to string.Format() all those details anyway. Heck, you’d even want to iterate through your invoices, tweets, or whatever collection you’d want to start building a simple <ul> with your collection of business data in <li>.

Even if it was a simple replacement of XML, with some business logic around which snippet to insert, consider if you'd had externalized those snippet into an XML resource file(s), you could refer to them easily, although not as simple as strongly typed XML literals compiled in a resource file. There’s that balance again – ease of coding vs. maintainability in production.

I always like discovering new personalities at Microsoft. I’ll be RSS’ing Lucian’s blog, looking forward to seeing any great content he might share.

Real World Production Examples?

Do you know of any examples in the real world of VB and XML Literals in a production app? If/when I find some, I’ll post a link here!


Posted in: visual basic  Tags:
Actions: E-mail | Permalink | Comments (0) |

cruft_folder_2Usually when jumping into a new OS, I largely disregard the built in programs. My typical thought is that they’re for newbies, grandmas, and otherwise lack the features that other 3rd party programs offer. (think MSPaint, Getting Started, Fax/Scanner Wizard, Welcome to XP videos, etc). It got so annoying that I actually go out of my way on new installs to make a new folder on the Start Menu to bury those shortcuts.

Windows 7 Snipping Tool Special-K  brought the new Windows 7 Snipping Tool to my attention, and it’s most definitely a productivity enhancer. My snap judgement was “really, a built-in Windows tool?”, but after 10 seconds of using this tool, I knew I’d be using it immediately in place of my current screenshotting process.

Screenshotting

Here’s my typical OLD style of creating a screenshot. Typical use case here is to send a cropped & marked-up screenshot by email, or perhaps for insert into Windows Live Writer.

paint_net Total Clicks/Buttons = up to 15

  • Alt-PrtScn
  • Open Paint.NET
  • Ctrl-V
  • Start cropping
  • Change the color selector to red or yellow or something to make your selection stand out
  • Select the Oval or Rectangle tool to highlight what you need. When Oval doesn’t line up the way you want, Ctrl-Z, and try again x3.
  • Either: a) Select All –> Ctrl V into a new email or b) Save As –> enter a filename, save to desktop. Open email client (Gmail or Outlook), and attach to email as attachment.

Stop the Insanity with Win7’s Snipping Tool

 

Windows 7 Snipping Tool Total Clicks = max 5

  • Keyboard Start key
  • Type sn as if you were typing snipping tool. Hit Enter.
  • Start cropping
  • Highlight, markup, erase, recrop to your heart’s content.
  • Click the Email button to generate a new email message with the image embedded. Launches the default mail client. Works well with Outlook and Gmail.
snip_types

Being the artsy type, you’ll probably want to screenshot in different ways. I think the typical use-case would be the rectangle, whereby you click-drag a rectangle to highlight the parts of your screen that you want. Otherwise, you have the ability to screenshot:

  • a window you choose (it outlines the window when you hover over it, Win7 style)
  • free-form, lasso-style!
  • the entire screen

 

Caveats (or not!)

  • doesn’t work well when you’re trying to capture something from your Start menu!
  • not a caveat – it’s super easy to snip/screenshot your entire toolbar. Select Window Snip, and click your toolbar. The tool captures just your toolbar, from Start button to minimize button. Awesome!
  • not a caveat – saves as .png by default. Yes, Paint.NET does this as well.
  • not a caveat – turns out the .exe isn’t named winsnip.exe (which I would have loved), but rather c:\Windows\System32\SnippingTool.exe

snipping_tool_windows_7_markup_msdn


Posted in: windows 7 , shortcuts , microsoft  Tags:
Actions: E-mail | Permalink | Comments (0) |
Phil posted on November 5, 2009 05:07

Perhaps you’ve got a collection of objects that you want ordered/sorted. I recently did. Perhaps you want them displayed in a non-deterministic manner or sorted randomly each time you write to an HTML view or otherwise consume that collection. Indeed, I did. (OK, lame shtick over…)

Randomize()

So imagine we’re working with a List of Customers.

data

Problem being, we don’t really have anything non-deterministic to work with. We could do this in SQL Server:

SELECT *
        ,(sin(Cust.ID * rand())) AS R
FROM Cust
ORDER BY R

This though, puts your presentation logic in your data tier. Maybe you don’t care, maybe it’s not a big price to pay. I wanted to take it up to the presentation tier and do this sorting right before binding or writing these objects to the page.

Taking the lead from Bruno Silva, I immediately realized this was the seed of the algorithm that I was looking for. Here’s my modification of Bruno’s algorithm:

   Random r = new Random(); 
   myCusts.OrderBy(x=>(r.Next())); //bind this, or use in a foreach

The call to r.Next() is obviously the key. Each object as it is evaluated in the OrderBy() will get a new random number associated with it. Celebrate good times!

Turn It Into an Extension Method

I haven’t written much here about how much I love extension methods in the .NET CLR 3.0. I can’t count the number of times that I’ve created a static ‘utility’ method that did something like this:

  • take in an object of some kind.
  • modify it.
  • return it back to the caller.
  • caller reassigns the return back into the object that it calls.

Rather than the above, I’ve created an extension method that I’ll be able to call whenever for any collection that implements IEnumerable. It’s trivial then to write the extension method for IQueryable.

ExtensionMethod I’ve submitted my Randomize() extension method over at ExtensionMethod.net. What a great site, by the way, kudos to those guys for taking user submissions and helping grow the use of this feature in .NET.

 

http://extensionmethod.net/Details.aspx?ID=236

public static IEnumerable<t> Randomize<t>(this IEnumerable<t> target)
   {
       Random r = new Random();
       return target.OrderBy(x=>(r.Next()));
   }


Posted in: development , c# , linq , extension methods  Tags:
Actions: E-mail | Permalink | Comments (0) |
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) |