Posts in category .net - page 14

Dissecting a C# Application – Inside SharpDevelop

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.

Alas, with their most recent web redesign their free e-books section has disappeared so I am temporarily hosting it here after recommending it to somebody interested in writing their own syntax highlighting editor on the MSDN forums.

Download Dissecting a C# Application – Inside SharpDevelop (Adobe PDF) (3.8MB)

[)amien

Using GUIDs as row identifiers

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:

  1. Avoid round-trips when creating new business objects I don’t know about you but I don’t populate my IDs until I persist and not on object creation so this reason is irrelevant.
  2. Data merging is easy Yes, this is a good reason to use GUIDs if you know merging is likely to happen.
  3. Type/table ignorance Basically he says here that a foreign key reference might relate to a row in any table which breaks relational concepts big time.
  4. Some weird anecdote I don’t quite get

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).

He also fails to consider how a page full of GUIDs will bloat out HTML page size especially if they end up used in a number of full drop-down SELECT boxes or collapsible JavaScript tree on a single page although deflate and GZip compression should take care of that if you’ve turned it on.

There are many valid scenarios for using GUIDs as unique identifiers but one size does not fit all using them without consideration will likely lead to somewhere bad ;-)

If you are using them and space is tight such as uncompressed HTML or the GET/POST size down you can write and parse the Guid as Base64 instead of hex format which cuts a Guid of 81187ecf-c452-4550-9ed2-8a51e3c46da1 (36 bytes) to z34YgVLEUEWe0opR48RtoQ== (22-24 bytes) which soon adds up. To do that in C# and .NET simply:

string base64 = Convert.ToBase64String(guid.ToByteArray());
Guid guid = new Guid(Convert.FromBase64String(base64));

For a further squeeze you could use ASCII85 encoding with Jeff Atwood’s ASCII85 implementation in C#.

[)amien

Object Initializers in .NET 3.5

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:

Dim myObj As MyClass
myObj = New MyClass()
With myObj
  .ProductCode = "ABC123"
  .Quantity = 5
  .Cost = 567.89
End With

This is more concise than writing myObj several times over, especially if setting a large number of properties, but as C# has no such keyword many people resorted to providing helpful constructors to facilitate code like:

MyClass myObj = new MyClass("ABC123", 5, 567.89);

If all three of these properties are essential then this makes for a sensible constructor however many classes have a number of properties that are optional and class designers struggle to determine whether to make constructors that merely cut-down on typing and which of the various combinations of optional properties might make sense in having their own constructor.

Invariably the combination you might want doesn’t exist and if it does the chances of being able to understand which properties are being set from one of a number of constructors that take parameters of similar types is quite low unless you go and take a peek with the IntelliSense.

Using object initializers you can stick to creating constructors that reflect parameters necessary to ensure your object is in a valid state and forget about providing helpful ones for those optional parameters. In our example if we assume the ProductCode is essential and the others are optional we can write code like:

MyClass myObj = new MyClass("ABC123") { Quantity = 5, Cost = 567.89 };

Which is both concise and easy to understand. It also requires no work on the part of the class designer and therefore works with all your existing classes. You can also nest them to set properties that require more complex types such as:

MyClass myObj = new MyClass("ABC123") {
   Quantity = 5,
   Cost = 567.89,
   Category = new Category("A") { Description = "New machine" }
};

This feature is no use if your objects are immutable in which case constructors are your only friend.

[)amien

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.

The problem is people borrowing this code may not notice the vulnerability or understand how to fix it. This isn’t the first time I’ve seen easily exploited sample code, responded and been buffed off with the it’s just sample code excuse.

Writing secure code isn’t difficult, time consuming or confusing to read.

Microsoft’s forthcoming LINQ toS QL and Entity Framework provide object-relational mapping that takes care of the SQL, as do other well-known ORM tools such as SubSonic and NHibernate.

If you must write your own data-access-layer (DAL) code use parameterized queries and not string concatenation.

When outputting values be 100% sure whether your technique will encode the values for you or not and be aware of what encoding tools are available to you.

ASP & ASP.NET’s Response.Write and <%= %> methods do NOT encode for you and you should be using HttpUtility.HtmlEncode to output data to a HTML stream.

Samples of vulnerable and secure code are in my presentation on Web Security I gave at the Guernsey Software Developer Forum a few months ago.

[)amien