June 2011 - Posts - Jon Galloway

June 2011 - Posts

My ASP.NET news sources

I just posted about the ASP.NET Daily Community Spotlight. I was going to list a bunch of my news sources at the end, but figured this deserves a separate post. I've been following a lot of development blogs for a long time - for a while I subscribed to over 1500 feeds and read them all. That doesn't scale very well, though, and it's really time consuming. Since the community spotlight requires an interesting ASP.NET post every day of the year, I've come up with a few sources of ASP.NET news.

Top Link Blogs

Chris Alcock's The Morning Brew is a must-read blog which highlights each day's best blog posts across the .NET community. He covers the entire Microsoft development, but generally any of the top ASP.NET posts I see either have already been listed on The Morning Brew or will be there soon.

Elijah Manor posts a lot of great content, which is available in his Twitter feed at @elijahmanor, on his Delicious feed, and on a dedicated website - Web Dev Tweets.

While not 100% ASP.NET focused, I've been appreciating Joe Stagner's Weekly Links series, partly since he includes a lot of links that don't show up on my other lists.

Twitter

Over the past few years, I've been getting more and more of my information from my Twitter network (as opposed to RSS or other means). Twitter is as good as your network, so if getting good information off Twitter sounds crazy, you're probably not following the right people. I already mentioned Elijah Manor (@elijahmanor). I follow over a thousand people on Twitter, so I'm not going to try to pick and choose a list, but one good way to get started building out a Twitter network is to follow active Twitter users on the ASP.NET team at Microsoft:

  • @scottgu (well, not on the ASP.NET team, but their great grand boss, and always a great source of ASP.NET info)
  • @shanselman
  • @haacked
  • @bradwilson
  • @davidfowl
  • @InfinitiesLoop
  • @davidebbo
  • @marcind
  • @DamianEdwards
  • @stevensanderson
  • @bleroy
  • @humancompiler
  • @osbornm
  • @anurse
  • @coolcsh

I'm sure I'm missing a few, and I'll update the list.

Building a Twitter network that follows topics you're interested in allows you to use other tools like Cadmus to automatically summarize top content by leveraging the collective input of many users.

Twitter Search with Topsy

You can search Twitter for hashtags (like #aspnet, #aspnetmvc, and #webmatrix) to get a raw view of what people are talking about on Twitter. Twitter's search is pretty poor; I prefer Topsy. Here's an example search for the #aspnetmvc hashtag:

http://topsy.com/s?q=%23aspnetmvc

You can also do combined queries for several tags:

http://topsy.com/s?q=%23aspnetmvc+OR+%23aspnet+OR+%23webmatrix

2011-06-22 15h42_04

Paper.li

Paper.li is a handy service that builds a custom daily newspaper based on your social network. They've turned a lot of people off by automatically tweeting "The SuperDevFoo Daily is out!!!" messages (which can be turned off), but if you're ignoring them because of those message, you're missing out on a handy, free service.

My paper.li page includes content across a lot of interests, including ASP.NET: http://paper.li/jongalloway

When I want to drill into a specific tag, though, I'll just look at the Paper.li post for that hashtag. For example, here's the #aspnetmvc paper.li page: http://paper.li/tag/aspnetmvc

Delicious

I mentioned previously that I use Delicious for managing site links. I also use their network and search features. The tag based search is pretty good:

2011-06-22 15h58_14

Even better, though, is that I can see who's bookmarked these links, and add them to my Delicious network. After having built out a network, I can optimize by doing less searching and more leaching leveraging of collective intelligence.

Community Sites

I scan DotNetKicks, the weblogs.asp.net combined feed, and the ASP.NET Community page, CodeBetter, Los TechiesCodeProject,  and DotNetSlackers from time to time. They're hit and miss, but they do offer more of an opportunity for finding original content which others may have missed.

Terms of Enrampagement

When someone's on a tear, I just manually check their sites more often. I could use RSS for that, but it changes pretty often. I just keep a mental note of people who are cranking out a lot of good content and check their sites more often.

What works for you?

The ASP.NET Daily Community Spotlight - How posts get there, and how to make it your Visual Studio Start Page

One really cool part of my job is selecting the articles for the Daily Community Spotlight, on the home page of the ASP.NET website. The spotlight highlights a new post about ASP.NET development every day from a member of the ASP.NET community. You can find it on the home page of the ASP.NET site, at http://asp.net

2011-06-22 10h26_26

These posts aren't automatically drawn from a pool of RSS feeds or anything - I pick a new post for each day of the year.

How I pick the posts

I have a few important selection criteria:

Interesting to well rounded ASP.NET developers

The ASP.NET website has a lot of material for all skill and experience levels, from download / get started to advanced. I try to select community spotlight posts to round that out with fresh and timely information that working ASP.NET developers can really use. Posts highlight solutions to common problems, clever projects and code that helps you leverage ASP.NET, and important announcements about things you can use today.

As part of that, I try to mix between ASP.NET MVC, Web Forms, and Web Pages (a.k.a. WebMatrix). As a professional developer, I want to keep on top of all of my options for ASP.NET development, and the common platform base they all share generally means that good ASP.NET code is good ASP.NET code.

Exposing new and non-Microsoft community members as much as possible

The exercise of selecting good ASP.NET community posts every day of the year has made me think about what the community is. Given the choice, I'll always favor non-Microsoft employees, but since Microsoft often hires ASP.NET community members and MVP's (myself included), I really think that the ASP.NET community includes developers who are using and writing about ASP.NET, both inside and outside of Microsoft.

I'm especially excited about the opportunity to highlight new and lesser known bloggers. Usually being featured on the ASP.NET Community Spotlight gives a pretty good traffic bump, and I love being able to both provide great content to the community and encourage lesser known community members by giving them some (much deserved) attention.

Announcements only when they're useful to working developers - not marketing

Some of the posts are announcements about new releases, such as Scott Hanselman's post on ASP.NET Universal Providers for Session, Memebership, and Roles. I include those when I think they're interesting and of immediate use to you on projects. I occasionally get asked to link to new content from a team at Microsoft; if it's useful and timely content I'll ask them to point me to a blog post by an actual person rather than a faceless team.

How the posts are managed

This feed used to be managed by an internal spreadsheet on a Sharepoint site, which was painful for a lot of reasons. I took a cue from Jon Udell, who uses of a public Delicious feed feed for his Elm City project, and we moved the management of these posts over to a Delicious feed as well. You can hear more about Jon's use of Delicious in Elm City in our Herding Code interview - still one of my favorite interviews. We ended up with a simpler scenario, but

Note: I watched the Yahoo/Delicious news over the past year and was happy to see that Delicious was recently acquired by the founders of YouTube. I investigated several other Delicious competitors, but am happy with Delicious for now.

My Delicious feed here: http://www.delicious.com/jon_galloway

You can also browse through this past year's ASP.NET Community Spotlight posts using the (pretty cool) Delicious Browse Bar

2011-06-22 12h53_30

Submitting articles

I'm always on the lookout for new articles to feature. The best way to get them to me is to share them via Delicious. It's pretty easy - sign up for an account, then you can add a post and share it to me.

Alternatively, you can send them to me via Twitter (@jongalloway) or e-mail (). If you do e-mail me, it helps to include a short description and your full name so I can credit you.

Way too many developer blogs don't include names and pictures; if I can't find them I can't feature the post.

Subscribing to the Community Spotlight feed

The Community Spotlight is available as an RSS feed, so you might want to subscribe to it: http://www.asp.net/rss/spotlight

Setting the ASP.NET Community Spotlight feed as your Visual Studio start page

If you're an ASP.NET developer, you might consider setting the ASP.NET Community Spotlight as the content for your Visual Studio Start Page. It's really easy - here's how to do it in Visual Studio 2010:

  1. Display the Visual Studio Start Page if it's not already showing (View / Start Page)
  2. Click on the Latest News tab and enter the following RSS URL: http://www.asp.net/rss/spotlight
  3. If you didn't previously have RSS feeds enabled for your start page, click the Enable RSS Feed button

2011-06-22 13h40_00

Now, every time you start up Visual Studio you'll see great content from members of the ASP.NET community:

2011-06-22 13h42_48

You can also configure - and disable, if you'd like - the Visual Studio start page in the Tools / Options / Environment / Startup dialog.

Credits

I'll do a follow-up highlighting some places I commonly find great content for the feed, but I'd like to specifically point out two of them:

Elijah Manor posts a lot of great content, which is available in his Twitter feed at @elijahmanor, on his Delicious feed, and on a dedicated website - Web Dev Tweets

Chris Alcock's The Morning Brew is a must-read blog which highlights each day's best blog posts across the .NET community. He's an absolute machine, and no matter how obscure the post I find, I can guarantee he'll find it as well if he hasn't already. Did I say must read?

Submitting a drive-by commit to a GitHub project in under 5 minutes

I recently mentioned how I contributed C# syntax for CodeMirror; what I didn't talk about was how incredibly easy it was. I think the biggest obstacles to open source contribution are:

  • I'm not sure what I need to do, especially for this particular project / open source host
  • I don't have time to figure this out right now

What you might not know is that you can contribute useful code to a project in just a few minutes, even without having git installed or any git know-how - you could submit a patch from your mobile-device-of-choice if you really wanted to.

Note for the haters: The normal workflow to contributing to a project is via the standard git tooling, and I've done that. I was happily surprised to see that the github site supports project contribution without requiring that full workflow, which is nice for simple cases. The method I'm showing here is only appropriate for very simple changes.

1. Downloading the current source

If you're looking to contribute, you'll generally want the most current source. The simplest way to do that is to hit the download button, then grab the zip.

2011-06-17 15h00_35

2. Make and thoroughly test your changes

In my case, I made a change, verified I didn't break anything, and gave it the Works On My Machine official certification. At this point, I decided I wanted to contribute my change. Make sure to follow the standard practices here:

  • Make an isolated, useful change
  • Don't needlessly refactor existing code
  • Adapt to the coding style and architecture that are already in place

3. Fork the project on GitHub

If you're new to distributed version control systems (git, mercurial, etc.) the term "fork" may kind of throw you off. In the open source world, forking a project previously used to indicate that you were in some way unhappy with the original project and were starting up a new project. In DVCS, forking is good, natural, healthy, and beautiful. Try it: go fork a random project, check out your fork, and delete it. No harm done.

Forking a project on GitHub is literally a one-click thing:

2011-06-15 22h25_31

Word up. Now you have your own fork and can start making changes.

2011-06-17 12h17_00

4. Update your repo

Here's the trick I came across: if you're making a simple change, you don't need to do the git clone / push remote business. If you're planning to continue working on your fork long-term, of course, you'd want to do that, but if you're doing a drive-by contribution there's no need for any of that. You can browse to the file on your repo and edit it-place.

2011-06-17 15h45_40

So, click the edit button, copy your local edits in, enter a commit message, and commit your changes.

2011-06-17 15h52_14

5. Submit a pull request

Make sure you're happy with your changes, then submit a pull request. That's as easy as clicking the Pull Request link near the top of the page.

2011-06-17 15h55_19

Recap

If you already had a code change that you were happy with, you could easily follow the above steps in under 5 minutes. Don't torment project owners with low quality pull requests, but as someone who's admin'd several open source projects, I'm always thrilled to get a thoughtful submission. I'm generally more of a CodePlex / BitBucket fan, but you gotta hand it to GitHub - they've made the drive-by commit drop dead simple.

Posted by Jon Galloway | with no comments

Herding Code podcast update: 3 years, 115 episodes and 25TB of traffic later...

Back in May 2008, K. Scott Allen accidentally called my on Skype, and we joked that we should start a podcast. And then we did - we roped in Kevin Dente and Scott Koon since the four of us tended to argue quite a bit on Twitter anyways - and kind of figured it out as we went along. Along the way, we've recorded 115 episodes (pretty much an entire week of audio), discussed the comings and goings of myriad technologies, and had the opportunity to talk to some incredible guests.

If you're not currently listening or subscribing, you can find shows and show notes here, and subscribe here.

Bandwidth

Initially, I tried to host the audio on SkyDrive, quickly found out that SkyDrive files didn't send correct media headers so it wouldn't work with FeedBurner. At Scott Koon's recommendation, I set up a simple WordPress blog at Site5 which has turned out to be a great decision. They've had great uptime and phenomenal prices. We pay about $7/month for an unlimited storage and bandwidth, and they've delivered that with great uptime as well. Here's a look at the download bandwidth per-year:

Year Bandwidth (GB)
2008 1830.36
2009 6134.74
2010 10705.6
2011 (to date) 6678.78
Total 25349.48

Popular shows

Here's a look at our top 25 shows of all time - the listener count is actually a bit higher since we also distribute via BitTorrent, but the order is pretty accurate. Remember that some of these shows have had 3 years to build up a count, so it's pretty cool to see two of the last 15 (102 and 106) already showing on this list:

Rank Show Title Downloads
1 HerdingCode 0063 Victory in Software Development 29762
2 HerdingCode 0010 LINQ 15410
3 HerdingCode 0011 Glenn Block Part 1 13521
4 HerdingCode 0005 Firefox 3 Released 13084
5 HerdingCode 0049 Search with Bing and Wolfram Alfa 12976
6 HerdingCode 0012 Glenn Block Part 2 12307
7 HerdingCode 0064 Phil Haack on MVC 2 12078
8 HerdingCode 0035 Fun at work 11476
9 HerdingCode 0051 Greg Young on Our Grand Failure 10510
10 HerdingCode 0046 Mistakes and News Recap 10481
11 HerdingCode 0037 Jon Udell 10014
12 HerdingCode 0047 Joe Brinkman on Webforms vs MVC 9869
13 HerdingCode 0048 Dustin Campbell on Visual Studio 2010 9751
14 HerdingCode 0102 Tim Caswell on Node js 9664
15 HerdingCode 0027 What every web developer sh... 9659
16 HerdingCode 0009 Rob Conery on SubSonic, MVC Storefont, and the Silverlight Ninja Squad 9402
17 HerdingCode 0058 Presentation Patterns with Jeremy Miller, Ward Bell, Rob Eisenberg and Glenn Block 9389
18 HerdingCode 0050 Damien Guard on LINQ to SQL, Entity Framework, and Fontography 9316
19 HerdingCode 0013 Back To Basics (but which ones?) 9266
20 HerdingCode 0038 NHibernate Performance with David Penton, and Ben Scheirman 9255
21 HerdingCode 0087 Jeff Atwood on Area 51 and Stack Overflow 9213
22 HerdingCode 0032 Windows 7 First Impressions 9118
23 HerdingCode 0059 Web Standards with Milan Negovan 9001
24 HerdingCode 0106 Mark Rendle on Simple Data 8980
25 HerdingCode 0015 Chris Tavares 8975

Our top show of all time is Victory in Software Development, talking about an interesting post K Scott had written. I think it was a really interesting discussion, but it's not clear how that show got so many listens. Stats don't really show anything obvious. Strange.

The full archive is here. For nostalgia's sake, you might want to check out our Hello World first show.

Show Topics and Guests

The one rule we've tried to stick to is avoiding the standard .NET podcast circuit. There are some great, well produced, very popular podcasts out there that cover the standard fare pretty well, and we thought it was important to try to surface topics and guests who are a bit below the radar, especially for the majority of our listenership with a  mostly Microsoft development background. I listen to a lot of podcasts, and we try not to duplicate what any of the others are covering.

A lot of our show topic and guest ideas have come from guest recommendations, so I recently set up the Herding Code Guest Suggestion form to make it easier to submit ideas. Got any?

Show Notes

The show notes and links take a lot of time. We've had a good amount of volunteer help on these from Ben Griswold over the years, as he has time available. He really stepped up the quality there - pretty much any topic mentioned during a show is listed in the show notes with links provided. Thanks!

Podcast Announcement Posts

Before we set up a site for the podcast, I used to post the episodes here. When I set up the separate site, I thought it was important to keep this blog and the podcast separate. In retrospect, that doesn't make any sense. I'm going to try to at least announce each show here, but also put in some sample code and additional info that I found interesting while editing and compiling notes.

Posted by Jon Galloway | with no comments
Filed under:

Using CodeMirror to add C# syntax highlighting to an editable HTML Textarea

I wanted to display some C# code in an html <textarea> control that was displayed in an ASP MVC 3 application using @Html.TextArea():

@using (Html.BeginForm())
{
    @Html.TextArea("sampleCode", (string)ViewBag.sampleCode, new { rows = "20", cols = "120" })
    <input type="submit" />
}

Note that I'm talking about an editable textarea, not just a code display - for code display, you can use something like SyntaxHighlighter or Prettify pretty easily.

While a big textarea is workable, I wanted to improve the experience a bit. There are several WYSIWYG textbox controls for general formatted text out there, but it was a little harder to find one that that fit well with code. I played around with SyntaxHighlighter a bit, since I use it for displaying code in my blog, but it didn't work smoothly with a textarea. A StackOverflow post pointed me to a great solution: CodeMirror. It didn't (yet) have c# syntax support, but I added that in pretty easily - I'll talk about that in a bit.

Demo

Here's an idea of how it works. This is an editable textbox with C# code syntax highlighting, which dynamically updates as you type.

Adding CodeMirror to a textbox

Adding CodeMirror is really easy:

  1. Grab the CodeMirror package
  2. Add the necessary CSS and JavaScript references in your page
  3. Call CodeMirror.fromTextArea() on your textarea element

Getting the CodeMirror package

Normally you'd grab that from http://codemirror.net, but my c# syntax changes were just merged in and aren't in the download package yet, so you can just grab the latest zip from github: https://github.com/marijnh/CodeMirror2/zipball/master.

Add the necessary CSS and JavaScript references in your page

The CSS and JavaScript dependencies vary based on you'll need, depending on which features you're using. Fortunately, the CodeMirror package includes a lot of great samples (also available on the website) which show clearly what you'll need to reference: just view-source. Assuming your CodeMirror scripts were in /Scripts/CodeMirror/, this would reference the basic scripts for C# highlighting:

<script src="/Scripts/CodeMirror/lib/codemirror.js"></script>
<script src="/Scripts/CodeMirror/mode/clike/clike.js" type="text/javascript"></script>
<link href="/Scripts/CodeMirror/lib/codemirror.css" rel="stylesheet" type="text/css" />
<link href="/Scripts/CodeMirror/theme/default.css" rel="stylesheet" type="text/css" />

Here's what those four references do:

  1. The first script reference brings in the main CodeMirror library
  2. The second script refernce uses one of the common supported modes - in this case I'm using the c-like syntax mode
  3. The next is the main codemirror CSS reference
  4. The last reference is for the default CodeMirror theme - there are 4 included color themes, and you can add your own with your own custom CSS file

Call CodeMirror.fromTextArea() on your textarea element

The CodeMirror call has a lot of sensible defaults, so this is pretty easy. The only real thing to point out is that the CodeMirror.fromTextArea() takes a textarea element, so you can either call document.getElementById or use jQuery and access the first array element, e.g. $('code')[0]. For a simple case, the code looks like this:

<script> 
  var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
    lineNumbers: true,
    matchBrackets: true,
    mode: "text/x-csharp"
  });
</script> 

Styling the CodeMirror box

CodeMirror creates a new element with the class "CodeMirror" so you need to apply your CSS styles to the CodeMirror class, not the ID or class of your original element.

Putting it all together

Here's the source for the above textbox

<script src="/Scripts/CodeMirror/lib/codemirror.js"></script>
<script src="/Scripts/CodeMirror/mode/clike/clike.js" type="text/javascript"></script>
<link href="/Scripts/CodeMirror/lib/codemirror.css" rel="stylesheet" type="text/css" />
<link href="/Scripts/CodeMirror/theme/default.css" rel="stylesheet" type="text/css" />

<style>
    .CodeMirror {
        border:1px solid #334;
        width:800px;
    }
</style>

<textarea id="code" name="code">using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcMusicStore.Models;

namespace MvcMusicStore.Controllers
{
    [Authorize(Roles = "Administrator")]
    public class StoreManagerController : Controller
    {
        private MusicStoreEntities db = new MusicStoreEntities();

        //
        // GET: /StoreManager/

        public ViewResult Index()
        {
            var albums = db.Albums.Include(a => a.Genre).Include(a => a.Artist);
            return View(albums.ToList());
        }

        //
        // GET: /StoreManager/Details/5

        public ViewResult Details(int id)
        {
            Album album = db.Albums.Find(id);
            return View(album);
        }

        // etc. etc.
    }
}
</textarea> 
 
<script> 
  var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
    lineNumbers: true,
    matchBrackets: true,
    mode: "text/x-csharp"
  });
</script> 
 

Adding new syntax

I mentioned earlier that when I first found CodeMirror, I noticed that it didn't have C# support. Fortunately, I noticed that it did have a C-Like syntax mode, and adding C# syntax support was really easy.

  1. I looked up the C# 4 keywords on MSDN here.
  2. I did some find-replace-fu to turn it into a space delimited list.
  3. I added a few lines to the end of clike.js, following the format of the previous C++ and Java samples.
CodeMirror.defineMIME("text/x-java", {
  name: "clike",
  atAnnotations: true,
  keywords: keywords("abstract assert boolean break byte case catch char class const continue default " + 
                     "do double else enum extends false final finally float for goto if implements import " +
                     "instanceof int interface long native new null package private protected public " +
                     "return short static strictfp super switch synchronized this throw throws transient " +
                     "true try void volatile while")
});
CodeMirror.defineMIME("text/x-csharp", {
  name: "clike",
  atAnnotations: true,
  atStrings: true,
  keywords: keywords("abstract as base bool break byte case catch char checked class const continue decimal" + 
                     " default delegate do double else enum event explicit extern false finally fixed float for" + 
                     " foreach goto if implicit in int interface internal is lock long namespace new null object" + 
                     " operator out override params private protected public readonly ref return sbyte sealed short" + 
                     " sizeof stackalloc static string struct switch this throw true try typeof uint ulong unchecked" + 
                     " unsafe ushort using virtual void volatile while add alias ascending descending dynamic from get" + 
                     " global group into join let orderby partial remove select set value var yield")
});

The key is to find a similar language which is already supported and modify it.

Posted by Jon Galloway | with no comments
Filed under:

Getting Mono compiler output in a web application using StreamReportPrinter

I've been continuing my experiment with Mono's compiler as a service in an ASP.NET MVC application and making pretty good progress. One of the difficulties I ran into along the way was in troubleshooting compiler errors when I'd deployed the application. Almost all of the content and documentation on Mono.CSharp is in a console application / REPL scenario, which doesn't help in tracking down errors in a web application.

To recap from before, most of the samples you'll see for using Mono.CSharp look like this (undoubtedly copied from Miguel's blog):

var report = new Report(new ConsoleReportPrinter());
var evaluator = new Evaluator(new CompilerSettings(), report);
evaluator.Run("DateTime.Now");

The problem is that the ConsoleReportPrinter writes to Console output, which isn't doing me any good.

// Mono.CSharp.ConsoleReportPrinter
public override void Print(AbstractMessage msg)
{
    base.Print(msg);
    if (base.Stacktrace)
    {
        Console.WriteLine(ConsoleReportPrinter.FriendlyStackTrace(new StackTrace(true)));
    }
}

ConsoleReportPrinter's base is StreamReportPrinter, though, and that works just fine with a StringWriter, like this:

var reportWriter = new StringWriter();
try
{
    var report = new Report(new StreamReportPrinter(reportWriter));
    var evaluator = new Evaluator(new CompilerSettings(), report);

    evaluator.Run("using System.ComponentModel.DataAnnotations;");
    evaluator.Run(modelDefinition);

    object model = evaluator.Evaluate("new Monkey();");
    return View(model);
}
catch
{
    string result = reportWriter.ToString();
    return Content(result);
}

Running this gives some useful output, indicating the compilation results:

{interactive}(1,30): error CS0234: The type or namespace name `DataAnnotations' does not exist in the namespace `System.ComponentModel'. Are you missing an assembly reference? {interactive}(1,30): error CS0234: The type or namespace name `DataAnnotations' does not exist in the namespace `System.ComponentModel'. Are you missing an assembly reference? {interactive}(1,6): error CS0246: The type or namespace name `Monkey' could not be found. Are you missing a using directive or an assembly reference?

Now that we've got the results as a string, they can be logged or handled appropriately.

Posted by Jon Galloway | with no comments
Filed under: , ,

C# and VB.NET - Differing namespace conventions

Recently, while reviewing the VB.NET translation of the MVC Music Store tutorial, I noticed that none of the controllers / models / classes in general have namespaces. I was going to blow up on the person who did the translation like a bad FxCop, but I fired up a new MVC 3 / VB.NET app and saw the project template doesn't use namespaces, and that the New Controller wizard doesn't use a namespace, etc. After checking with the ASP.NET team, I decided to post the VB.NET source code without explicit namespaces in each class, because that's how the code would look if you followed the steps in the tutorial.

I'm sure developers who work with both VB.NET and C# regularly know this; I pretty much moved from VB6 to C# and this was news to me, so I thought I'd share it.

When you're creating a new class in a C# application, the class will have a namespace that matches its path in the application. The default project structure for an ASP.NET MVC application has a Controllers directory, so all controller classes in the MvcMusicStore application (for example) are in the MvcMusicStore.Controllers namespace.

using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using MvcMusicStore.Models;

namespace MvcMusicStore.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
    {
        // ...

Note: that's just the default. You can use any namespace you'd like; ASP.NET MVC doesn't use the namespace / directory location in locating your controllers.

Controller classes created using the "Add Controller" tooling in Visual Studio will look like this:

Public Class HomeController
    Inherits Controller

    Public Function Index() As ActionResult
    ' ...

However, if you reflected over the assembly, you'd see that the HomeController class is in the MvcMusicStore namespace, as are all other classes in the assembly. That's because in VB.NET you have a default namespace that's set in the project properties, and that namespace is applied to all the generated assemblies.

2011-06-02 12h04_39

I'd have guessed that I could drop a namespace definition into the class and it would then work like I'm used to with C#, but that's not the case. If I added the same namespace that's in my C# class (using Namespace MvcMusicStore.Controllers) it would be still be prefixed by the project's default namespace, so I'd end up with my HomeController class in MvcMusicStore.MvcMusicStore.Controllers.

In the end, I decided it was best to follow the When In Rome approach and fit with how the standard ASP.NET MVC VB project templates work. Looking back on my first steps from VB into C#, I remember being a little confused and frustrated by the implied requirement to drop namespaces everywhere, and I didn't even really reconsider it until I read Jeff Atwood's A Modest Namespace Proposal post asking why we're all slavishly adding unnecessary namespaces in cases when they add no value.

Note: Many posts that compare or even mention both C# and VB bring out the crazies. Be warned that I will probably edit any "my language is better that your language" comments, replacing bile with lyrics from contemporary popular music.

More Posts