Lorenz Cuno Klopfenstein

Posts tagged "dotnet"

I have been tinkering around my "home brewed" dependency injection library, as I mentioned in my last post. Since most of the code revolves around instantiating objects (well, and keeping them orderly registered), I figured it couldn't hurt to check out which is the best (i.e. fastest) way to dynamically instantiate objects in .NET.

There are essentially two ways you can register objects to my IoC container: using a delegate or using the type. The delegate is a really nice method, also used by Autofac (any comparison between my library and Autofac is probably an insult to Autofac  :)). It works like this:

container.Register(c => new Implementor());

In this case the delegate simply instantiates an instance of a class that implements the IInterface interface. Pretty slick and also very fast: calling the delegate is exactly one method call slower than calling the new operator, so that shouldn't be a problem at all.

Problem is, sometimes you can't register a delegate (for instance when you're registering dynamically loaded plug-ins to the container). In that case you need to manually instantiate the objects: .NET provides a lot of different ways to do that, and some methods can be compiled to dynamic methods or to delegates which probably should improve their performance.

There's a pretty complete blog post by Haibo Luo, but it's 5 years old and might not be accurate (it also misses the methods that use System.Linq.Expressions).

More...

Posted on Monday, January 11, 2010
155 Views
1 comments posted
ASP.NET MVC logo

As I mentioned in my previous article about how to render an ASP.NET MVC View to a string, there are several methods to do it and they probably are quite different performance-wise. Well, this time I've got some benchmarks.  :)

More...

Posted on Sunday, November 01, 2009
547 Views
0 comments posted

Building a localized application and ensuring that the correct language is used in its GUI (a process also called internationalization or i18n) has always been quite simple in .NET. Resx resource files natively support multiple localized versions (which are built into "satellite" dll assemblies) and automaticaly determine the correct resources to read from (eventually falling back to the base language).

This is done by creating a simple resource file containing all strings of your application (for instance, Strings.resx) and then define a localized version of the same strings in separate resource files (Strings.it.resx for the italian strings, Strings.de-CH.resx for the swiss-german dialect version... etc.).

String resources and localized versions.

Visual Studio will create a static Strings class (defined in Strings.Designer.cs) that you can use to retrieve each single string (this also allows you to retrieve the localized strings in a strongly typed fashion, ensuring that you won't have null strings and exceptions thrown around randomly in your code).

More...

Posted on Friday, June 05, 2009
1136 Views
0 comments posted

While I was implementing the data import/export functionalities of MotoX Stopwatch, having decided to use the XmlSerializer to load and save human readable files, I found out that the serializer doesn't work for TimeSpan values for some reason!  :S

It appears to be a known problem and several other people have already posted their workarounds. However, here's my solution using Cobra: mark the TimeSpan properties (which cannot be serialized normally) with the XmlIgnore attriute. This will force the serializer to skip them. Then declare new string properties, which you will never use in your code, that simply wrap the original TimeSpan value.

use System.Xml
use System.Xml.Serialization

class StopWatchInfo
	has Serializable

	# ... normal properties ...
	
	# The next property will be ignored by the serializer
	var time as TimeSpan
		is public
		has XmlIgnore
		
	# This property wraps the one above for the serializer
	pro timeWrap as String
		get
			return .time.toString
		set
			ret = TimeSpan()
			if TimeSpan.tryParse(value, out ret)
				.time = ret
			else
				.time = TimeSpan.zero

Remember that the serializer uses the property names of the class, therefore "timeWrap" will appear in the output file instead of "time". To avoid this, you'll want to rename the wrapping property adding an XmlAttribute to it.

Posted on Tuesday, November 11, 2008
253 Views
2 comments posted

XNA logo

Giuseppe Maggiore, Microsoft student partner at the faculty of computer science of Venice, is leading a series of lessons about Microsoft XNA. I have been attending these interesting lessons from the start, and last week Giuseppe announced a Microsoft sponsored contest: the objective is to produce a little XNA demo game with spaceships, planets and such. The first prize is an XBox 360 and an XNA premium membership account!  :D

Obviously, I'll have to try and win that prize!

I'll try to cover my partecipation to the contest in this series of articles, displaying the evolution of the game, step by step, as I'm going to build it.

Objectives

First of all, I'm firmly decided not to hack together an ugly demo to show off some of the techniques available on XNA. I neither want to develop a full blown XNA game engine, but I'd like to take the time to define a flexible architecture for the game and develop it in a cleanly coded project.

The formal objectives of the contest are the following:

  • Build the model of a solar system: this is gonna be fun, with moving planets, orbits and so on. I'll skip on realism and try to be as creative as possible.  :)
  • Collision detection: I know this is one of the hardest components to develop correctly and efficiently (it's one of the "difficult" problems of class hierarchies and can be solved by double dispatching, but I'll have to investigate...).
  • Moving cameras: easy.
  • Advanced shading: this is gonna be fun! And also, lots of code around on the 'net.
  • Game logic: I have some interesting ideas about this.

Setup

There are several needed components in order to start coding: first of all, Visual Studio!

XNA 2.0 seems to be compatible only with Visual Studio 2005. I originally switched to Visual Studio 2008 since Beta 2 and wouldn't like to switch back just for this contest, but hey... (I'll miss automatic properties in C# and all that nice stuff though  :().

I got a Visual Studio 2005 professional license from the university's MSDN Accademic Alliance and then had to upgrade it with the following additional downloads from Microsoft:

And that's it: after 2 hours or so of installation, I'm ready to go!

Posted on Tuesday, April 15, 2008
Tagged as
344 Views
0 comments posted

While working on the latest revision of OnTopReplica, I tought it would be great to store the custom regions selected by the user and persist them to file, in order to reload them when the application starts. So, the problem was essentially:

"How to store a list of rectangles (regions) and strings to file and load them again?"

Of course, working with .NET on Windows, you are confronted with several options for storing your application's data:

  • Local files: this is one of my favorite options, since the settings file can be copied and modified very easily by the user. However, on Vista this file would most likely be stored in a folder normally not accessible to a limited user account, and you'd have to write some kind of parsing and file handling functionality.
  • The register: this may sound as the place to store settings, but I really don't like the settings being hidden from the user's eyes. And by the way, I hate when uninstalled applications leave a mess behind in the register.
  • .NET Application Settings: this is the simplest approach and is recommended by Microsoft itself. The .NET component will store the data for you in a folder in the user's AppData files, loading and parsing it automagically. Additionally, Visual Studio has a settings editor that simplifies your task enormously.

Closer look to the .NET Settings

The Visual Studio project tree All Visual Studio C# projects include a Settings.settings file that can be used to store the application's data. The format of this data can be changed very easily using the visual editor and Visual Studio will automatically generate a specific class that loads, stores and handles your data and can be used from your code.

All data is usually serialized as an XML file in:

\Users\<User>\AppData\Local\<AppAuthor>\<AppName>_<Hash>

The built-in editor looks like this:

The settings editor

Every data element can be either a User element (which means it may assume a different value from user to user, on the same system) and an Application element (will have a unique value and be read-only). Accessing the data from code is really simple:

Intellisense support

Also remember that settings will be loaded automatically on start up, but you'll have to explicitly save the data to disk (usually whan you close the main form and exit the application):

Settings.Default.Save();

The problem: storing an ArrayList of objects

The code above works perfectly in most cases, is easy to use, shifts a lot of complexity out of your code... great!  :D

But in fact, after a couple of tests, I found out that I was unable to store a list of objects to the file. It seems to be impossible to use Generic collections in the NAP settings, therefore I had to choose a standard ArrayList of objects in order to store the user's regions (a Rectangle and a string, as said before). But even if I tried to save the ArrayList to disk it didn't work still, returning an empty collection of regions on the next start up...  :S

The problem is simple if you think about it: the settings file manager asks the ArrayList to serialize itself to Xml. That's easily done, but unfortunately ArrayList knows nothing about the stuff it contains and cannot serialize it at all! The solution I found is the following:
Implement a specific derivate of ArrayList with a custom serialization function and call the correct (custom) serialization method on the objects in the collection.

Sounds easy? It is (after you hit the wall a couple of times...): this is the code of the custom class deriving from ArrayList:

public class StoredRegionArray : ArrayList, IXmlSerializable { #region IXmlSerializable Members public System.Xml.Schema.XmlSchema GetSchema() { return null; } public void ReadXml(System.Xml.XmlReader reader) { this.Clear(); XmlSerializer x = new XmlSerializer(typeof(StoredRegion)); while (reader.ReadToFollowing("StoredRegion")) { object o = x.Deserialize(reader); if (o is StoredRegion) this.Add(o); } } public void WriteXml(System.Xml.XmlWriter writer) { XmlSerializer x = new XmlSerializer(typeof(StoredRegion)); foreach(StoredRegion sr in this){ x.Serialize(writer, sr); } } #endregion }

And the following is the "StoredRegion" class. This class simply keeps a rectangle and a string together and handles their XML serialization (in order to be serialized by the ArrayList above):

public class StoredRegion : IXmlSerializable { public StoredRegion() { } public StoredRegion(Rectangle r, string n) { Rect = r; Name = n; } public Rectangle Rect { get; set; } public string Name { get; set; } public override string ToString() { return Name; } #region IXmlSerializable Members public System.Xml.Schema.XmlSchema GetSchema() { return null; } public void ReadXml(System.Xml.XmlReader reader) { if (reader.MoveToAttribute("name")) Name = reader.Value; else throw new Exception(); reader.Read(); XmlSerializer x = new XmlSerializer(typeof(Rectangle)); Rect = (Rectangle)x.Deserialize(reader); } public void WriteXml(System.Xml.XmlWriter writer) { writer.WriteAttributeString("name", Name); XmlSerializer x = new XmlSerializer(typeof(Rectangle)); x.Serialize(writer, Rect); } #endregion }

And that's it! Selecting the StoredRegionArray as the type we wish to store in the settings editor, the list of regions will be correctly serialized and deserialized using our custom methods.  :)

Posted on Saturday, February 02, 2008
Tagged as
1080 Views
4 comments posted
Back to Klopfenstein.net
Clemens Klopfenstein Serena Kiefer Lukas Tiberio Klopfenstein Lorenz Cuno Klopfenstein
English German