124 blog posts categorised .NET

Estimating JSON size

  • πŸ“…
  • πŸ“ 990
  • πŸ•™ 5
  • πŸ“¦ .NET
  • πŸ’¬ 2

I've been working on a system that heavily uses message queuing (RabbitMQ via MassTransit specifically) and occasionally the system needs to deal with large object graphs that need to be processed different - either broken into smaller pieces of work or serialized to an external source and a pointer put into the message instead.

The first idea was to serialize all messages to a MemoryStream but unfortunately this has some limitations, specifically:

Migrating from OpenTracing.NET to OpenTelemetry.NET

  • πŸ“…
  • πŸ“ 1,338
  • πŸ•™ 6
  • πŸ“¦ .NET

OpenTracing is an interesting project that allows for the collection of various trace sources to be correlated together to provide a timeline of activity that can span services for reporting in a central system. They were competing with OpenCenus but have now merged to form OpenTelemetry.

I was recently brought in as a consultant to help migrate an existing system that used OpenTracing in .NET that recorded trace data into Jaeger so that they might migrate to the latest OpenTelemetry libraries. I thought it would be useful to document what I learnt as the migration process is not particularly clear.

Creating OR expressions in LINQ

  • πŸ“…
  • πŸ“ 618
  • πŸ•™ 3
  • πŸ“¦ .NET

As everybody who has read my blog before knows, I love LINQ and miss it when coding in other languages, so it's nice when I get a chance to use it again. When I come back to it with fresh eyes, I notice some things aren't as easy as they should be - and this time is no exception.

People often need to build up LINQ expressions at runtime based on filters or criteria a user has selected. Adding criteria is incredibly easy, as you can chain operations together on the IQueryable interface, e.g.

Azure Pipeline Build Variables

  • πŸ“…
  • πŸ“ 359
  • πŸ•™ 2
  • πŸ“¦ .NET

Azure Pipelines has been interesting to me especially given the generous free open source tier and seemingly instant availability of build agents. The setup is easy if you're building .NET targets with lots of useful starters available.

Some areas have been frustrating, specifically build variables, the difficulty in getting the app installed, and the limitations on triggers if you can't (non-GitHub apps can't be installed on Enterprise accounts even if FREE).

Model binding form posts to immutable objects

  • πŸ“…
  • πŸ“ 633
  • πŸ•™ 3
  • πŸ“¦ .NET
  • πŸ’¬ 2

I've been working on porting over my blog to a static site generator. I fired up an Azure Function to handle the form-comment to PR process to enable user comments to still be part of the site without using a 3rd party commenting system - more on that in the next post - and found the ASP.NET model binding for form posts distinctly lacking.

It's been great getting back into .NET and brushing up some skills making the code clear, short and reusable. What I wanted was a super-clear action on my controller that tried to collect, validate and sanitize the data then, if all was well, create the pull request or report errors.

Differences between Azure Functions v1 and v2 in C#

  • πŸ“…
  • πŸ“ 618
  • πŸ•™ 3
  • πŸ“¦ .NET
  • πŸ’¬ 2

I've been messing around in the .NET ecosystem again, jumping back in with Azure Functions (similar to AWS Lambda) to get my blog onto 99% static hosting. I immediately ran into the API changes between v1 and v2 (currently in beta).

These changes are because v1 was based around .NET 4.6 using WebAPI 2 while v2 is based on ASP.NET Core which uses MVC 6. There are some guides around conversion, but none in the context of Azure Functions.

Table per hierarchy in Azure Table Storage

  • πŸ“…
  • πŸ“ 590
  • πŸ•™ 3
  • πŸ“¦ .NET

If you’re coming from an ORM background to Azure Table Storage, you might be wondering how to map class hierarchies to tables.

Documentation on the topic is hard to find unless you know the magic class name EntityResolver which you can discover by digging into the Azure Client for .NET source code.

Optimizing Sum, Count, Min, Max and Average with LINQ

LINQ is a great tool for C# programmers letting you use familiar syntax with a variety of back-end systems without having to learn another language or paradigm for many query operations.

Ensuring that the queries still perform well can be a bit of a chore and one set that fails quite badly are the aggregate operations when you want more than one.

Probable C# 6.0 features illustrated

  • πŸ“…
  • πŸ“ 883
  • πŸ•™ 4
  • πŸ“¦ .NET
  • πŸ’¬ 79

C# 6.0 is now available and the final list of features is well explained by Sunny Ahuwanya so go there and try it with his interactive samples page.

Adam Ralph has a list of the probable C# 6.0 features Mads Torgersen from the C# design team covered at new Developers Conference() NDC 2013 in London.

Enums – Better syntax, improved performance and TryParse in NET 3.5

  • πŸ“…
  • πŸ“ 495
  • πŸ•™ 3
  • πŸ“¦ .NET
  • πŸ’¬ 10

Recently I needed to map external data into in-memory objects. In such scenarios the TryParseTryParse methods of Int and String are useful but where is Enum.TryParseEnum.TryParse? TryParseTryParse exists in .NET 4.0 but like a lot of people I’m on .NET 3.5.

A quick look at Enum left me scratching my head.

Include for LINQ to SQL (and maybe other providers)

  • πŸ“…
  • πŸ“ 672
  • πŸ•™ 3
  • πŸ“¦ .NET
  • πŸ’¬ 12

It’s quite common that when you issue a query you’re going to want to join some additional tables.

In LINQ this can be a big issue as associations are properties and it’s easy to end up issuing a query every time you hit one. This is referred to as the SELECT N+1 problem and tools like EF Profiler can help you find them.

Creating RSS feeds in ASP.NET MVC

ASP.NET MVC is the technology that brought me to Microsoft and the west-coast and it’s been fun getting to grips with it these last few weeks.

Last week I needed to expose RSS feeds and checked out some examples online but was very disappointed.

LINQ to SQL tips and tricks #3

  • πŸ“…
  • πŸ“ 925
  • πŸ•™ 5
  • πŸ“¦ .NET
  • πŸ’¬ 3

Another set of useful and lesser-known LINQ to SQL techniques.

LINQ to SQL supports stored procedures for retrieving entities, insert, update and delete operations, as you know. But you can also use them to perform lazy-loading of navigation properties.

SQL Server query plan cache – what is it and why should you care?

SQL Server like all databases goes through a number of steps when it receives a command. Besides parsing and validating the command text and parameters it looks at the database schema, statistics and indexes to come up with a plan to efficiently query or change your data.

You can view the plan SQL Server comes up with for a given query in SQL Management Studio by selecting Include Actual Execution Plan from the Query menu before running your query.

When an object-relational mapper is too much, DataReader too little

  • πŸ“…
  • πŸ“ 248
  • πŸ•™ 2
  • πŸ“¦ .NET
  • πŸ’¬ 16

I fired up Visual Studio this evening to write a proof-of-concept app and found myself wanting strongly typed domain objects from a database but without the overhead of an object-relational mapperΒ  (the application is read-only).

One solution is to write methods by hand, another is to code generate them but it would be nice to be able to do:

LINQ to SQL cheat sheet

A few short words to say I’ve put together a cheat sheet for LINQ to SQL with one page for C# and another for VB.NET.

It shows the syntax for a number of common query operations, manipulations and attributes and can be a very useful quick reference :)

Dictionary<T> look-up or create made simpler

  • πŸ“…
  • πŸ“ 236
  • πŸ•™ 2
  • πŸ“¦ .NET
  • πŸ’¬ 6

The design of a Dictionary<T>Dictionary<T> lends itself well to a caching or identification mechanism and as a result you often see code that looks like this:

It’s not that it is particularly difficult but it can be a bit error prone and when you’re doing it over and over. What would be nicer is something that let you do:

LINQ to SQL resources

  • πŸ“…
  • πŸ“ 723
  • πŸ•™ 4
  • πŸ“¦ .NET

A quick round-up of some useful LINQ to SQL related resources that are available for developers. I’ve not used everything on this list myself so don’t take this as personal endorsement.

Note: While the T4 templating language is built-in to Visual Studio 2008/2010 it does not come with syntax highlighting or IntelliSense. Check out either:

LINQ to SQL tips and tricks #2

  • πŸ“…
  • πŸ“ 534
  • πŸ•™ 3
  • πŸ“¦ .NET
  • πŸ’¬ 4

A few more useful and lesser-known tips for using LINQ to SQL.

There are times when LINQ to SQL refuses to cook up the TSQL you wanted either because it doesn’t support the feature or because it has a different idea of what makes an optimal query.

LINQ to SQL tips and tricks #1

  • πŸ“…
  • πŸ“ 534
  • πŸ•™ 3
  • πŸ“¦ .NET
  • πŸ’¬ 4

Being on the inside of a product team often leads to uncovering or stumbling upon lesser-known techniques, and here are a few little nuggets I found interesting – I have more if there is interest.

LINQ to SQL lets you specify that a property is delay-loaded, meaning that not retrieved as part of normal query operations against that entity. This is particularly useful for binary and large text fields such as a photo property on an employee object that is rarely used and would cause a large amount of memory to be consumed on the client, not to mention traffic between the SQL and application.

Multiple outputs from T4 made easy

  • πŸ“…
  • πŸ“ 972
  • πŸ•™ 5
  • πŸ“¦ .NET
  • πŸ’¬ 14

An improved version is now available.

One of the things I wanted my LINQ to SQL T4 templates to do was be able to split the output into a file-per-entity. Existing solutions used either a separate set of templates with duplicate code or intrusive handling code throughout the template. Here’s my helper class to abstract the problem away from what is already complicated enough template code.

LINQ to SQL templates updated, now on CodePlex

  • πŸ“…
  • πŸ“ 193
  • πŸ•™ 1
  • πŸ“¦ .NET
  • πŸ’¬ 12

My templates that allow you to customize the LINQ to SQL code-generation process (normally performed by SQLMetal/LINQ to SQL classes designer) have been updated once again.

CodePlex makes it easier for people to be able to see and merge updates in with their own modified versions as well as report issues via the issue tracker etc. There is also an RSS feed that lets you keep track of releases, source updates or whatever else you are interested in.

ALT.NET Seattle

One of the cool things about living in Seattle is the sheer number of passionate developers around. Whether you’re dropping into offices, heading across campus for lunch, meeting downtown for music and beer or, in my case, last month taking a Saturday out to participate in ALT.NET Seattle, there are ideas, enthusiasm and discussions with great developers to be had everywhere.

The ALT.NET event was interesting. If you didn’t already know the name encapsulates:

LINQ to SQL log to debug window, file, memory or multiple writers

The Log property on a LINQ to SQL data context takes a TextWriter and streams out details of the SQL statements and parameters that are being generated and sent to the server.

Normally in examples you will see Console.Out being assigned to it which is fine for small demos and sandboxes but sooner or later you’ll want access to it in Windows or web applications. Here are some examples of how to redirect TextWriter output such as the DataContext log to other destinations.

LINQ to SQL T4 template reloaded

  • πŸ“…
  • πŸ“ 344
  • πŸ•™ 2
  • πŸ“¦ .NET
  • πŸ’¬ 10

A newer version of this LINQ to SQL template is available.

The topic of modifying the code generation phase of LINQ to SQL comes up quite often and the limited T4 template I published here last month was good at showing the potential but wasn’t a practical replacement for the code generation phase.

AnkhSVN 2.0 – free Subversion integration with Visual Studio

The guys over on the AnkhSVN team have acquired new members and burnt the midnight oil to deliver a great 2.0 release with:

Despite all these great features it’sΒ absolutely freeabsolutely free and still works with older versions of Subversion and both Visual Studio 2005 and 2008.

Localizing MVC for ASP.NET views and master pages

Microsoft’s MVC for ASP.NET is still under serious development but at the moment support for localization is a little weak. Here’s one approach that works with the 04/16 source-drop.

This class helps by trying to identify language-specific versions of views, user controls and master-pages where they exist, falling back to the generic one where necessary.

Using LINQ to foreach over an enum in C#

  • πŸ“…
  • πŸ“ 188
  • πŸ•™ 1
  • πŸ“¦ .NET
  • πŸ’¬ 8

I later expanded this out into a full Enum<T> strongly typed helper.

I can’t be the only person in the world who wants to foreach over the values of an enum otherwise Enum.GetValues(Type enumType) wouldn’t exist in the framework. Alas it didn’t get any generics love in .NET 2.0 and unhelpfully returns an array.

Windows 2008 Server on my MacBook Pro

A troublesome disk (a story for another time) has forced me to reinstall my MacBook Pro and review my Windows partition.

My Boot Camp partition was running Vista Ultimate x86 which felt sluggish, ignored the last 1GB and bugged me with UAC. One Windows update kept failing to install which also prevented SP1 from completing.

Web site vs web application in Visual Studio

Rob Conery got me thinking about web site maintenance and I put forward a brief comment on the two distinct types and how Visual Studio handles them which I have expanded upon here.

Primarily for working with ad-hoc web sites that have programmed elements. Easily identified by customer-specific content present in aspx files.

Where developer is succinct

Radio 4 covered the The Six Word Memoir competition, inspired by Earnest Hemingway’s wager he could tell a complete story in just six words. He deliciously delivered β€œFor sale: Baby shoes, never worn” earning him $10.

Expressing a life story in six words is just as tricky. Some of my favorite submissions include:

The pragmatic .NET developer

  • πŸ“…
  • πŸ“ 761
  • πŸ•™ 4
  • πŸ“¦ .NET
  • πŸ’¬ 10

Long-time friend, fellow co-host of the GSDF and the coding genius behind the open-source Ogre3D engine Steve Streeting has written an interesting piece on Open source adoption; countering the fear and doubt. I have no doubt that this was fueled by a lengthy discussion last night in the Ship & Crown pub – a common ritual after our GSDF meetings.

The reasons why I adopted .NET as my primary platform despite being tied to a single-supplier are:

Language Integrated Query: An introduction talk tomorrow

  • πŸ“…
  • πŸ“ 128
  • πŸ•™ 1
  • πŸ“¦ .NET, Guernsey

I’m just finishing up the slides, notes and writing code samples for my LINQ presentation at the Guernsey Software Developer Forum tomorrow evening.

Hopefully the broader scope of this presentation will mean a few new faces – the previous talks on Subversion and web application security might have been a little specific for a such a small audience (Guernsey is around 70,000 people on an island 9 miles long).

LINQ presentation at Guernsey Developer Forum

  • πŸ“…
  • πŸ“ 69
  • πŸ•™ 1
  • πŸ“¦ .NET
  • πŸ’¬ 2

I will be giving a talk at the Guernsey Software Developer Forum at the end of the month on Microsoft’s new Language Integrated Query (LINQ) with particular emphasis on the capabilities and object-relational mapping characteristics of LINQ to SQL.

Now confirmed for:

Thoughts on awareness of security vulnerabilities & full disclosure

  • πŸ“…
  • πŸ“ 322
  • πŸ•™ 2
  • πŸ“¦ .NET
  • πŸ’¬ 1

HTML, SQL and XSS injection vulnerabilities aren’t new but they are still largely ignored by developers.

My first encounter with these issues was in 1999 whilst writing an extranet e-commerce web site. Back then the ASP fix consisted of Server.HtmlEncode for all output and a Replace("'", """")Replace("'", """") for strings heading to SQL (other types headed there via CInt/CLong/CDate and I wasn’t aware of parametrized queries).

5 signs your ASP.NET application may be vulnerable to HTML injection

If you don’t encode data when using any of the following methods to output to HTML your application could be compromised by unexpected HTML turning up in the page and modifying everything from formatting though to capturing and interfering with form data via remote scripts (XSS). Such vulnerabilities are incredibly dangerous.

Using MonoRail or Microsoft’s MVC does not make you automatically immune – use {! }{! } in MonoRail’s Brail engine and the HtmlHelpers in Microsoft’s MVC to ensure correct encoding.

Shrinking JS or CSS is premature optimization

Rick Strahl has a post on a JavaScript minifier utility the sole job of which is to shrink the size of your JavaScript whilst making it almost impossible to read in order to save a few kilobytes.I thought I’d take a quick look at what the gain would be and fed it the latest version (1.6) of the very popular Prototype library:

The 30.7 KB saving looks great at first glance but bear in mind that external JavaScript files are cached on the client between page requests and it looses some appeal.If you also consider the fact that most browsers and clients support GZip compression and the savings there are around 4.7 KB4.7 KB and you might wonder if you are wasting your time.In computer science there is a term for blindly attempting to optimize systems without adequate measurement or justification and that term is premature optimization.As Sir Tony Hoare wrote (and Donald Knuth paraphrased)

Publishing .NET applications with prerequisites

  • πŸ“…
  • πŸ“ 117
  • πŸ•™ 1
  • πŸ“¦ .NET

Now .NET 3.5 is shipping I took the opportunity to update one of our internal applications and elected to have it install the necessary components (in this case the .NET Framework 3.5) using the Download prerequisites from the same location as my applicationDownload prerequisites from the same location as my application option.

When trying to install the application via the IIS web server the installer would fail with a download error.

Calculating CRC-64 in C# and .NET

  • πŸ“…
  • πŸ“ 233
  • πŸ•™ 2
  • πŸ“¦ .NET

Seeing how the CRC-32 C# class I posted some time ago continues to get lots of Google hits I thought I’d post a CRC-64 version which will no doubt be far less popular being the more limited use. Again, do not use this as a secure message signature, it’s really for backward compatibility with legacy systems.

This is the ISO-3309 version of CRC-64 algorithm. It is not compatible with the ECMA-182 algorithm.

Dissecting a C# Application – Inside SharpDevelop

  • πŸ“…
  • πŸ“ 104
  • πŸ•™ 1
  • πŸ“¦ .NET
  • πŸ’¬ 6

Cover of Dissecting a C# ApplicationThis great book shows you the process, thinking and code behind the open-source .NET IDE SharpDevelop that went on to branch into MonoDevelop.

It was not in print for very long but Apress bought Wrox when they closed down and made the book freely available on its site for download in PDF format.

Using GUIDs as row identifiers

  • πŸ“…
  • πŸ“ 387
  • πŸ•™ 2
  • πŸ“¦ .NET
  • πŸ’¬ 13

Wade Wright is preaching that IDs in a database should always be GUIDs and lists four reasons. I commented there with my opinions but it hasn’t shown up – some people like to censor if you don’t agree with them completely. My points addressing each of his four β€˜reasons’ were:

He does acknowledge that querying the database by hand is a bit of a pain but underestimates the Guid/uniqueidentifier performance penalty in SQL Server especially with regards to INSERTs (might be able to optimize there by having .NET generate the GUID instead of SQL Server).

Object Initializers in .NET 3.5

  • πŸ“…
  • πŸ“ 419
  • πŸ•™ 2
  • πŸ“¦ .NET

One compiler improvement in .NET 3.5 is the object initializers feature that lets you concisely set properties of an object as you create it.

If you’ve ever used VB.NET you may well have found and enjoyed the with keyword to write code such as:

Security vulnerabilities are not acceptable in sample code

Earlier this week the ASP.NET article of the day linked to 4-Tier Architecture in ASP.NET with C# which I noticed suffered from both HTML and SQL injection. I promptly informed the author and the ASP.NET site (who pulled the link) but the author was rather unconcerned and wrote (after editing my comment):

Thanks for your feedback Damieng. Sql statement has been used here to make the tutorial simple, it is informed in the DAL description.

Extension methods illustrated

  • πŸ“…
  • πŸ“ 480
  • πŸ•™ 3
  • πŸ“¦ .NET
  • πŸ’¬ 6

Extension methods are a great new feature in the .NET Framework 3.5 that let you write new methods that appear to be part of existing classes without the need to subclass or modify them.

We can explain this in simple terms with an example. Here is a useful routine that takes a string and returns what it finds between two other strings that works just fine with .NET 2.0 and .NET 1.1.

Color schemes for Visual Studio

The default syntax color scheme in Visual Studio seems to be stuck in the 16-color era so once you’ve found your perfect font you are going to need a great theme to go with it.

Here is the theme I’m currently using at home (currently on a 42β€³ 1900Γ—1200 LCD TV until I can find space for my monitor) that a couple of people have asked for.

Observations on Microsoft MVC for ASP.NET

Anyone who’s tried to develop large complex web sites with ASP.NET has likely run into many problems covering the page and control life cycle, view state and post backs and subsequent maintainability including the difficulty in creating automated unit tests.

Microsoft, taking a cue from the popularity of Ruby on Rails and subsequent .NET related efforts such as MonoRail, are embracing the model-view-controller (MVC) pattern and developing something more suited to web development than WebForms which aimed to make web development as similar to Windows development as possible (despite the major underlying differences in architecture).

Refactoring shared libraries and public APIs

Refactoring is an essential process to keep code clean and elegant while it evolves. IDE’s offer common refactorings (although somewhat short of those prescribed in Fowler’s excellent Refactoring book and way short of the overall goals explained in Kerievsky’s Refactoring Patterns).

One limitation of existing tools is that they can only update references within your solution. When you are refactoring a shared library this is a problem, especially if it is your public API to the outside world.

LINQ in 60 seconds

  • πŸ“…
  • πŸ“ 388
  • πŸ•™ 2
  • πŸ“¦ .NET

Microsoft’s Language INtegrated Query (LINQ) aims to provide a way of selecting objects with a common syntax independent of the data source.

By integrating query into the language instead strings parsed by an external provider at runtime we gain IntelliSense prompting for fields, members and table names and full compile-time syntax checking and a unified syntax.

Investigating MonoRail

  • πŸ“…
  • πŸ“ 528
  • πŸ•™ 3
  • πŸ“¦ .NET
  • πŸ’¬ 2

I hate fighting with a technology to get it to do what I want because it means I either have the wrong expectation or wrong technology.

With web development I expect strict web standard support and clean code that is easy to maintain.

Web Application Security for Developers presentation

Last nights Guernsey Software Developers Forum meeting was sparsely attended with a number of the regulars attendees absent. There were however two new faces including Kezzer who I’d been chatting to on-line for years.

Hopefully the low numbers were down to the seasonal summer holidays and the subsequent knock-on effect that we couldn’t get email out to the BCS Guernsey division to gather sufficient awareness.

Multiple-inheritance, composition and single responsibility principle in .NET

  • πŸ“…
  • πŸ“ 854
  • πŸ•™ 4
  • πŸ“¦ .NET
  • πŸ’¬ 5

.NET is often chided by C++ developers for failing to support multiple-inheritance. The reply is often Favor object composition over class inheritance – a mantra chanted from everywhere including the opening chapters of the Gang of Four’s Design Patterns book.

If the accepted mantra is that your object should expose interfaces and delegate the implementation of those interfaces elsewhere then it could really do with some better support than .NET currently offers especially where the interface comprises more than a member or two.

Typed session data in ASP.NET made easier still

  • πŸ“…
  • πŸ“ 289
  • πŸ•™ 2
  • πŸ“¦ .NET
  • πŸ’¬ 5

Philippe Leybaert is unimpressed with Microsoft’s Web Client Software Factory approach for typed session data and offers his own Typed session data made (very) easy which still seems overkill to me comprising as it does of generics, a delegate a helper class to achieve the desired effect. (Whilst you are there check out his very interesting MVC project for ASP.NET called ProMesh)

The solution which I have been using since my .NET 1.1 days is much simpler still and involves nothing more than creating a plain class with properties for every session variable and a static get accessor that obtains or creates it on the HttpContext similar to a singleton.

Partial methods in .NET 3.5, overview and evolution

  • πŸ“…
  • πŸ“ 473
  • πŸ•™ 3
  • πŸ“¦ .NET
  • πŸ’¬ 1

One of the interesting new things in .NET 3.5 is partial methods which are now being used extensively by LINQ to SQL and no-doubt will be Microsoft’s corner-post of extensibility for generated classes. Here’s a quick overview:

When inheriting from generated classed designers often provide virtual methods for you to override and extend at a cost of being forced to inherit from the generated class instead of one of your own choosing. e.g.

Rails-style controllers for ASP.NET

  • πŸ“…
  • πŸ“ 610
  • πŸ•™ 3
  • πŸ“¦ .NET
  • πŸ’¬ 1

Rob Conery has been putting together some great screen casts on SubSonic and his latest on generating controllers pointed out that ASP.NET doesn’t support the Rails-style http://site//controller/method style of execution.

This got me quite excited and I’ve put together a proof-of-concept web project that demonstrates mapping the path to controller methods using an IHttpHandlerIHttpHandler and reflection.

Italic syntax highlighting in Visual Studio 2005

I came across a posting by Thomas Restrepo about a theme for Vim he likes called Wombat and how it wouldn’t be worth porting to Visual Studio as it doesn’t support italic syntax highlighting – as we all know.

This got me thinking and I was able to port it with italicswith italics although the process is a bit of a hack.

CodeSmith template to generate LINQ To SQL Data Context

If you are interested in what LINQ to SQL generates and don’t have Orcas installed or available right now but useΒ CodeSmith try the following template to generate very similar code.

The primary difference is that this writes out the System types rather than the C# aliasesΒ (e.g. System.Int32 instead of int) but that could easily be changed but is binary compatibleΒ and otherwise almost identical to the source.

Discarding new entity objects in LINQ to SQL beta 1

  • πŸ“…
  • πŸ“ 404
  • πŸ•™ 2
  • πŸ“¦ .NET
  • πŸ’¬ 2

An unusual bug in .NET Framework 3.5 beta 1 that relates to creating a new entity object in LINQ to SQL has been getting in my way.

When you create a new entity object it is not automatically added to the database unless you either attach it to the table or create an association to another existing entity.

DiffMerge is free, try it with AnkhSVN

SourceGear, known for their Vault source control software, are giving away their three-way diff & merge tool DiffMerge for Windows, Mac and Unix.

DiffMerge has a clear interface and supports for file-type specific rule-sets that allow you to decide how to deal with white-space, line-endings, encoding etc.

LINQ to SQL NullReferenceException on SubmitChanges

  • πŸ“…
  • πŸ“ 176
  • πŸ•™ 1
  • πŸ“¦ .NET
  • πŸ’¬ 5

I’ve been busy working on some LINQ to SQL (formerly DLINQ) apps that have been going well bar a NullReferenceException thrown at me from deep in the bowels of LINQ and it’s change tracker. A cursory glance in debug showed none of the properties that represent columns were null…

The null was actually a collection property that represented a one-to-many relationship that was automatically created using the foreign key constraints in the database. Normally this is set to an empty EntitySet however I was failing to call the default constructor from my new useful constructor.

NotifyIcon context menus for both buttons in .NET (evolution of a hack)

  • πŸ“…
  • πŸ“ 625
  • πŸ•™ 3
  • πŸ“¦ .NET
  • πŸ’¬ 6

Here’s the evolution of what should have been a clean reusable component in .NET and how it becomes a hack thanks to the limitation of the .NET framework.

I’m working on an application where I want two contextual menus on the notify icon. The right one will display a number of options for settings and creating new items and the left to switch between the various items.

LINQ to SQL details, issues and patterns

  • πŸ“…
  • πŸ“ 872
  • πŸ•™ 4
  • πŸ“¦ .NET
  • πŸ’¬ 8

LINQ to SQL (formerly called DLINQ) is a simple object-relational mapper (ORM) scheduled for .NET Framework 3.5/Visual Studio 2007 (Orcas).

On projects with new data I’m keen on keeping the tables and classes as similar as possible and so the limited functionality of LINQ to SQL really appeals to me.

ActiveRecord, the ugly design pattern

I first encountered the Gang of Four Design Patterns book back in 2001 when a friend lent me a copy. I didn’t immediately get it, most likely because my object oriented experience up to that point consisted primarily of small Delphi applications.

In the last few years I’ve been working on much larger systems and have come to appreciate design patterns enough to get my own copy and also to invest in Martin Fowler’s excellent Patterns of Enterprise Architecture which provides higher-level patterns aimed at large data-driven applications.

AnkhSVN 1.0 released (Subversion plug-in for Visual Studio)

AnkhSVN 1.0 has been released!

If you use Visual Studio 2003 or 2005 and are currently either using the TortoiseSVN shell extension (or Subversion command line) then you would do well to see just how much more productive having source-control available from within the IDE can be.

How to spot a Visual Studio 2005 SP1 installation

If like me you have a couple of machines, a few virtual machines and secondary installations such as Express editions (for XNA of course) you can easily loose track of which have been patched with service pack 1. Especially if you also messed around with the SP1 beta.

Help > AboutHelp > About from Visual Studio 2005 can tell us – cryptically…

Eight things I hate about Visual Studio 2005

While Visual Studio is quite a capable IDE it isn’t perfect – here is my personal top 10 list of things I hate about it. I’ve kept the gripes to the IDE itself – the issues I have with .NET Framework deserve a post of their own some time.

Sometimes your solution has to be a mixed language one – you know the odd VB.NET class library that nobody wants to rewrite in C#.

LINQ in C# Web Applications

  • πŸ“…
  • πŸ“ 210
  • πŸ•™ 1
  • πŸ“¦ .NET

I’m a big fan of the Web Application type that was previously available as an add-on to Visual Studio 2005 but thankfully got promoted to a standard citizen with Service Pack 1.

So with a little more time on my hands lately I’ve been delving into the wonder that is LINQ – part of the forthcoming Orcas release of technologies.

Adding depth to my programming ability

I remember gazing at the screen of Acornsoft’s Elite in my childhood wondering what the code behind those 3D images looked like.

How did they rotate like that? How did it know which lines to hide? And more importantly where I can get a good price for this cargo hold of radio-actives and platinum?

Localizing .NET web applications

It seems that globalization often makes the wish list of many a web site until the client realizes professional quality translations require a significant investment of time and money.

On occasion however smaller web applications with their limited vocabulary are prime targets for localizationlocalization globalization and it can be quite feasible to translate the couple of hundred strings involved.

WinForms tricks & tips

  • πŸ“…
  • πŸ“ 308
  • πŸ•™ 2
  • πŸ“¦ .NET

I’m not sure why it doesn’t do this as standard but a simple event handler should do the trick:

People have asked (in the IRC #CSharp) why adding text to a TextBox is so slow and flickery. Normally they are trying:

Compile XNA for your Xbox 360 tomorrow?

  • πŸ“…
  • πŸ“ 189
  • πŸ•™ 1
  • πŸ“¦ .NET
  • πŸ’¬ 1

There’s a possibility that tomorrow will see the announcement of XNA Game Studio Beta 2 with support for compiling and running applications on your Xbox 360.

Originally this was scheduled for the final 1.0 release and would involve a $99 annual fee for the privilege but what better way to get hype and excitement than to offer it free for a month or two while it’s being polished and tested during the beta phase?

Parameterising the IN clause of an SQL SELECT in .NET

  • πŸ“…
  • πŸ“ 401
  • πŸ•™ 2
  • πŸ“¦ .NET
  • πŸ’¬ 6

I’m a fan of parameterized queries with a strong dislike for building SQL (or other magic strings). Encoding, escaping errors, localization formatting problems and injection can run rampant when you think everything is a string.

Today I found myself a quandary as I needed to SELECT records based on a list of values I had. e.g.

Switching from Boot Camp to Parallels

A few weeks ago I managed to screw up my Windows XP installation on my MacBook using some low-level tools and driver related stuff.

I’d already run out of space on the 30GB partition I’d allocated, I was missing the OS X side and not running any 3D applications so I took the plunge to remove the partition entirely and switch over to using the Parallels VM product I’d purchase instead.

AnkhSVN & TortoiseSVN

  • πŸ“…
  • πŸ“ 228
  • πŸ•™ 2
  • πŸ“¦ .NET
  • πŸ’¬ 2

I’m proud to announce that I’ve joined the AnkhSVN team, albeit in a rather minor capacity.

For the last few weeks I’ve been working on a set of new icons to add a bit of sparkle to the user interface for the forthcoming AnkhSVN 1.0 release. There is a good chance they will make the next release candidate that’s on it’s way to address some issues with delete/remove functionality.

Visual Studio 2005 Service Pack 1 Beta experiences

  • πŸ“…
  • πŸ“ 280
  • πŸ•™ 2
  • πŸ“¦ .NET

Like most people I’ve run into my fair share of oddities and problems in Visual Studio 2005 including the dreaded VB compiler dying a death on reasonable-sized projects so I jumped at the chance to get my hands on the beta of SP1.

There are several versions of the service pack including one for Visual Studio 2005, one for each of the Express editions and one for the Team Foundation Server. My experiences here are with the 350MB SP1 beta for Visual Studio 2005.

QuickReminder mini-app – Time based reminders in your system tray

  • πŸ“…
  • πŸ“ 235
  • πŸ•™ 2
  • πŸ“¦ .NET
  • πŸ’¬ 1

Screenshot of QuickReminder in actionWhether it’s a meeting for a specific time or remembering to stop the tea brewing in 7 minutes time (lovely tea from Adagio Teas that deserves it’s own blog post) events often whiz by without me noticing. I’m not great at time based background threading… but a computer is.

Sure I fire up Outlook (which I don’t use any more), iCal (Only open when I need it) or Google Calendar, create a new event, choose the type, choose which day and time it occurs at and mentally do the math in my head for 7 minutes from now taking the seconds into consideration…. but that’s distracting enough I think β€œNo, I’ll just remember” and I don’t.

Extending GridView to access generated columns

  • πŸ“…
  • πŸ“ 507
  • πŸ•™ 3
  • πŸ“¦ .NET

ASP.NET’s GridView is a useful control and one of it’s best features is it’s ability to generate the columns automatically from the data source given.

The problem however is that these generated columns are not exposed as part of the Columns collection or indeed available at all so you can’t hide or manipulate the selected columns.

Equatable Weak References

  • πŸ“…
  • πŸ“ 484
  • πŸ•™ 3
  • πŸ“¦ .NET

In a previous post I described a WeakReference<T>WeakReference<T> class for providing strongly-typed WeakReferenceWeakReference objects.

GitHub has the latest version of EquatableWeakReference<T>EquatableWeakReference<T>

Microsoft announces XNA for homebrew, score 1 for my prediction skills

  • πŸ“…
  • πŸ“ 213
  • πŸ•™ 1
  • πŸ“¦ .NET
  • πŸ’¬ 4

Over the last few months I’ve pieced together various snippets and hints from the web to come to the conclusion that Microsoft’s forthcoming XNA platform, specifically the XNA Framework version, would be available to home-brew developers and let them develop on the Xbox 360 – the first official home-brew since the PlayStation 1’s Net Yaroze!

Indeed I’ve been telling people in IRC and on forums that I believe this to be true. One friend, after messing with Managed DirectX2, told me if I was wrong about this I was in trouble. I went as so far to claim that it’s already tested and GarageGames Marble Blast Ultra was an XNA Framework title.

Calculating CRC-32 in C# and .NET

Just a few days ago I found myself needing to calculate a CRC-32 in .NET. With so many facilities available I was a little shocked that there was nothing built-in to do it so knocked up something myself.

GitHub has the latest version of Crc32

Implementing a generic WeakReference<T> in C#

  • πŸ“…
  • πŸ“ 384
  • πŸ•™ 2
  • πŸ“¦ .NET
  • πŸ’¬ 4

Check out the replacement EquatableWeakReference<T>EquatableWeakReference<T> class

A weak reference lets you hold a reference to an object that will not prevent it from being garbage collected. There are a few scenarios where this might be important – such as listening for events, caching, various MVC patterns.

Patterns of Enterprise Application Architecture

  • πŸ“…
  • πŸ“ 691
  • πŸ•™ 4
  • πŸ“¦ .NET

While a big fan of patterns I found the original Gang of Four (GoF) book a little dry and so had left the pattern books alone until Martin Fowler’s Patterns of Enterprise Application Architecture (PEAA), got referenced so many times on-line I gave in and purchased a copy. I’m glad I did – even if the examples are mostly in Java with the very occasional one in C#.

The patterns in the original GoF were really about the interactions between the objects themselves and whilst PEAA has some object-to-object interactions it concentrates on problems encountered in β€œEnterprise Applications”. This includes database mappings, transactions, web pages and concurrency.

Observing changes to a List<T> by adding events

  • πŸ“…
  • πŸ“ 580
  • πŸ•™ 3
  • πŸ“¦ .NET
  • πŸ’¬ 8

In an attempt to get more C# and .NET content up I’m putting up some snippets I’ve put together in response to questions on some C# user support groups. Many of them are not particularly advanced but they are quite useful.

GitHub has the latest version of ObservableList<T>ObservableList<T>

First look: Applying Domain-Driven Designs and Patterns

In an attempt to quench my thirst for all things C# and having already torn through the great .NET Framework Design Guidelines and less-great Effective C# I grabbed a copy of Applying Domain-Driven Design and Patterns (With Examples in C# and .NET) by Jimmy Nilsson.

The book is obviously based around domain models but also gives some coverage to test-driven development, NHibernate, design patterns, refactoring, code-smells etc.

Extend HttpApplication with session counts and uptime

It’s sometimes useful to know or display how many people are currently using your web application and how long it’s been up for.

As web applications normally inherit from System.Web.HttpApplicationSystem.Web.HttpApplication we can extend this class with a common re-usable class to add the required functionality.

IEnumerable<T> as IEnumerable<BaseClassOfT>

  • πŸ“…
  • πŸ“ 525
  • πŸ•™ 3
  • πŸ“¦ .NET
  • πŸ’¬ 10

A few weeks ago I touched on the substitutability of generic types and how Collection<BaseClass>Collection<BaseClass> is never substitutable for Collection<SubClass>Collection<SubClass>. This is because while the read facilities would be substitutable the write ones would not be. A Collection<SubClass>Collection<SubClass> can’t contain non-SubClass classes.

One approach for dealing with collections in general recommended in .NET Framework Design Guidelines is to expose IEnumeratorIEnumerator or IEnumerableIEnumerable interfaces rather than the collection itself – especially if you intend on it being read-only.

Piecing together Microsoft’s XNA gaming platform

I’ve briefly covered Microsoft’s XNA gaming platform before but have been trying to piece together what it is actually going to mean to developers.

Sorry, had to clarify the whole commercial/non-commercial parts. XNA Framework is just a portion of XNA… that won’t apply to the big guys.

Substitutability of generic types in .NET

  • πŸ“…
  • πŸ“ 504
  • πŸ•™ 3
  • πŸ“¦ .NET
  • πŸ’¬ 1

Anyone using object orientated programming soon finds themselves wanting to perform some action only if an object is of some type or implements some interface.

The easiest way is to do this is to use the isis operator. Typically it will appear something like:

Handling nullable value types in .NET 1.x

  • πŸ“…
  • πŸ“ 233
  • πŸ•™ 2
  • πŸ“¦ .NET

One of the great new features in .NET 2.0 is support for nullable types – especially important when dealing with value types such as Int or DateTime values coming from a database. Previously you were forced to either set and track another binary flag or to use a β€œspecial” value to represent null that sooner or later would turn up in real data.

In C# 2.0 thanks to a bit of syntactic sugar we can do this;

Bad programming advice – don’t use exceptions

  • πŸ“…
  • πŸ“ 226
  • πŸ•™ 2
  • πŸ“¦ .NET
  • πŸ’¬ 2

Kristian Dupont Knudsen has written a top 10 of programming advice notnot to follow with his rationalisation for each one. Being a programmer I thought I’d chip in with my 2 bits.

Joel recommends not using exceptions because they are β€œinvisible in the source code” and that they create β€œtoo many possible exit points”.

Microsoft XNA

  • πŸ“…
  • πŸ“ 517
  • πŸ•™ 3
  • πŸ“¦ .NET
  • πŸ’¬ 1

Microsoft have announced their XNA platform for game development.

The platform is based around C# and the .NET 2.0 CLR and frameworks, specifically tailored for the requirements of game developers. This might possibly mean much of the common language specification (CLS) elements are removed for performance.

Web applications in Visual Studio 2005

  • πŸ“…
  • πŸ“ 213
  • πŸ•™ 1
  • πŸ“¦ .NET

One of the things that annoyed me with Visual Studio.NET 2003 and Visual Studio 2005 is the web β€œproject” type.

The main problem is that these projects are not treated as traditional applications, but in order to please the ad-hoc web developer crowd they are treated as collections of files with no specific project options or compilation process – instead compiled on-the-fly by the web server.

Do not expose the implementation

  • πŸ“…
  • πŸ“ 548
  • πŸ•™ 3
  • πŸ“¦ .NET

One of the things we are taught in object oriented design is that the outside world should not be exposed to the complexities of how our object achieves their goals. Other developers are busy, don’t care and really don’t need to know. It is a sound idea and goes hand-in-hand with ease of use.

Televisions used to expose the implementation with a single tuning knob that had to be adjusted every time you wanted to watch another broadcast. With time engineers replaced this with an interface that hid the implementation, specifically the concept of channels where each one could be individually tuned and switched between on a whim. Implementation no longer exposed.

NullableTypes 1.3.1 beta

  • πŸ“…
  • πŸ“ 221
  • πŸ•™ 1
  • πŸ“¦ .NET

In my early .NET days I ran into a problem many developers integrating with other systems do. Unlike XML with it’s xsl:nilxsl:nil or database fields with <null><null> the standard .NET value-types don’t support the concept of null for missing values. It’s such an important omission that Microsoft implemented it in .NET 2.0 (now gone RTM and up on MSDN) with a generics class named Nullable<T>Nullable<T> and a little syntactic sugar to help it go down smoothly.

For those of us still working with .NET 1.1 the NullableTypes project provides null-capable versions of all your favorite .NET types and unlike the SqlTypes included in .NET these match the System types for precision and provide support for .NET remoting and web services.

Automatic comparison operator overloading in C#

  • πŸ“…
  • πŸ“ 531
  • πŸ•™ 3
  • πŸ“¦ .NET
  • πŸ’¬ 1

Abhinaba has blogged on the painful C# operator overloading experience.

The basic problem that is if you want to overload one, you soon end up many of the tests including == != < <= > >= Equals, Compare and probably CompareTo via IComparable when it turns out one function can provide everything needed in general use.

Conditional operator bug in .NET 1.x & 2.0

  • πŸ“…
  • πŸ“ 397
  • πŸ•™ 2
  • πŸ“¦ .NET

Update: This behavior is as expected according to the .NET team but it's probably unexpected for most users.

I encountered a strange problem this week when a conditional operator appeared to be evaluating the false expression contrary to the C# documentation. The line looked like:

Avoiding SQL injection

  • πŸ“…
  • πŸ“ 1,025
  • πŸ•™ 5
  • πŸ“¦ .NET

Back in ’98 I was developing an extranet site for a local company when I realized that it would be open for exploit if somebody put single quotes in text fields. It was early in the development cycle so I fixed it and moved on, unable to find out how other people were avoiding the problem.

It turned out many were not and it became a well-known exploit called SQL injection. Unfortunately there are many developers who don’t know or appreciate the problem, and it is this:

Visual Studio 2003 – System.ArgumentException in debugger

I recently ran into a problem while debugging inside Visual Studio 2003.Net. Google couldn’t find me an answer, only a few other people with the same problem. Here’s my solution in the hope it might save somebody else some time.

Whenever debugging a specific VB.NET application that used a C# class library I would receive the following error certain objects in the C# class library:

VB.NET to C# conversion

  • πŸ“…
  • πŸ“ 525
  • πŸ•™ 3
  • πŸ“¦ .NET

I recently converted some components on a project from VB.NET to C#, mainly for overloading and better tool support (such as ReSharper). Some of the existing code was generated from my own CodeSmith templates, so a small rewrite to generate C# handled most of that.

The remaining code, while not extensive in size, is a rather complex affair and the prospect of debugging this code when hand-converted was a little daunting so I decided to give the demo version of VBConversion’s VB.NET to C# Converter 1.31 a spin.

My .NET toolkit

  • πŸ“…
  • πŸ“ 397
  • πŸ•™ 2
  • πŸ“¦ .NET
  • πŸ’¬ 1

Every developer has his own favorite set of development tools and libraries that he’s come to rely on. Here’s a round-up of some I use or am looking at.

I’m also on the lookout for a replacement for my object-relational CodeSmith templates I knocked up a while back and have been refining since. While they are functional and incredibly fast I’m now wanting features they don’t provide such as database independence, lazy loading and locking patterns.

Lapsed-listeners – Memory leaks in subscriber-publisher scenarios

  • πŸ“…
  • πŸ“ 882
  • πŸ•™ 4
  • πŸ“¦ .NET
  • πŸ’¬ 1

I’ve been promising something .NET related for a while… here’s something!

There exists a β€˜gotcha’ in .NET (and other programming environment) whereby an object has subscribed to another objects published event will not be garbage collected when you expect because the environment itself holds a reference to the subscriber inside the event notification system.