Another technology blog...

25 illustrated examples of Visual Studio 2010 and .NET 4

Tuesday, October 27, 2009

In my quest for both some engaging blog material and a desire to get up to speed with everything new in the latest generation VS and .NET fast, following is an overview of 25 illustrated examples of Visual Studio 2010 and .NET 4. It’s not seriously in depth, just enough to understand what’s new and where you can go to get the serious details.

Background

Rather than churning out another ubiquitous “Hello World” app, I’ve used an existing ASP.NET 3.5 project which has been my test bed for pretty much every version of .NET released so far. Hopefully this will give a bit more practical context than something hypothetical although it does mean a webform bias to the post. The features below are in no particular order, they just appear as I’ve discovered or read about them.

1. Starting up

image The first obvious difference with VS2010; no more rectangular start up screen! Ok, it’s of zero functional value but it does give the product a pretty swish new look.

Actually, the first big shock was no more Mr Tiny Face during the install. Maybe it was the public ridicule, maybe it was just inconsistent with the new branding but either way, I’m going to miss the little guy!

2. Windows 7 taskbar access to recent solutions

image This neat Windows 7 feature is now surfacing itself through a number of applications and whilst it’s a bit trivial for programs opening small, fast files (such as Notepad), it’s really handy for Visual Studio. I’ve tended to always have it auto load the last solution on open then choose a recent solution after that so you end up loading multiple projects just to get to where you want to be. Pin it to the Windows 7 taskbar, right click and it’s always a one step process.

3. Conversion process

imagePretty much the same deal as in VS08 here with loading an existing solution from an older version prompting a conversion. Any web projects allow you to automatically upgrade them to .NET 4 whilst other projects, such as class libraries, need to be done manually after the solution conversion.

In terms of actual changes to the solution performed by the conversion process, the .suo gets the VS version incremented and the .csproj files update the .NET version and include a reference to the version they were upgraded from. There are a few other minor framework related changes but the biggest move is in the Web.Config which shrunk by more than half after the conversion.

4. A cleaner Web.Config

Scott Guthrie has published some good info about Clean Web.Config Files so I’ll just give you the brief version. In short, a lot of the bulk is moved out to the machine.config and what you’re left with is just enough project specific info to make things run. You also get a reference to control rendering compatibility being set to the previous version of the framework so you don’t get breaking CSS and HTML changes (more on that later).

image

5. Better multi monitor support

I’ve said “better” support because there was multi monitor capability in VS08, it’s just that you were limited to basic operations such as docking some of the windows (properties, solution explorer, etc) in a second monitor. In VS2010, you can take open file windows and move them to another screen or rearrange them in the same window which is really handy if you wan to see both ASPX and codebehind at the same time. It’s a still a little clunky though; windows don’t open where you left them and it’s easy for newly opened files to appear behind undocked windows. There’s also no ability to automatically arrange windows and they won’t snap to each other or to screen edges so there’s a bit of fiddling required to get an optimal setup.

image

6. Code snippets

image This is a small one but it will save a lot of keystrokes over time. There are now a number of built in code snippets for ASP.NET, HTML and MVC. What it means is that intellisense will pick up you’re possibly looking for a RadioButtonList if you begin typing “<rad” (yes, without the “asp:” prefix) and it only takes the tab key to then automatically insert the entire tag including sample children. You can then tab between the highlighted values for quick editing.

7. Optional parameters, default values and named parameters

Rather than creating a series of method overloads to cater for different scenarios requiring different parameters, they can now be specified as optional by designating a default value (so long as they appear at the end of the method signature). To avoid ambiguity between multiple optional parameters, they can be referenced by name within the method call. To top it off, VS2010 surfaces optional parameter names through intellisense which makes discovery dead easy. David Hayden has a more comprehensive overview here.

  image 

8. Dynamic language support

The concept of a dynamic language, one that executes at runtime without knowing how it will behave during design or compile time, is not new to programming (Ruby and Python are just a couple of existing dynamic languages), but it is new to .NET in version 4. One advantage this gives us is the ability to use the DLR (Dynamic Language Runtime) to facilitate communication with systems where strongly typed language features are not available without the bloat of using reflection. This is a pretty simplistic (and possibly slightly inaccurate!) overview though so take a look at Scott Hanselman’s excellent explanation.

image

9. URL routing in ASP.NET

This was introduced back in ASP.NET 3.5 SP1 and is used extensively in ASP.NET MVC but is still worth a mention here as it becomes a native part of the framework. Routing provides a means of making a request to a URL which doesn’t necessarily map directly to a physical file. Instead, it provides us with querystring like features but without the explicit name / value pair formatting. What this leaves us with is the ability to create very clean, human readable, search engine optimised URLs.

Process wise, it’s just a matter of registering the route in the Application_Start event in the Global.aspx.cs. My aim in the following example was to take the path normally expressed as /Leases.aspx?InvestmentPropertyID={InvestmentPropertyID} and instead allow /Leases/{InvestmentPropertyID}. Doing this with GUIDs is not great legibility wise but the concept translates just as well to strings which would result in nicely legible URLs.

image

The above code simply gives the route a friendly name, specifies the URL pattern then states the page we want to send the request to. All we need to do then is to read the parameter from the target ASPX page (note: I’ve used a nullable GUID due to the nature of the app not always having the ID available).

image

Quick note; if you’re trying to make this work with IIS6 or IIS7 running in classic mode, have a read of Using ASP.NET MVC with Different Versions of IIS. If you don’t follow this guidance you’ll end up with a lot of 404s.

10. Intellisense gets more intelligent

imageThis one has been around in ReSharper for ages, but intellisense now filters the available options as you type rather than just displaying all possible matches and defaults to the best match to the characters typed. Where it goes a little further than ReSharper is by not just listing matches that start with the characters but matches which contain them. And if you’re not real keen on a filtered list, CTRL-Space will give you back the full version.

image

Another really neat feature is matching by acronym where a type or member adheres to Pascal case (also currently supported by ReSharper). If you enter a string in uppercase you’ll get a filtered list of all possible matches (i.e. Grid.DS will give you the option of Grid.DataSource). It will be interesting to see how ReSharper 5 responds to these changes given previous versions has replaced the native VS intellisense altogether.

11. Geo-location awareness

There seems to be very little available information on this so far other than this extract from the BCL Team blog:

System.Device.Location (which can be found in System.Device.dll) enables .NET applications running on Windows 7 to determine the current geo-location (e.g. latitude/longitude) of the device.  Windows 7 supports a number of different location sensors, including GPS devices and WWAN radios, and automatically handles transitioning between different sensors — if multiple sensors are available — to provide the most accurate data for the current situation. .NET applications will be able to use this new API to access the following data (if available): latitude, longitude, altitude, horizontal and vertical accuracy, course, speed, and civic address (i.e. country/region, state/province, city, postal code, street, building, floor level).

That’s enough information to get me excited! Coupled with online mapping services, address resolution and SQL08’s spatial data capabilities, we’re getting some pretty cool geo-specific capabilities these days. Here’s a quick glimpse of the members:

image

12. Code navigation

Scott Guthrie has a comprehensive blog post on the new navigation features and he starts off with an interesting statement:

In usability studies we’ve done, we typically find that developers spend more time reading, reviewing and searching existing code than actually writing new code.

imageIt would be hard to argue with this and Microsoft have obviously taken it pretty seriously. A quick CTRL+Comma now gives you a “Navigate to” window which filters by keyword and includes the type of match (event, class, member, etc) and the file and line in which it appears. As with the intellisense improvements mentioned above, you can also enter acronyms which match Pascal case names within your solution. This feature will come to the forefront in many cases which would have otherwise required a normal “Find” and stepping manually though results.

13. Meta tag properties

image A small but worthy addition; meta tag properties are now part of the Page class and can be assigned to directly by reference. Should make search engine optimisation that little bit easier, particularly for data driven pages.

14. Guid.TryParse

To get an idea of how handy this will be, take a look at the number of Google results for “Guid.TryParse” that don’t refer to the .NET 4 implementation and instead refer to either a desire to add this to the framework or take you to people’s own bespoke implementations.

image

15. Call hierarchy

There’s more than just a passing similarity to ReSharper’s “Find usages” in this feature but it extends the concept into some new territory. The call hierarchy feature not only displays usages (or “Calls To” as it’s phrased"), but also calls it makes (“Calls From”). There’s also a drill down feature so you can navigate through the tree of nested calls which is a pretty neat way of quickly understanding precisely how the code is being used.

image

16. Auto-start for ASP.NET applications

How many times is someone left wondering why an an ASP.NET app is running so slowly only to realise it has been rebuilt or the application restarted and there is yet to be a client hit to the app? Certainly happens to me a lot so I’m pretty keen on the new auto-start feature.

The only downside to the feature is there is an IIS 7.5 dependency so unless your web server is pretty current, you’re not going to get any value from it. If you are current, it’s just a simple change to the applicationHost.config file to set the startMode attribute to “AlwaysRunning”. More info, once again, from Scott Guthrie here.

image

17. Usage highlighting

This is another feature previously surfaced through ReSharper using Shift+Alt-F11 (are you sensing a theme here?!) but happens automatically in VS2010. Select a name anywhere within code and all usages are automatically highlighted. Just a little feature but yet another small productivity boost.

image

18. Managing the client side ID of controls

Anyone who has ever written client side code to reference server side generated controls will appreciate how much easier this can make life. Rather than the auto generated IDs like ct100_BodyPlaceHolder_TenantID we can now utilise the ClientIDMode to achieve greater naming control. This can be configured at the page level, in the config file of either the application or the machine or at the control level. Take a look at the Setting Client IDs page in the ASP.NET website.

image

19. String.IsNullOrWhiteSpace

A small one but a good one; whereas previously a check for a null or empty string would return false if white spaces existed (you’d normally trim it beforehand to avoid this), the new IsNullOrWhiteSpace method checks for all three conditions in the one call.

image

20. Broad CSS standardisation improvements

ASP.NET has always tended to render some pretty heavy HTML which has been very table dependent and often not particularly accessibility compliant. The latest generation .NET attempts to tackle that by changing the default rendering of a number of controls. For the sake of not introducing breaking changes, upgraded applications are placed in a control rendering compatibility mode which ensure ASP.NET 3.5 apps continue to render identically (you can see this set in the Web.Config image further up the page). Without this, there are potential breaking changes although in my app, the extent of “breaks” was limited to a generated chart image displaying with a border as table and image controls no longer default to zero border.

A good example of where a more standards orientated approach is applied is in the RadioButtonList control. In addition to the “Table” and “Flow” layouts, we now have “OrderedList” and “UnorderedList” which output <ol> and <ul> tags respectively to surround the list items. Apparently this brings improvements for users with “Assistive Technologies” such as screen readers. More on the CSS improvements back on the ASP.NET website here.

image

21. Changed project templates

The standard “ASP.NET Web Application” project template (see the first image below), is now a far more comprehensive beast generating not just the Default.aspx file but also adding forms based authentication pages, JQuery script files, a default CSS file, a couple of general ASPX pages, a Global.asax and even a master page with a basic layout on it. Personally, this is of mixed use to me; I rarely use forms based authentication but I like the idea of having the master page, CSS and JQuery scripts inserted automatically.

At the other end of the scale, there is a new “Empty ASP.NET Web Application” template (second image below), which is closer in nature to the old web app template but doesn’t even give you a default page.

image image

22. Toolbox search

image Ever have trouble finding that pesky control hidden somewhere in the depths of the toolbox? With the new toolbox search feature it’s only ever a few keystrokes away. So long as the focus is on the toolbox you can begin typing the name and the control will be auto selected. You can see from the screen grab on the right I began typing “grid” and the selection has automatically moved down the GridView control.

23. Box insertion

image We’ve had box selection in Visual Studio for a while; hold down the ALT key while dragging a rectangle with the mouse then cut or copy. VS2010 takes this to the next level with box insertion which provides the ability to add text to the selected box. The example on the right shows where I’ve made a zero column width selection (you can just see the turquoise selection line to the right of the text) then typed the one statement which is simultaneously inserted on each row. You really need to see this in action to appreciate it so take a look at Brittany Behren’s (Program Manager from the Visual Studio Editor Team) Box Selection and Multi-Line Editing video on the Visual Studio Blog.

24. Chart control

As with the ASP.NET Routing, this is another permanent addition first surfaced in .NET 3.5 SP1. Actually it goes back even further than that originating from Dundas and making its way into the Microsoft framework following their acquisition a couple of years back (some interesting comments on that at the bottom of Scott Guthrie’s blog entry about the new control).

In case you haven’t previously used this control, there’s quite a comprehensive suite of charts available and in most cases will save you from going out to the likes of .netCharting or Component Art and spending money on a third party tool. There’s a great sample site available which gives you the codebase for all the chart combinations so it’s very easy to get up and running.

image

25. Response.RedirectPermanent

The traditional approach for redirecting users to a moved page is to provide a Response.Redirect in the old page which issues an HTTP 302 to the browser (temporary redirect) and causes it to make a new request to the alternative location. Response.RedirectPermanent causes an HTTP 301 (moved permanently) which allows search engines to recognise the resource no longer exists at the originally indexed location and to instead directly reference the new location which will save the browser a round trip.

 image

27-10-2009 18-12-25You can see based on the Fiddler capture to the right how the request for OldPage1 with the traditional redirect differs from the request to OldPage2 with the permanent redirect. The only thing I’d like to see to make this really easy to manage is the permanent redirects defined in a configuration file to save applications accumulating a raft of orphaned files that simply point to their newer counterparts.

Summary

From my perspective and based on my own needs, there’s no single “killer feature” (LINQ to SQL was this for me in .NET 3.5) rather a broad collection of enhancements that will touch many aspects of the way I build software. Looking back through my examples above, there’s unintentionally a pretty even split between .NET 4 features and VS2010 features and I think that’s pretty representative across the raft of other improvements I didn’t mention (delve into some of the links I’ve included if you want to read more).

Looking to the future, the new WPF based editor (Scott Hanselman has a good interview with Noah Richards from the Visual Studio Editor team on this), is said to provide greater extensibility for third parties to surface more features within the IDE. I’m eagerly awaiting to see how ReSharper tackles this, particularly given the number of features it previously provided that VS2010 now implements natively. Based on Ilya Ryzhenkov’s recent tweets there seems to be some pretty good things in store so fingers crossed for yet more ReSharper goodness in the near future.

I hope this has been useful for other people, I enjoyed putting it together and it’s provided me with the fastest learning curve yet for a new .NET and Visual Studio release. If it helps other people do the same it’s been a very productive days work indeed!


Share/Save/Bookmark

Creating your own custom Subversion management layer

Friday, October 9, 2009

I’m a big fan of Subversion. As far as source control management products go I find it pretty intuitive and very easy for people to get to grips with regardless of their degree of technical competence. The autonomy it has from the prime time technology stacks gives it broad appeal and the fact that it’s freely available is surely a significant part of why it’s so popular today. If you’re looking for pure source control management, it’s hard to go past SVN.

Following is the process I recently went through to provision a Subversion instance with a custom management layer to surface a few key features through a web UI. I’m not going to go into great detail code wise, rather offer some info on the nuts and bolts required to couple the system together with a few key code snippets as required. Hopefully this will give someone else with a similar need a jumpstart in the future.

The goal

Recently I set out to source a new Subversion instance to support a broad range of people working across multiple, autonomous projects in different locations around the world. What I really wanted to do was find a Subversion distribution which would allow me to break rights down into three tiers:

  1. End users; normal Subversion users who can be granted read and write permissions
  2. Repo managers; named individuals who have the right to create a new repo on demand plus manage permissions in existing repos they have rights to
  3. System administrators; all of the above across all repos

All the roles would need to be able to perform their duties via a web based UI and it had to run in a Windows environment leveraging Active Directory accounts for authorisation purposes. Oh, and cost is important. If I could achieve this model then the administrative burden would be moved back to the people actively creating and managing projects rather than those supporting the environment.

Now before anyone jumps up and starts singing the praises of distributed source control management systems such as Mercurial and Git, these were considered but some key constraints ruled them out. Due to various circumstances, namely product familiarity with a large audience and a desire to make the switch “low friction”, these products were off the cards for the moment.

Currently available options

There are two Subversion paths you can go down:
  1. Run Subversion directly by installing your own instance of SVN and Apache (very good overview of that here)
  2. Run a packaged distribution of Subversion which automates the install and provides a GUI and other easy useful management features you don’t find in the previous option

The first option is out right away as there’s no GUI. The second option is closer but out of all the packages I looked at, nothing can distribute management the way I needed them to. When it comes to creating repos and managing access rights, nothing out there seems to do the job at the moment.

If you want something done properly…

As the saying goes, sometimes you just need to do it yourself. We’re not talking about reinventing the wheel here; Subversion is a perfectly good tool in terms of managing source code, it’s really just the configuration management part I’m talking about. What I was envisaging was a web layer that would facilitate creating the repo and managing the permissions. That’s it. In my mind, the only hurdle I needed to tackle was finding a suitable API for .NET to chat to and it would be a piece of cake.

Choosing a Subversion distribution

This was actually a pretty easy choice as there’s one Subversion distribution which stands head and shoulders above the rest in terms of ease of use, price and functionality; VisualSVN Server. This is a very small footprint product (4Mb installer), gets up and running in a couple of clicks and just works every time. I’ve run it directly on a number of PCs for version control on personal projects and never had the slightest glitch with it.

VisualSVN

The other thing VisualSVN Server gives you is a nice MMC style UI to perform common management tasks such as creating repos and managing permissions. It also facilitates server configuration activities such as the port, authentication method and whether an SSL certificate is used.

A final note on product variants; the Standard edition does pretty much everything anyone would need but there is an Enterprise edition. This adds logging functionality for operational tasks such as a user checking out code and allows for remote administration. Nice features, but not worth US$500 based on my particular requirements so I didn’t bother purchasing the license after the trial expired (hence the notice in the screen grab above).

Talking to Subversion

There are a couple of different APIs out there but the most common and most well received seems to be SharpSVN. I also later discovered that the guy behind the project, Bert Huijben, is pretty active on Stack Overflow so there’s a familiar channel available to get support on the product.

SharpSVN is essentially a wrapper for the native SVN commands and as such, it can only perform functions these commands natively expose. This is fine for activities such as creating repositories or reading log messages but the one thing it can’t do that I really needed is to manage permissions. Here’s how Bert explained it:

SharpSvn is mostly a wrapper around the Subversion api and the Subversion
api doesn't implement an api for managing subversion permissions.
and
Different configurations of Subversion have different repository permission
settings.
Right, so the only option was to look at how VisualSVN implements permissions then devise a mechanism to edit these directly.

Creating repositories

The first thing to understand with creating repositories is that the underlying command is svnadmin create, a command which needs to be run on the server. Many of the commands the SharpSVN API exposes can be executed remotely (such as reading log messages) but creating repos is not one of them.

Here’s how the new repo is created:

using (var svnRepoClient = new SvnRepositoryClient())
{
  svnRepoClient.LoadConfiguration(repoPath);
  svnRepoClient.CreateRepository(repoPath);
}

Firstly, the repoPath parameter needs to be physical path of where the repo will be created so in most cases is will be something like c:\Repositories\MyRepo. Next a bit of background on the LoadConfiguration statement:

SvnClient.LoadConfig​urationDefault() (just like svn.exe) assumes the users registry hive is always available (e.g. it can read from HKEY_CURRENT_USER). It uses a few windows api calls on retrieving which directory to use for the settings.

Using .LoadConfiguration(​<path>) skips these procedures as it says: Only load these settings. (+- equivalent to using --config-dir <path> on svn.exe)

In short, it’s a performance thing. As a sidenote, later on I added some functionality to read log messages from a revision range and without loading the configuration first, the process was extremely slow (actually exceeding the default ASP.NET timeout).

Managing repo permissions

As mentioned earlier, the structure of the permissions file is largely dependent on the Subversion distribution. VisualSVN Server takes the approach of using a file named authz-windows in the root of the repositories folder for any Active Directory based authorisations. This file then describes, for both the server as a whole and each repo, who has access and whether it’s read only or read and write. Here’s what it ends up looking like:

[/]
S-1-5-21-8439203732-8503583263-2345657657-123442=rw

[MyRepo:/]
S-1-5-21-2345435435-2346665755-2343245653-99804=rw

This file is granting one account rights over the entire repository and another account rights to just “MyRepo”. You’ll notice each account is referenced as a Windows SID rather than a username but you can resolve one to the other pretty easily if required:

var account = new NTAccount(username);
var sid = (SecurityIdentifier)account.Translate(typeof(SecurityIdentifier));

Creating a data layer

Something that became clear pretty early on was that there was information I wanted to capture which wasn’t natively stored anywhere within VisualSVN. For example, I wanted to collect a little bit more information about the project that was going into the repo as well as some meta data about who created it and when. I also had plans to introduce more functionality later on that would require fast access to both a list of repos and permissions and I wasn’t real keen on the idea of trying to derive these from the file system. The final straw was that managing the permissions file was going to be a bit nasty if the only source of permissions data was SIDs in a text file and this also didn’t provide a mechanism for modelling admin rights or repo creator rights.

So the data layer is actually pretty simple. All it really needs is a Repo table, a Role table and a mapping table including the identity of the user who has been granted permissions. Obviously this can be expanded a little to capture more info but there are really only two entities in the system plus the mapping table.

Securing the application layer

Now that we already have a data model to reflect the permissions we want to apply it’s pretty simple to drop a security-conscious web app on top. I just created a simple role provider implementing the GetRolesForUser method then leveraged security trimming to protect the interfaces to authorised users.

Putting it all together

Firstly the repo management page; all that’s required here is to provide a UI which allows authorised users to create new repos. Just a single textbox will suffice although in my case I ended up asking for a little more information. The role provider secures the page and the SharpSVN API creates the repo followed by a quick LINQ to SQL call to create an entry in the data layer.

Secondly the permissions management page; I redirected straight into this after creating a repo as normally the first thing you want to do is to provide access to other people. This page only needs to provide a means of selecting an identity (I had an existing source of identity data) then choosing whether to give the user admin, reader or writer permissions. After each change I’m just rewriting the Subversion authorisation file in its entirety. The only thing you need to be cautious of here is that if you then use the VisualSVN Server UI to change permissions they’ll be overwritten the next time the permissions file is regenerated from the data layer.

Making it live

Something that only struck me once I got out of development mode and onto a live server was that I was trying to expose both Apache and IIS on the one machine and that I wasn’t going to be able to run them both over port 80. My original intention had been to bind one domain name to Subversion and another to the management interface. There are a number of ways around this including writing ISAPI filters for IIS, using a reverse proxy or most elegantly, running multiple IP addresses (one for each domain) on separate NICs and binding them to the appropriate server.

All the above options were either getting clunky or would require more investment in time and probably dollars so I took the easy route and broke out the duct tape. I left port 80 bound to VisualSVN then edited the default file Apache serves up for any requests to the root (located at C:\Program Files\VisualSVN Server\htdocs\index.html) and added a JavaScript redirect to the same URL but on port 81 which I then bound to the IIS site with the management interface. To be honest, I felt a little dirty after doing it and may still pursue the multiple IP addresses option but this got things up and running quickly with the only real downside being a port appearing after navigating to the site.

Conclusion

All said and done this was a pretty simple little piece of work which got me back into some code for a while and threw a few curve balls. The underlying Subversion structure hasn’t been touched so VisualSVN upgrades shouldn’t be a problem in the future and I can still pick any repo and ship it somewhere else.

Most importantly though, the users are happy as they’re now empowered to manage their own repos without compromising on the security of others. The only problem I have now is resisting the temptation to use the platform to add more features!

Things I omitted in this post

For the sake of simplicity I’ve left out information about some of the frills I added along the way. This includes granting permissions to AD groups or to everyone, email notifications when repos are created, account the VisualSVN service runs under and some other features I added to surface repo data to the web. I also haven’t touched on pre-commit hooks; I’m saving this one for a subsequent post as it’s a project in and of itself.


Share/Save/Bookmark

Disclaimer

Opinions expressed here are my own and may not reflect those of my employer, my colleagues, my mates, my wife and so on and so forth. Unless I’m quoting someone, they’re my own opinions and may not necessarily be cohesive nor entertaining but hey, at least they’re original!