<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>activa&#039;s blog</title>
	<atom:link href="http://blog.activa.be/index.php/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.activa.be</link>
	<description>.NET, Web, Mobile and more stuff I can&#039;t stop talking about</description>
	<lastBuildDate>Tue, 08 May 2012 21:39:43 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.1.2</generator>
		<item>
		<title>Vici Core, the forgotten child</title>
		<link>http://blog.activa.be/index.php/2012/05/vici-core/</link>
		<comments>http://blog.activa.be/index.php/2012/05/vici-core/#comments</comments>
		<pubDate>Tue, 08 May 2012 21:39:43 +0000</pubDate>
		<dc:creator>Philippe Leybaert</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Frameworks]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Vici Project]]></category>
		<category><![CDATA[Windows Phone]]></category>

		<guid isPermaLink="false">http://blog.activa.be/?p=204</guid>
		<description><![CDATA[The Vici Project has been around for about 4 years now, and although most of the attention has gone to CoolStorage, the unsung hero of the framework collection is Vici Core, a general-purpose toolkit for .NET and Mono]]></description>
			<content:encoded><![CDATA[<p>The Vici Project has been around for about 4 years now, and although most of the attention has gone to CoolStorage, the unsung hero of the framework collection is Vici Core, a general-purpose toolkit for .NET and Mono.</p>
<p>I bet most people don&#8217;t have a clue what Vici Core is, and the current website doesn&#8217;t offer a lot of insight either, so I thought it might be a good idea to give an overview of the components included in the toolkit. I will follow up with additional blog posts describing the components in more detail.</p>
<h3>What is Vici Core?</h3>
<p>The most important parts of Vici Core are the dynamic expression parser and template rendering engine. These components allow the developer to incorporate runtime expression parsing and template rendering in their applications. The parser is generic, meaning that it can handle any imaginable syntax, but it includes a C# style expression parser in the core library.<br />
The parser and template renderer are both based on a generic and extensible tokenizer. The tokenizer is also used by the built-in JSON parser.</p>
<p>This is a quick overview of the components in Vici Core:</p>
<ul>
<li><a href="#tokenizer">Tokenizer</a></li>
<li><a href="#parser">Expression Parser (C# built-in)</a></li>
<li><a href="#template">Template engine</a>
<ul>
<li>Mustache syntax</li>
<li>Velocity syntax</li>
<li>Vici MVC syntax</li>
</ul>
</li>
<li><a href="#json">JSON parser</a></li>
<li>JSON serializer</li>
<li><a href="#configuration">Configuration</a></li>
<li><a href="#logging">Logging</a></li>
<li><a href="#typeconversion">Exception-free smart type conversion</a></li>
<li><a href="#smartcache">SmartCache</a></li>
<li>FastReflection</li>
<li>Notifications/Subscriptions</li>
<li><a href="#scheduling">Scheduling</a></li>
<li>Binary and Base64 serialization</li>
</ul>
<p>Best of all, these components can be used on the following platforms:</p>
<ul>
<li>.NET 3.5 or higher</li>
<li>Windows Phone 7.5</li>
<li>MonoTouch</li>
<li>Mono for Android</li>
</ul>
<p>If you want to check it out, feel free to download the source and/or binaries at <a href="http://viciproject.com/core">viciproject.com</a></p>
<p>Below is a description of most of the components in the framework.</p>
<p><a name="tokenizer"></a></p>
<h2>Tokenizer</h2>
<p>The Vici Core tokenizer allows you to tokenize any stream of characters to a list of tokens. The tokenizer is extensible so you can define your own tokenizer logic by creating classes implementing the <strong>ITokenParser</strong> and <strong>ITokenProcessor</strong> interfaces.</p>
<p>Using the tokenizer, you can take the following string:</p>
<p><strong>Items["Key"] = 45;</strong></p>
<p>And turn it in the following list of tokens:</p>
<table border="1" cellspacing="0" cellpadding="6">
<tbody>
<tr>
<td>Items</td>
<td>[</td>
<td>"</td>
<td>Key</td>
<td>"</td>
<td>]</td>
<td>=</td>
<td>45</td>
<td>;</td>
</tr>
</tbody>
</table>
<p>The code for this is would be:</p>
<pre class="brush: csharp; title: ;">
Token[] tokens = new CSharpTokenizer().Tokenize(&quot;Items[\&quot;Key\&quot;] = 45;&quot;);
</pre>
<p>To give you an idea of the way you would write your own token recognizer, this is the source code of one of the built-in classes that will recognize a string (keyword):</p>
<pre class="brush: csharp; title: ;">
    // This class does double duty, implementing both ITokenMatcher and ITokenProcessor
    public class KeywordMatcher : ITokenMatcher, ITokenProcessor
    {
        private int _index;
        private readonly string _string;

        public KeywordMatcher(string s) { _string = s; }

        public ITokenProcessor CreateTokenProcessor()
        {
            return new KeywordMatcher(_string);
        }

        public void ResetState() { _index = 0; }

        public TokenizerState ProcessChar(char c, string fullExpression, int currentIndex)
        {
            if (_index &gt;= _string.Length)
                return TokenizerState.Success;

            return (c == _string[_index++]) ? TokenizerState.Valid : TokenizerState.Fail;
        }

        public string TranslateToken(string originalToken, ITokenProcessor tokenProcessor)
        {
            return originalToken;
        }
    }
</pre>
<p><a name="parser"></a></p>
<h2>Expression Parser</h2>
<p>Vici&#8217;s expression parser builds an expression tree from any expression. Internally, it tokenizes the input string, reorders the tokens to RPN notation (using the Shunting Yard algorithm) and then creates a true expression tree that can be used to evaluate the expression.</p>
<p>Although you could use Vici&#8217;s parser to parse any syntax, only the C# syntax is supported in the core library.</p>
<p>In its simplest form, this is how you could use the expression parser:</p>
<pre class="brush: csharp; title: ;">
CSharpParser parser = new CSharpParser();

int value = parser.Evaluate&lt;int&gt;(&quot;5+4*a&quot;,new CSharpContext(new {a=10}));

// value == 45
</pre>
<p>Since it is a true C# expression parser, you can use any C# (2.0) feature you like:</p>
<pre class="brush: csharp; title: ;">
CSharpContext context = new CSharpContext();
CSharpParser parser = new CSharpParser();

context.AddType(&quot;Math&quot;,typeof(Math));
context.Set(&quot;f&quot;, new Func&lt;int,int&gt;(i =&gt; i*2));
context.Set(&quot;obj&quot;, new { Value=5 });

int value1 = parser.Evaluate&lt;int&gt;(&quot;5 * f(2)&quot;, context);
double value2 = parser.Evaluate&lt;double&gt;(&quot;Math.Cos(1.0)&quot;, context);
string value3 = parser.Evaluate&lt;string&gt;(&quot;obj.Value.ToString()&quot;, context);
</pre>
<p><a name="template"></a></p>
<h2>Template Engine</h2>
<p>Vici&#8217;s template rendering engine is based on the built-in expression parser, adding support for extra control structures like <strong>conditional statements</strong>, <strong>loops</strong> and <strong>external references</strong>.</p>
<p>The templates can be anything from simple strings to HTML files and mail templates. As an example, I&#8217;ll present a real-world mail template that could be used to send out order confirmation e-mails to a customer:</p>
<pre class="brush: plain; title: ;">
Dear $Order.Customer.Prefix $Order.Customer.LastName,

Thank you for your order. The estimated shipping date is $Order.EstShipDate

Your order:
#foreach(item in Order.OrderItems)
$item.Description ($item.Price)
#end

Total price: $ $Order.TotalPrice
...
</pre>
<p>Rendering this template is done in just a few lines of code:</p>
<pre class="brush: csharp; title: ;">
Order order = OrderService.ReadOrder(...);

CSharpContext data = new CSharpContext(new { Order = order });
VelocityTemplateParser parser = new VelocityTemplateParser();

string renderedMail = parser.Render(template, data);

MailService.SendMail(order.Customer.Email, renderedMail);
</pre>
<p>This is just one of the many ways you could use the template engine. In addition, it&#8217;s very easy to create your own template syntax definitions. Check out the source code of the built-in template syntax handlers to learn more.</p>
<p><a name="json"></a></p>
<h2>JSON Parser</h2>
<p>JSON data can be parsed to a dictionary or to a real object. The parser will try to match the JSON data structure to the target object&#8217;s properties or fields.</p>
<pre class="brush: csharp; title: ;">
// json:
// { &quot;firstname&quot; : &quot;John&quot; , &quot;lastname&quot; : &quot;Doe&quot;, &quot;children&quot; : [ &quot;Kelly&quot;,&quot;Tim&quot; ] }

public class Person
{
    public string FirstName;
    public string LastName;
    public string[] Children;
}

// ...
JSONParser parser = new JSONParser();

Person person = parser.Parse&lt;Person&gt;(json);
</pre>
<p><a name="configuration"></a></p>
<h2>Configuration Framework</h2>
<p>The configuration framework allows you to map data from a data source (XML file, app.config, database, &#8230;) to class properties and fields. </p>
<p>For example, if this is your app.config file:</p>
<pre class="brush: xml; title: ;">
&lt;appSettings&gt;
    &lt;add key=&quot;Database.Server&quot; value=&quot;db.mycompany.com&quot; /&gt;
    &lt;add key=&quot;Database.Port&quot; value=&quot;6005&quot; /&gt;
    &lt;add key=&quot;Database.Schema&quot; value=&quot;Customers&quot; /&gt;
    &lt;add key=&quot;LogFile&quot; value=&quot;Z:\Logs\Logfile.txt&quot; /&gt;
&lt;/appSettings&gt;
</pre>
<p>Then you can easily map this to some static &#8220;Config&#8221; object in your application:</p>
<pre class="brush: csharp; title: ;">
public class Config
{
     public class _Database
     {
          public string Server;
          public int Port;
          public string Schema;
     }

     public static _Database Database;
     public static string Logfile;
}

//...

ConfigManager configManager = new ConfigManager();

configManager.Register&lt;Config&gt;();

configManager.RegisterProvider(new ConfigurationProviderAppConfig());
configManager.Update();

//...

Database.Connect(Config.Database.Name, Config.Database.Port);
</pre>
<p>The source of your configuration can be anything you like. The framework will call your configuration provider class and the provider simply has to return key/value pairs. Keys can be structured using dotted notation. The values will be converted to the target datatype (strings, numbers, arrays, &#8230;)</p>
<p>Versioning is also supported. Your configuration objects will be updated when a version number is changed in your source file.</p>
<p><a name="logging"></a></p>
<h2>Logging</h2>
<p>Logging is something that can be found in a lot of third-party libraries, but since it&#8217;s not that complicated to implement, it was added to Vici Core to minimize dependencies. The end result is a pretty decent logging framework.</p>
<p>It features:</p>
<ul>
<li>Pluggable logging providers (logging to multiple providers at the same time)</li>
<li>Log levels (Debug,Warning,Error,Fatal, &#8230;)</li>
<li>Log rotation and cleanup (by hour,day,week,month,&#8230;)</li>
<li>Dynamic log file names (with embedded dates)</li>
</ul>
<p>In its simplest form, logging can be added to your application like this:</p>
<pre class="brush: csharp; title: ;">
Logger.Default.AddProvider(new LogProviderFile(&quot;c:\\logs\\logfile.txt&quot;));

//...
Logger.Default.Log(LogLevel.Debug, &quot;User logged in: {0}&quot;, userName);
//...
Logger.Default.LogException(ex);
//...
</pre>
<p><a name="smartcache"></a></p>
<h2>SmartCache</h2>
<p>What&#8217;s in a name? SmartCache is a very simple but flexible caching framework that supports most basic features a caching solution should have:</p>
<ul>
<li>Configurable cache size</li>
<li>Fully typed</li>
<li>Thread-safe</li>
<li>Cache entries can be configured to time out after a specific time or at a specific absolute time</li>
</ul>
<p>Code sample:</p>
<pre class="brush: csharp; title: ;">
var cache = new SmartCache&lt;Record&gt;(500); // max. 500 cache entries

// add item, does not expire
cache.Add(record1.Key, record1);
// add item, expires after 30 minutes when not accessed
cache.Add(record2.Key, record2, TimeSpan.FromMinutes(30));
// add item, expires in exactly 10 minutes
cache.Add(record3.Key, record3, DateTime.Now.AddMinutes(10));

// Retrieving:

// Checks if a record is cached and retrieves it
if (cache.TryGetValue(&quot;key1&quot;, out record)) ...

// Tries to retrieve a record from the cache, and if not found
// the supplied delegate will be called to fetch the record again
// and store it back in the cache
cache.TryGetValue(&quot;key2&quot;, out record, () =&gt; Database.LoadRecord(&quot;key2&quot;));
</pre>
<p><a name="typeconversion"></a></p>
<h2>Type Conversion</h2>
<p>The Smart Conversion library allows you to convert any datatype to another data type, without risking type conversion exceptions.</p>
<p>Heuristics are used to convert values from one type to another.</p>
<p>Examples:</p>
<pre class="brush: csharp; title: ;">
string s1 = &quot;25&quot;;
string s2 = &quot;0&quot;;
string s3 = &quot;&quot;;
string s4 = null;
string s5 = &quot;a&quot;;
enum LogLevel { Debug = 0, Information = 1, Error = 2, FatalError = 3 };

int a = s1.To&lt;int&gt;(); // returns 25
int b = s2.To&lt;int&gt;(); // returns 0
int c = s3.To&lt;int&gt;(); // returns 0
int d = s4.To&lt;int&gt;(); // returns 0
int e = s5.To&lt;int&gt;(); // returns 0
int? e = s1.To&lt;int?&gt;(); // returns 25
int? f = s2.To&lt;int?&gt;(); // returns 0
int? g = s3.To&lt;int?&gt;(); // returns null
int? h = s4.To&lt;int?&gt;(); // returns null
int? i = s5.To&lt;int?&gt;(); // returns null

LogLevel ll1 = &quot;1&quot;.Convert&lt;LogLevel&gt;(); // returns LogLevel.Information
LogLevel ll2 = &quot;3&quot;.Convert&lt;LogLevel&gt;(); // returns LogLevel.FatalError
LogLevel ll3 = &quot;Error&quot;.Convert&lt;LogLevel&gt;(); // return LogLevel.Error

// If a value can't be converted, the default is returned, which is
// the value 0 (zero) casted to the enum type (according to the C# specs).
// If the target type is nullable and the conversion fails, null is returned.

LogLevel ll4 = &quot;5&quot;.Convert&lt;LogLevel&gt;(); // returns LogLevel.Debug
LogLevel ll5 = &quot;Bogus&quot;.Convert&lt;LogLevel&gt;(); // returns LogLevel.Debug
LogLevel? ll6 = &quot;5&quot;.Convert&lt;LogLevel?&gt;(); // returns null
LogLevel? ll7 = &quot;Bogus&quot;.Convert&lt;LogLevel?&gt;(); // returns null
</pre>
<p>You can also plug in your own converter in the framework. This allows you to perform very specific type conversions by just calling <strong>stringValue.To<TargetType>()</strong>.</p>
<p><a name="scheduling"></a></p>
<h2>Scheduler</h2>
<p>The Scheduler is a collection of classes to allow your application to perform certain tasks at a predefined schedule (for example: every 5 minutes, every monday at 4pm, every 2nd of the month at noon, &#8230;)</p>
<p>A few built-in schedulers are included, but you can create your own very easily.</p>
<pre class="brush: csharp; title: ;">
Scheduler scheduler1 = new CyclicScheduler(null, TimeSpan.FromMinutes(30));

// inside your application, call ShouldRun to check if your task should run:
if (scheduler1.ShouldRun) {}

// Monthly or daily schedulers
Scheduler scheduler2 = new MonthlyScheduler(&quot;MONTHLY&quot;, new TimeSpan(12, 0, 0), 5, 10);
Scheduler scheduler3 = new TimeOfDayScheduler(&quot;DAILY&quot;, new TimeSpan(12, 0, 0));
</pre>
<p>Of course, having a scheduler that runs every month or so should have a means of remembering when it ran for the last time. If your application quits, that information will be lost. To handle this, you can attach a <strong>HistoryStore</strong> object to a scheduler. If you don&#8217;t specify one, an in-memory store is used. There is one other built-in store: the <strong>FileHistoryStore </strong>which stores state in a file on disk.</p>
<pre class="brush: csharp; title: ;">
Scheduler scheduler = new MonthlyScheduler(&quot;MONTHLY&quot;, new TimeSpan(12, 0, 0), 5, 10);
scheduler.HistoryStore = new FileHistoryStore(&quot;c:\\appstate.hst&quot;);
</pre>
<h2>There&#8217;s more&#8230;</h2>
<p>Yes, there&#8217;s more, but I ran out of breath. I will try to go into more detail in the next few weeks. In the meantime, feel free to download the bits at <a href="http://viciproject.com/core">viciproject.com</a> and check it out.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.activa.be/index.php/2012/05/vici-core/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Simple traditional classes in Javascript</title>
		<link>http://blog.activa.be/index.php/2011/12/simple-traditional-classes-in-javascript/</link>
		<comments>http://blog.activa.be/index.php/2011/12/simple-traditional-classes-in-javascript/#comments</comments>
		<pubDate>Thu, 22 Dec 2011 09:11:51 +0000</pubDate>
		<dc:creator>Philippe Leybaert</dc:creator>
				<category><![CDATA[Javascript]]></category>

		<guid isPermaLink="false">http://blog.activa.be/?p=191</guid>
		<description><![CDATA[A simple way to create java-like classes in Javascript.]]></description>
			<content:encoded><![CDATA[<p>Yesterday I saw a <a href="http://stackoverflow.com/questions/8594536/how-can-i-fix-this-example-so-that-it-works-after-the-first-or-second-subclass">question on StackOverflow</a> by someone who wanted to have something similar to real classes in Javascript. This caught my interest and tried to come up with a very simple way to define &#8220;traditional&#8221; classes in Javascript.</p>
<p>I&#8217;m sure this has been done several times before by hundreds of people, but I wanted to see what I could do with my limited knowledge of Javascript. </p>
<p>The idea was to be able to do something like this:</p>
<pre class="brush: jscript; title: ;">
var Shape = new Class( { color:&quot;white&quot;, area: function() { return 0.0; } } );

var Square = Shape.Derive({side:0.0, area:function() { return this.side*this.side; } } );
var Circle = Shape.Derive({r:0.0, area:function() { return this.r*this.r*Math.PI; } } );

var shapes = [];

shapes.push(new Square({side:5.0}));
shapes.push(new Circle({r:5.0}));
shapes.push(new Square({side:3.0 , color:&quot;red&quot;}));

for (var i in shapes)
  console.log(&quot;area = &quot; + shapes[i].area() + &quot; , color = &quot; + shapes[i].color);

/*
Should output:
area = 25 , color = white
area = 78.53981633974483 , color = white
area = 9 , color = red
*/
</pre>
<p>The code required to make this happen is surprisingly simple. A real Javascript ninja could make it even shorter I&#8217;m sure:</p>
<pre class="brush: jscript; title: ;">
Class = function(parent, options) {
    if (parent &amp;&amp; typeof(parent) != 'function') {
      options = parent;
      parent = undefined;
    }

    var newClass = function(o) { $.extend(this,o); };

    if (typeof(parent) == 'function') {
      newClass.prototype = new parent();
    }

    $.extend(newClass.prototype,options);

    newClass.Derive = function(o) { return new Class(newClass,o); };

    return newClass;
  };
</pre>
<p>I admit, it does use jQuery ($.extend), but it wouldn&#8217;t be hard to write a simple replacement function for that one. It simply copies the properties of a given object to another object. Maybe I&#8217;ll add that when I have some time to burn.</p>
<p>As you can see, there are 3 ways to create a class:</p>
<pre class="brush: jscript; title: ;">
var NewClass1 = new Class( prototype );
var NewClass2 = new Class( BaseClass, prototype );
var NewClass3 = BaseClass.Derive( prototype );
</pre>
<p>In all cases, the prototype parameter is optional. It is used to define functions and default properties for each class.</p>
<p>That&#8217;s it. If you think it&#8217;s useful, feel free to use it for whatever you like.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.activa.be/index.php/2011/12/simple-traditional-classes-in-javascript/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Using SQLite in a Windows Phone app</title>
		<link>http://blog.activa.be/index.php/2011/04/using-sqlite-in-a-windows-phone-app/</link>
		<comments>http://blog.activa.be/index.php/2011/04/using-sqlite-in-a-windows-phone-app/#comments</comments>
		<pubDate>Wed, 27 Apr 2011 12:47:39 +0000</pubDate>
		<dc:creator>Philippe Leybaert</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Vici Project]]></category>
		<category><![CDATA[Windows Phone]]></category>
		<category><![CDATA[Open Source]]></category>
		<category><![CDATA[ORM]]></category>
		<category><![CDATA[sqlite]]></category>
		<category><![CDATA[windows phone]]></category>

		<guid isPermaLink="false">http://blog.activa.be/?p=159</guid>
		<description><![CDATA[Adding support for SQLite to a Windows Phone app is actually very easy. Vici CoolStorage, an open-source data access layer and ORM, allows you to add local SQLite db access to your Windows Phone app with just a few lines of code, even if you don't want to use the ORM features at all.]]></description>
			<content:encoded><![CDATA[<p>In the current version of Windows Phone, there&#8217; s no support for a built-in local database. This will be taken care of in the next release of the OS (codename &#8220;Mango&#8221;), which will be released late this year. Mango will have a built-in SQL CE (-like) database which can be accessed using LINQ to SQL. At the time of writing, there seem to be a few drawbacks you&#8217;ll have to keep in mind:</p>
<ul>
<li>The backend store is in a non-standard format</li>
<li>It&#8217;s not possible to execute ad-hoc SQL queries (neither DDL nor DML)</li>
<li>Shipping a database file with your app is a complicated process</li>
</ul>
<p>If any of these limitations is a blocker for your application, or you just want to have a local database right now, using SQLite is a great alternative.</p>
<h3>Using CoolStorage for easy SQLite access on Windows Phone</h3>
<p>By far the easiest way to use a local SQLite database in your Windows Phone app is by using the free, open-source Vici CoolStorage ORM library. There is a specific native build for Windows Phone which includes a driver for SQLite.</p>
<p>Adding CoolStorage to your app is pretty straightforward:</p>
<ul>
<li>Option 1: If you have NuGet installed in VS2010, add the <strong>Vici CoolStorage</strong> package (available in the NuGet gallery)</li>
<li>Option 2: If you don&#8217;t have NuGet, <a href="http://viciproject.com/wiki/Projects/CoolStorage/Download" target="_blank">download the binaries</a> from the Vici Project website and reference both Vici.Core.WP7.dll and Vici.CoolStorage.WP7.dll</li>
</ul>
<p>Then you add the following line of code somewhere in your initialization code:</p>
<pre class="brush: csharp; light: true; title: ;">
    CSConfig.SetDB(&quot;mydb.sqlite&quot;); // &quot;mydb.sqlite&quot; is the name of your database file
</pre>
<p>By default, CoolStorage will create the database file for you if it doesn&#8217;t exist. But for this article, we&#8217;ll assume you already have a database with data (see <a href="#existingdb">here</a>)</p>
<p>CoolStorage is a <a href="http://viciproject.com/wiki/Projects/CoolStorage/Doc/UserGuide/Mapping" target="_blank">full-blown ORM</a> with support for relations, lazy loading, relation prefetching, etc, so you will be able to use all of that in your Windows Phone app, but for once I won&#8217;t go into that, because if you want you can also use CoolStorage as a lightweight data layer and execute ad-hoc SQL queries.</p>
<p>Here are some examples:</p>
<pre class="brush: csharp; title: ;">
// execute a SQL insert statement
CSDatabase.ExecuteNonQuery(&quot;insert into customer (name,city) values (@name,@city)&quot;,
                                  new { name=&quot;Microsoft&quot;, city=&quot;Redmond&quot; });
</pre>
<pre class="brush: csharp; title: ;">
// execute a select SQL statement and map the result to a class

class QueryResult
{
   public string name;
   public int numsales;
   public decimal totalsales;
}

QueryResult[] results = CSDatabase.RunQuery&lt;QueryResult&gt;(
                                        @&quot;select name,count(*),sum(s.total)
                                            from salesperson sp
                                            inner join sales s on s.salespersonid=sp.id
                                            group by sp.name&quot;);
</pre>
<pre class="brush: csharp; title: ;">
// retrieve a scalar value (for example, the total number of customers)

int numCustomers = CSDatabase.GetScalar&lt;int&gt;(&quot;select count(*) from customer&quot;);
</pre>
<p>So if you&#8217;re not that crazy about ORM&#8217;s, or you want to execute some very specific SQL satements, you can do that very easily on Windows Phone with a local SQLite db.</p>
<h3>Shipping a SQLite database file with your app</h3>
<p>If you have an existing SQLite database file and you want to ship it with your application, you&#8217;ll have to make it available in <b>Isolated Storage</b>. This is pretty straightforward, but not always obvious:</p>
<p>First, add your database file to your Visual Studio project and set the build action to &#8220;Content&#8221; (also leave &#8220;Do not copy&#8221;). </p>
<p>Then add the following piece of code before calling <b>CSConfig.SetDB(&#8230;)</b>:</p>
<pre class="brush: csharp; title: ;">
string fn = &quot;mydb.sqlite&quot;;

StreamResourceInfo sr = Application.GetResourceStream(new Uri(fn, UriKind.Relative));

IsolatedStorageFile iStorage = IsolatedStorageFile.GetUserStoreForApplication();

if (!iStorage.FileExists(fn))
{
   using (var outputStream = iStorage.OpenFile(fn, FileMode.CreateNew))
   {
      byte[] buffer = new byte[10000];

      for(;;)
      {
         int read = sr.Stream.Read(buffer, 0, buffer.Length);

         if (read &lt;= 0)
             break;

         outputStream.Write(buffer, 0, read);
      }
   }
}

// Now you can use your database

CSConfig.SetDB(fn);
</pre>
<p>Having the possibility to ship a SQLite database file with your app is especially useful if you want to share a pre-built database with other mobile platforms, since both iPhone and Android have built-in support for SQLite.</p>
<p>In a next post, I will show how to use the ORM features of CoolStorage.</p>
<p>And while you&#8217;re at it, you might as well use MonoTouch (and CoolStorage) for building the iPhone version of your app, allowing you to reuse all of your business logic and data layer code.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.activa.be/index.php/2011/04/using-sqlite-in-a-windows-phone-app/feed/</wfw:commentRss>
		<slash:comments>14</slash:comments>
		</item>
		<item>
		<title>CoolStorage now supports Windows Phone</title>
		<link>http://blog.activa.be/index.php/2011/04/coolstorage-now-supports-windows-phone/</link>
		<comments>http://blog.activa.be/index.php/2011/04/coolstorage-now-supports-windows-phone/#comments</comments>
		<pubDate>Fri, 15 Apr 2011 01:09:19 +0000</pubDate>
		<dc:creator>Philippe Leybaert</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Frameworks]]></category>
		<category><![CDATA[Vici Project]]></category>
		<category><![CDATA[Windows Phone]]></category>
		<category><![CDATA[CoolStorage]]></category>
		<category><![CDATA[windows phone]]></category>

		<guid isPermaLink="false">http://blog.activa.be/?p=149</guid>
		<description><![CDATA[Our CoolStorage ORM has been around for quite a while, but I felt that it was particularly useful as a data access layer on smaller scale applications and mobile devices running .NET (or some flavor of it). Not everybody needs a massive (*) data access layer like Entity Framework or NHibernate. About a year ago [...]]]></description>
			<content:encoded><![CDATA[<p>Our CoolStorage ORM has been around for quite a while, but I felt that it was particularly useful as a data access layer on smaller scale applications and mobile devices running .NET (or some flavor of it). Not everybody needs a massive (*) data access layer like Entity Framework or NHibernate.</p>
<p>About a year ago support for <a href="http://monotouch.net/">MonoTouch</a> was added to the core library, which meant you could use SQLite databases in iPhone and iPad applications when using MonoTouch. Porting CoolStorage to MonoTouch was fairly straightforward because the MonoTouch guys did a great job by building an ADO.NET provider for SQLite in the core MonoTouch library.</p>
<p>Next up: Windows Phone support. I wanted to get this done in time for Microsoft&#8217;s Mix conference, but I was shocked to learn there was no ADO.NET or System.Data available. This meant the complete data access layer had to be refactored to use custom interfaces instead of ADO.NET interfaces and classes, which I did. A few days before MIX, CoolStorage was running successfully on Windows Phone using an SQLite databases in isolated storage. </p>
<p>To recap, Vici CoolStorage now supports the following databases out of the box:</p>
<ul>
<li>SQL Server (on .NET)</li>
<li>MySQL (on .NET)</li>
<li>SQLite (on .NET)</li>
<li>SQLite (on MonoTouch)</li>
<li>SQLite (on Windows Phone)</li>
</ul>
<p>The version supporting Windows Phone (1.5) is not yet released, but a development build can be downloaded from the <a href="http://viciproject.com/coolstorage">Vici Project website</a>. The final release of version 1.5 is planned before the end of April.</p>
<p>(*) <a href="http://blog.wekeroad.com/">Rob Conery</a> wrote a very useful and lightweight data layer which he named &#8220;<a href="http://blog.wekeroad.com/helpy-stuff/and-i-shall-call-it-massive">Massive</a>&#8220;. So I&#8217;m obviously not referring to that.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.activa.be/index.php/2011/04/coolstorage-now-supports-windows-phone/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Handling dates in JSON responses with jQuery 1.4 (the easy way)</title>
		<link>http://blog.activa.be/index.php/2010/03/handling-dates-in-json-responses-with-jquery-1-4-the-easy-way/</link>
		<comments>http://blog.activa.be/index.php/2010/03/handling-dates-in-json-responses-with-jquery-1-4-the-easy-way/#comments</comments>
		<pubDate>Fri, 12 Mar 2010 16:46:05 +0000</pubDate>
		<dc:creator>Philippe Leybaert</dc:creator>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[JSON]]></category>

		<guid isPermaLink="false">http://www.blog.activa.be/PermaLink,guid,a4a87d68-d356-4706-98fd-228a2c8ba651.aspx</guid>
		<description><![CDATA[Handling dates in JSON responses is something many web developers struggle with. The JSON Specification doesn&#8217;t specify how dates should be represented in a JSON string, so every implementation invented its own way of representing dates. These are some of the formats in use today: {&#8220;date&#8221;: new Date(ms_since_epoch) } {&#8220;date&#8221;: Date(ms_since_epoch) } {&#8220;date&#8221;: &#8220;Date(ms_since_epoch) } [...]]]></description>
			<content:encoded><![CDATA[<p>Handling dates in JSON responses is something many web developers struggle with. The JSON Specification doesn&#8217;t specify how dates should be represented in a JSON string, so every implementation invented its own way of representing dates.</p>
<p>These are some of the formats in use today:</p>
<ol>
<li>{&#8220;date&#8221;: new Date(ms_since_epoch) }</li>
<li>{&#8220;date&#8221;: Date(ms_since_epoch) }</li>
<li>{&#8220;date&#8221;: &#8220;Date(ms_since_epoch) }</li>
<li>{&#8220;date&#8221;: &#8220;/Date(ms_since_epoch)/&#8221; }</li>
<li>{&#8220;date&#8221;: &#8220;\/Date(ms_since_epoch)\/&#8221; }</li>
<li>{&#8220;date&#8221;: &#8220;yyyy-MM-ddTHH:mm:ssZ&#8221; }</li>
<li>{&#8220;date&#8221;: &#8220;yyyy-MM-ddTHH:mm:ss&#8221; }</li>
</ol>
<p>Formats 1 and 2 are actually invalid JSON. However, they&#8217;re the only formats that were handled correctly by jQuery 1.3.2 and earlier. eval() also handles these. But again, it&#8217;s not valid JSON.</p>
<p>That leaves the other 5 formats, which are valid according to the JSON specs.</p>
<p>Starting with version 1.4, jQuery&#8217;s built-in JSON evaluator will check if there is a function <strong>JSON.parse() </strong>available. If it is there, it will use that function to evaluate JSON objects. If not, jQuery will use the &#8220;unsafe&#8221; <strong>eval()</strong> way of parsing JSON. <strong>JSON.parse()</strong> is a function from the <strong>json2.js</strong> file, which can be downloaded from the <a href="http://json.org">JSON website</a></p>
<h3>The problem</h3>
<p>JSON.parse() doesn&#8217;t handle dates. <strong>At all</strong>. But it does have a way to handle non-standard values by specifying an extra parameter &#8220;reviver&#8221;, which is a function that takes a value and returns the value converted to the data type of your choice.</p>
<p>For example: if you want to handle the ISO date format correctly, you can do this:</p>
<pre class="brush: jscript; title: ;">

var parsedObject = JSON.parse(jsonData, function (key, value) {
   var a;

   if (typeof value === 'string') {
     a =/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);

     if (a) {
       return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4], +a[5], +a[6]));
     }
   }

   return value;
});
</pre>
<p>(this example is taken from the json2.js source code)</p>
<p>This function will check if a string value parsed from the JSON string is in a specific date format, and return a Javascript date object.</p>
<p>You could expand this function to handle every other possible date format, which shouldn&#8217;t be too hard to do, but how do you tell jQuery to use this &#8220;reviver&#8221; function?</p>
<p>Well, you can&#8217;t.</p>
<h3>The solution</h3>
<p>There&#8217;s an easy solution: after including <strong>json2.js</strong>, redefine the <strong>JSON.parse()</strong> function so it passes your conversion (<em>reviver</em>) function to the original <strong>JSON.parse()</strong> function:</p>
<pre class="brush: jscript; title: ;">
&lt;script type=&quot;text/javascript&quot; src=&quot;json2.js&quot;&gt;&lt;/script&gt;
&lt;script&gt;
(function() {
   var _origParse = JSON.parse;

   JSON.parse = function(text) {
      return _origParse(text, function(key, value) {
         var a;

         if (typeof value === 'string') {
            a = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);

            if (a)
                 return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4], +a[5], +a[6]));

            if (value.slice(0, 5) === 'Date(' &amp;&amp; value.slice(-1) === ')') {
               var d = new Date(value.slice(5, -1));

               if (d)
                  return d;
            }
         }

         return value;
      });
   }
})();

&lt;/script&gt;
</pre>
<p>Now when you return some JSON object to your jQuery script, dates will be parsed correctly, without having to change your code. The code snippet above handles cases 3 to 6 correctly. I&#8217;ll leave it up to you to add case 7&#8230;</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.activa.be/index.php/2010/03/handling-dates-in-json-responses-with-jquery-1-4-the-easy-way/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>The difference between 1986 and 2010</title>
		<link>http://blog.activa.be/index.php/2010/03/the-difference-between-1986-and-2010/</link>
		<comments>http://blog.activa.be/index.php/2010/03/the-difference-between-1986-and-2010/#comments</comments>
		<pubDate>Tue, 09 Mar 2010 21:53:03 +0000</pubDate>
		<dc:creator>Philippe Leybaert</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[iPhone]]></category>
		<category><![CDATA[Objective-C]]></category>

		<guid isPermaLink="false">http://www.blog.activa.be/PermaLink,guid,354c0d02-c7e0-41b6-824e-d4f4af50bf05.aspx</guid>
		<description><![CDATA[The iPhone is a fabulous device, few people will argue about that. But&#8230; When I started developing iPhone apps about a year ago, it felt&#8230; awkward. If you want to create an app for the iPhone, you have to use Objective C, which was invented sometime around 1934. I&#8217;m kidding of course: it was 1986, [...]]]></description>
			<content:encoded><![CDATA[<p>The iPhone is a fabulous device, few people will argue about that.</p>
<p>But&#8230;</p>
<p>When I started developing iPhone apps about a year ago, it felt&#8230; awkward. If you want to create an app for the iPhone, you have to use Objective C, which was invented sometime around 1934. I&#8217;m kidding of course: it was 1986, but that&#8217;s a small detail.</p>
<p>Apart from the odd syntax (which is fine, other languages have odd syntax as well), I was amazed by the lack of basic language and framework features we take for granted these days.</p>
<p>To illustrate the contrast, I&#8217;ll show a small function that strips the time portion of a date, written in Objective C:</p>
<pre class="brush: objc; title: ;">
+ (NSDate *) stripTime:(NSDate *) date {
   NSCalendar *gregorian =
         [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];

   NSDateComponents *components =
          [gregorian components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit)
                       fromDate:date];

   date = [gregorian dateFromComponents:components];

   [gregorian release];

   return date;
}
</pre>
<p>The same thing in C#:</p>
<pre class="brush: csharp; title: ;">
public DateTime StripTime(DateTime date)
{
    return date.Date;
}
</pre>
<p>I guess I have been spoiled by C#. Can you imagine what it would be like to consume a SOAP webservice from Objective C? Well, <a href="http://www.odesk.com/jobs/iPhone-application-consuming-WSDL_%7E%7E5c5a496dcee19ea9">check this out</a>. (I have to admit: it received a 5-star rating, so I guess it was worth the 62 hours spent on it)</p>
<p>PS. I realize I suck at Objective C, and I&#8217;m sure a better Objective C developer can shave off a line or 2 of my code, but you get the picture&#8230;</p>
<p>Thank god a few geniuses over at Novell created <a href="http://monotouch.net">MonoTouch</a>&#8230;</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.activa.be/index.php/2010/03/the-difference-between-1986-and-2010/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Vici CoolStorage: ORM on MonoTouch made simple</title>
		<link>http://blog.activa.be/index.php/2010/02/vici-coolstorage-orm-on-monotouch-made-simple/</link>
		<comments>http://blog.activa.be/index.php/2010/02/vici-coolstorage-orm-on-monotouch-made-simple/#comments</comments>
		<pubDate>Thu, 25 Feb 2010 08:23:24 +0000</pubDate>
		<dc:creator>Philippe Leybaert</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[CoolStorage]]></category>
		<category><![CDATA[MonoTouch]]></category>
		<category><![CDATA[ORM]]></category>
		<category><![CDATA[Vici]]></category>

		<guid isPermaLink="false">http://www.blog.activa.be/PermaLink,guid,b7318bfb-25c4-4925-8143-4f57913fa74b.aspx</guid>
		<description><![CDATA[I&#8217;ve been developing iPhone apps for the past 9 months using the recommended development tools, being Xcode, Interface Builder and the iPhone SDK. Being a C# .NET programmer didn&#8217;t make this easy: Objective-C is&#8230; weird and&#8230; primitive. Dealing with pointers after 10 years of focusing on problems instead of memory addresses is a slight culture [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve been developing iPhone apps for the past 9 months using the recommended development tools, being Xcode, Interface Builder and the iPhone SDK.</p>
<p>Being a C# .NET programmer didn&#8217;t make this easy: Objective-C is&#8230; weird and&#8230; primitive. Dealing with pointers after 10 years of focusing on problems instead of memory addresses is a slight culture shock, but luckily having previous C and C++ experience helps a lot.</p>
<p>In September last year, the geniuses (by lack of a stronger word) at Novell&#8217;s Mono team came up with <a href="http://monotouch.net" target="_blank">MonoTouch</a>, a C# cross-compiler that allows you to build iPhone apps using .NET and C#, including the use of most of the .NET Framework. I&#8217;m not going to go into detail on how this works. Enough has been written about this subject.</p>
<p>One feature of MonoTouch caught my attention: as of version 1.2, an ADO.NET provider was added for accessing the iPhone&#8217;s native SQLite database format. A relational database accessed from C# code desperately needs an ORM, don&#8217;t you agree? So last weekend I decided to try and port the CoolStorage ORM to MonoTouch. It wasn&#8217;t as easy as I thought, because of some severe limitations in the version of SQLite installed on the iPhone, but in the end I got it working, and working well.</p>
<p>To give you an idea of the time you&#8217;ll save by using an ORM like CoolStorage on the iPhone, I will present three examples:</p>
<ol>
<li>Reading a list of records using the iPhones&#8217;s SQLite library (C / Objective-C)</li>
<li>Reading a list of records using ADO.NET + MonoTouch</li>
<li>Reading a list of records using CoolStorage + MonoTouch</li>
</ol>
<p>We&#8217;re not going to make it too complicated. The example reads a list of customer records. It retrieves the ID, Name and City. No filters are being applied, simply a list of customers ordered by Name. After that, it prints the records to the console.</p>
<p>The examples also omits the declaration of the Customer class (which is used to hold a single customer record)</p>
<p><strong><span style="text-decoration: underline;">Native Objective-C example</span></strong>:</p>
<pre class="brush: objc; title: ;">
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [documentPaths objectAtIndex:0];

databasePath = [documentsDir stringByAppendingPathComponent:@&quot;mydb.db3&quot;];

sqlite3 *database;

customers = [[NSMutableArray alloc] init];

if(sqlite3_open([databasePath UTF8String], &amp;amp;database) == SQLITE_OK) {
   const char *sql = &quot;select id,name,city from customer order by name&quot;;
   sqlite3_stmt *stmt;

   if(sqlite3_prepare_v2(database, sql, -1, &amp;amp;stmt, NULL) == SQLITE_OK) {

      while(sqlite3_step(stmt) == SQLITE_ROW) {
           Customer *customer = [[Customer alloc] init];

           customer.CustomerID = sqlite3_column_int(stmt, 0)];
           customer.Name = [NSString stringWithUTF8String:(char *)sqlite3_column_text(stmt, 1)];
           customer.City = [NSString stringWithUTF8String:(char *)sqlite3_column_text(stmt, 2)];

           [customers addObject:customer];

	   [customer release];
      }
   }

   sqlite3_finalize(stmt);
}

sqlite3_close(database);

for (int i=0;i&amp;lt;[customers count];i++) {
   Customer *customer = [customers objectAtIndex:i];

   NSLog(&quot;ID: %d, Name: %@, City: %@&quot;,customer.CustomerID,customer.Name,customer.City);
}
</pre>
<p>It&#8217;s pretty obvious that things will get unbearably complicated when you try to do things like accessing related records, persisting data to the database, and so on.</p>
<p><em>Now let&#8217;s introduce MonoTouch and ADO.NET.</em></p>
<p><strong><span style="text-decoration: underline;">ADO.NET example (MonoTouch)</span></strong>:</p>
<pre class="brush: csharp; title: ;">
string dbName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), &quot;mydb.db3&quot;);

var conn = new SqliteConnection(&quot;Data Source=&quot; + dbName);

List customers = new List();

using (var cmd = conn.CreateCommand())
{
  conn.Open();
  cmd.CommandText =&quot;select id,name,city from customer order by name&quot;;
  using(var reader = cmd.ExecuteReader())
  {
    while (reader.Read())
    {
      Customer customer = new Customer();

      customer.CustomerID = int.Parse(reader[&quot;id&quot;].ToString());
      customer.Name = (string) reader[&quot;name&quot;];
      customer.City = (string) reader[&quot;city&quot;];

      customers.Add(customer);
    }
  }
}

foreach (var customer in customers)
   Console.WriteLine(&quot;ID: {0}, Name: {1}, City: {2}&quot;,customer.CustomerID,customer.Name,customer.City);
</pre>
<p>Now that&#8217;s a <strong>lot</strong> better, don&#8217;t you think? But still, it requires a lot of boilerplate code that&#8217;s just there to distract you from what you&#8217;re actually trying to do: read a list of records from the database.</p>
<p>So let&#8217;s move to the next level:</p>
<p><strong><span style="text-decoration: underline;">CoolStorage example (MonoTouch)</span></strong>:</p>
<pre class="brush: csharp; title: ;">
string dbName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), &quot;mydb.db3&quot;);

CSConfig.SetDB(dbName, false);

var customers = Customer.List().OrderedBy(&quot;Name&quot;);

foreach (var customer in customers)
   Console.WriteLine(&quot;ID: {0}, Name: {1}, City: {2}&quot;,customer.CustomerID,customer.Name,customer.City);
</pre>
<p>Well, you get the picture&#8230; Now you can focus on the application instead of data access technology. Isn&#8217;t this what it&#8217;s all about?</p>
<p>In case you want to use this in your own code, go ahead and grab the latest development build of CoolStorage, which now fully supports MonoTouch. It can be downloaded from the <a href="http://viciproject.com/coolstorage" target="_blank">CoolStorage website</a>.</p>
<p>Best of all, it&#8217;s open source&#8230;</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.activa.be/index.php/2010/02/vici-coolstorage-orm-on-monotouch-made-simple/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Javascript equality – nothing is what it seems</title>
		<link>http://blog.activa.be/index.php/2009/06/javascript-equality-nothing-is-what-it-seems/</link>
		<comments>http://blog.activa.be/index.php/2009/06/javascript-equality-nothing-is-what-it-seems/#comments</comments>
		<pubDate>Fri, 05 Jun 2009 20:45:55 +0000</pubDate>
		<dc:creator>Philippe Leybaert</dc:creator>
				<category><![CDATA[Javascript]]></category>

		<guid isPermaLink="false">http://www.blog.activa.be/PermaLink,guid,c6f8f5b4-ac44-4cf9-a2be-b7af027ae728.aspx</guid>
		<description><![CDATA[Read till the end, because nothing is what it seems What is equality? Equality means different things in different programming languages. In most modern languages (C# for example), you can define your own terms of what equality means. In others you can&#8217;t. Take javascript for example. There are actually two kinds of equality: normal equality [...]]]></description>
			<content:encoded><![CDATA[<p>Read till the end, because <strong>nothing is what it seems</strong></p>
<p><span style="text-decoration: underline;"><em>What is equality?</em></span></p>
<p>Equality means different things in different programming languages. In most modern languages (C# for example), you can define your own terms of what equality means. In others you can&#8217;t.</p>
<p>Take javascript for example. There are actually two kinds of equality: <strong>normal equality</strong> and<strong> being identical</strong>.</p>
<p>To check if two variables or values are equal, you use:</p>
<pre class="brush: jscript; title: ;">
f (a == b) {
  // ...
}
</pre>
<p>To check if two variables are identical, you use:</p>
<pre class="brush: jscript; title: ;">
if (a === b) {
  // ...
}
</pre>
<p>Most articles (and even supposedly good books) define the latter comparison as <strong>being equal and of the same type</strong>. While this over-simplification may be true in the majority of cases, it is <strong>very inaccurate</strong>, because you have to know what &#8220;equal&#8221; means. I’m not going to talk about javascript’s normal equality operator (==), because enough has been written about that. I’ll focus on the === operator.</p>
<p>The correct meaning of === is that the 2 operands should be identical. This means they should reference the same object, or, in the case of value types, the values should be the same. Only <strong>numbers</strong> and <strong>booleans</strong> are value types. <strong>Strings</strong> behave as value types, but they are actually reference types.</p>
<p>Bringing this all together, let&#8217;s look at some examples of equality in javascript:</p>
<pre class="brush: jscript; title: ;">
var a = 1;
var b = 1;

alert(a == b); // true
alert(a === b); // true

b = &quot;1&quot;;

alert(a == b); // true
alert(a === b); // false
</pre>
<p>These are the obvious ones. Now the more interesting stuff:</p>
<pre class="brush: jscript; title: ;">
var a = [1,2,3];
var b = [1,2,3];
var c = a;

alert(a === b); // false (these look equal to me, and of the same type)
alert(a === c); // true
</pre>
<p>Remember I mentioned that strings behave like value types? Now it becomes interesting:</p>
<pre class="brush: jscript; title: ;">
var a = &quot;12&quot; + &quot;3&quot;;
var b = &quot;123&quot;;

alert(a === b); // returns true, because strings behave like value types
</pre>
<p>And to make it really interesting:</p>
<pre class="brush: jscript; title: ;">
var a = new String(&quot;123&quot;);
var b = &quot;123&quot;;

alert(a === b); // returns false !! (but they are equal and of the same type)
</pre>
<p>I thought strings behave like value types? Well, it depends who you ask&#8230;</p>
<p><strong>EDIT</strong>: As one of the commenters (zihotki) points out, the last example adds another twist to the story. Creating a string using the String() object constructor actually doesn&#8217;t create a variable of type &#8220;string&#8221;, but of type &#8220;object&#8221;. But you can use the object as a string. If you are unaware of this behavior, you can easily shoot yourself in the foot without knowing it.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.activa.be/index.php/2009/06/javascript-equality-nothing-is-what-it-seems/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Vici MVC finally released as part of the Vici Project</title>
		<link>http://blog.activa.be/index.php/2009/05/vici-mvc-finally-released-as-part-of-the-vici-project/</link>
		<comments>http://blog.activa.be/index.php/2009/05/vici-mvc-finally-released-as-part-of-the-vici-project/#comments</comments>
		<pubDate>Sat, 30 May 2009 11:59:04 +0000</pubDate>
		<dc:creator>Philippe Leybaert</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Frameworks]]></category>
		<category><![CDATA[MVC]]></category>
		<category><![CDATA[Vici]]></category>

		<guid isPermaLink="false">http://www.blog.activa.be/PermaLink,guid,5ba1dd20-939b-4f32-bb18-7eb1ca881953.aspx</guid>
		<description><![CDATA[Even before there was talk about ASP.NET MVC, there were a few open source MVC frameworks available for .NET. Among them, MonoRail was best known, but there was also ProMesh.NET, a .NET MVC web framework that evolved from a small personal project to a full-blown MVC framework for building web applications in .NET, without using [...]]]></description>
			<content:encoded><![CDATA[<p>Even before there was talk about ASP.NET MVC, there were a few open source MVC frameworks available for .NET. Among them, MonoRail was best known, but there was also ProMesh.NET, a .NET MVC web framework that evolved from a small personal project to a full-blown MVC framework for building web applications in .NET, without using ASP.NET WebForms.</p>
<div style="float: right;"><a href="http://viciproject.com" target="_blank"><img title="Vici Project" src="http://dstyler.com/vici/300x100/im-_Logo300.jpg" border="0" alt="Vici Project" /></a></div>
<p>A few months ago, just before the release of ProMesh.NET version 2.0, we decided to move the project to the <a href="http://viciproject.com" target="_blank">Vici Project</a>, a project that bundles several open-source frameworks for .NET 2.0. The idea of the Vici Project is to provide .NET developers with a collection of lightweight libraries and frameworks, and at the same time get the community involved in the development and support of these libraries.</p>
<p>To make it easier to get the community involved, a complete system was created with the following features:</p>
<ul>
<li>Central SubVersion repository with online browsing (using WebSVN)</li>
<li>Automated build server (using JetBrains TeamCity)</li>
<li>Wiki infrastructure for maintaining documentation</li>
<li>Support forum</li>
</ul>
<p>After several months of testing all of this, the project is finally ready to go live. There is still a lot of work to be done, especially on documentation, but I think there is no point in postponing the release.</p>
<p>The first sub-project of the Vici Project to be released is <a href="http://viciproject.com/wiki/projects/mvc/home" target="_blank">Vici MVC</a>, formerly known as ProMesh.NET. Later this week, 2 other projects will be released as well: <a href="http://viciproject.com/wiki/projects/parser/home" target="_blank">Vici Parser</a> (formerly LazyParser.NET/SharpTemplate.NET) and <a href="http://viciproject.com/wiki/projects/coolstorage/home" target="_blank">Vici CoolStorage</a> (formerly CoolStorage.NET)</p>
<ul>Vici MVC 2.0 new features (compared to ProMesh.NET 1.2)</ul>
<ul>
<li>New powerful URL routing engine. Also supports &#8220;extension-less&#8221; URLs with IIS 7.0 or IIS 6.0 (with wildcard mapping or URL rewriting)</li>
<li>Support for view components (&#8220;inline&#8221; controllers with templated views)</li>
<li>Support for sub-templates with parameters</li>
<li>Support for template macros</li>
<li>Configurable template syntax</li>
<li>Full C# 2.0 expression supported in templates</li>
<li>New template language syntax (the old one is still supported)</li>
</ul>
<p>Anyone interested in contributing to the Vici Project, please let me know by posting on the <a href="http://viciproject.com/forum" target="_blank">forum</a> (or by sending me a private message on the forum. My username is <strong>activa</strong>)</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.activa.be/index.php/2009/05/vici-mvc-finally-released-as-part-of-the-vici-project/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Looking for beta testers for dStyler.com</title>
		<link>http://blog.activa.be/index.php/2008/12/looking-for-beta-testers-for-dstyler-com/</link>
		<comments>http://blog.activa.be/index.php/2008/12/looking-for-beta-testers-for-dstyler-com/#comments</comments>
		<pubDate>Tue, 16 Dec 2008 08:39:10 +0000</pubDate>
		<dc:creator>Philippe Leybaert</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[dStyler]]></category>

		<guid isPermaLink="false">http://www.blog.activa.be/PermaLink,guid,93856df5-f55c-406d-af86-ac9d02ffd07d.aspx</guid>
		<description><![CDATA[Early next year, a cool new service will go online targeted at web developers and designers. It will go by the name of dStyler.com but it&#8217;s a little hard to explain what the service will do, but I&#8217;ll start with a simple example: It turns this into this Lorem ipsum dolor sit amet, consectetur adipiscing [...]]]></description>
			<content:encoded><![CDATA[<div>
<p>Early next year, a cool new service will go online targeted at web developers and designers. It will go by the name of <a href="http://www.dstyler.com" target="_blank">dStyler.com</a> but it&#8217;s a little hard to explain what the service will do, but I&#8217;ll start with a simple example:</p>
<table border="0" cellpadding="5">
<tr>
<td align="center">It turns this</td>
<td align="center">into this</td>
</tr>
<tr>
<td>
<div style="width:194px;height:244px;border:1px solid black;background:white;padding:7px;margin:5px">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed vel arcu eget lorem dapibus molestie.</div>
</td>
<td>
<div style="width:194px;height:244px;border:0;padding:8px;margin:2px;background-image: url(http://dstyler.com/ufnqfr/204x254/bo-333/ib-fff-2/ro-5/gr-eef-b8e/gr-fff9-fff0-210x260/sh-0008-0-r3.png)">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed vel arcu eget lorem dapibus molestie.</div>
</td>
</tr>
<tr>
<td colspan="2" align="center">With just a single line of CSS</td>
</tr>
</table>
<p>What dStyler actually provides is real-time online image generation. It is a highly scalable REST-style webservice that generates images based on a custom-built URL. For example, the box on the right is generated by the following url:
<p>http://dstyler.com/ufnqfr/204&#215;254/bo-333/ib-fff-2/ro-5/gr-eef-b8e/gr-fff9-fff0-210&#215;260/sh-0008-0-r3.jpg.</p>
<p>It is in a way similar to the Google Charts API and the Google static maps API.</p>
<p>Some of the things dStyler can generate:</p>
<ul>
<li>Solid backgrounds</li>
<li>Gradients</li>
<li>Single or double borders</li>
<li>Drop shadows</li>
<li>Image embedding (useful for watermarks)</li>
<li>Special effects</li>
<li>Rounded corners</li>
<li>Slicing</li>
<li>&#8230;</li>
</ul>
<p>The online administration interface allows you to:</p>
<ul>
<li>Build images in an interactive way (to generate the URL for you)</li>
<li>Upload images to your account that can be used for generating images</li>
</ul>
<p>Best of all, dStyler.com will be a free service</p>
<p>We are currently looking for people interested in beta testing this service. So if you&#8217;re interested, contact me at beta -at- dstyler -dot- com (I know, I hate these obfuscated e-mail addresses more than anyone, but sadly enough, the world is a nasty world filled with f**king spammers)</p>
<p><img width="0" height="0" src="http://www.blog.activa.be/aggbug.ashx?id=93856df5-f55c-406d-af86-ac9d02ffd07d"/><br/><br />
<hr/>This weblog is sponsored by <a href="http://viciproject.com">The Vici Project</a>. </div>
]]></content:encoded>
			<wfw:commentRss>http://blog.activa.be/index.php/2008/12/looking-for-beta-testers-for-dstyler-com/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Simple time mocking for testing time-dependent code</title>
		<link>http://blog.activa.be/index.php/2008/11/simple-time-mocking-for-testing-time-dependent-code/</link>
		<comments>http://blog.activa.be/index.php/2008/11/simple-time-mocking-for-testing-time-dependent-code/#comments</comments>
		<pubDate>Fri, 28 Nov 2008 17:41:29 +0000</pubDate>
		<dc:creator>Philippe Leybaert</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Patterns]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Mocking]]></category>
		<category><![CDATA[Testing]]></category>

		<guid isPermaLink="false">http://www.blog.activa.be/PermaLink,guid,2be92a67-fb86-4869-89c2-11040f32b698.aspx</guid>
		<description><![CDATA[We all love unit tests (do we?). Yes we do (repeat 100 times). And we all love mocking for making life easier, but sometimes we just want to write some simple unit tests that don&#8217;t require any mocking at all, because the code you are testing is easy to test without having to resort to [...]]]></description>
			<content:encoded><![CDATA[<p>We all love unit tests (do we?). Yes we do (repeat 100 times). And we all love mocking for making life easier, but sometimes we just want to write some simple unit tests that don&#8217;t require any mocking at all, because the code you are testing is easy to test without having to resort to all those mocking tricks</p>
<p>But what if you need to test code that relies on the date or some elapsed time? Let&#8217;s say you wrote a simple caching class that automatically removes items from the cache when a certain amount of time has passed since the last access. It&#8217;s tempting to slap some Thread.Sleep() calls in there to trigger expiration of cache items, but that will slow down your unit test, and most importantly, it&#8217;s not accurate. What if you want to test some edge cases? Like, what happens when you access an item at the exact timeout period?</p>
<p>A few years ago I worked with a <a href="http://rubymatic.blogspot.com">brilliant Java architect</a> who simply said: &#8220;just mock the time!&#8221;. What he meant was that I should create a fake DateTime class which behaves like the real DateTime class with one important difference: YOU control the time, not the system clock. </p>
<p><u>How is that done?</u></p>
<p>Simply create an interface with a single getter property of type DateTime:</p>
<pre class="brush: csharp; title: ;">
public interface ITimeProvider
{
   DateTime Now { get; }
}
</pre>
<p>Then you create 2 classes that implement this interface: one that returns the real time, and one that can be used to control a &#8220;fake&#8221; time:</p>
<pre class="brush: csharp; title: ;">
public class RealTimeProvider : ITimeProvider
{
    public DateTime Now { get { return DateTime.Now; } }
}

public class MockTimeProvider : ITimeProvider
{
    private DateTime _time;

    public DateTime Now { get { return _time; } set { _time = value; } }
}
</pre>
<p>Of course the class(es) you want to test should be aware of this. For example, our cache class could look like this:</p>
<pre class="brush: csharp; title: ;">
public class Cache
{
     private ITimeProvider _time = new RealTimeProvider();

     public ITimeProvider TimeProvider { get { return _time; } set { _time = value; } }

     // ... the rest of the class implementation
}
</pre>
<p>In our class implementation, all calls to <b>DateTime.Now</b> should be replaced by <b>TimeProvider.Now</b>.</p>
<p><b>And now the fun part, faking the time in our unit tests:</b></p>
<pre class="brush: csharp; title: ;">
[Test]
public void TestCacheTimeout()
{
    ITimeProvider time = new MockTimeProvider();
    Cache cache = new Cache();

    cache.TimeProvider = time; // Tell our cache class to use our fake time

    cache.Add(&quot;A&quot; , 1); // add an item to the cache

    Assert.IsTrue(cache.Contains(&quot;A&quot;)); // check if it's added

    time.Now += TimeSpan.FromHours(1); // let one hour go by...

    Assert.IsFalse(cache.Contains(&quot;A&quot;)); // check if it was automatically removed
}
</pre>
<p>That&#8217;s pretty cool and simple, isn&#8217;t it? <b>Wouldn&#8217;t it be nice if we could do the same in real life? <img src='http://blog.activa.be/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' /> </b></p>
<p><i>Next week I&#8217;ll talk a little about unit testing multithreaded concurrency issues&#8230;</i></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.activa.be/index.php/2008/11/simple-time-mocking-for-testing-time-dependent-code/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Extracting URLs, not perfect but &#8220;good enough&#8221;</title>
		<link>http://blog.activa.be/index.php/2008/10/extracting-urls-not-perfect-but-quotgood-enoughquot/</link>
		<comments>http://blog.activa.be/index.php/2008/10/extracting-urls-not-perfect-but-quotgood-enoughquot/#comments</comments>
		<pubDate>Thu, 30 Oct 2008 17:36:30 +0000</pubDate>
		<dc:creator>Philippe Leybaert</dc:creator>
				<category><![CDATA[Patterns]]></category>
		<category><![CDATA[HTML]]></category>
		<category><![CDATA[Regex]]></category>

		<guid isPermaLink="false">http://www.blog.activa.be/PermaLink,guid,d5cda958-bd1e-430d-b34c-8ad09b4ba04f.aspx</guid>
		<description><![CDATA[Jeff Atwood (Coding Horror) wrote an interesting blog post about detecting hyperlinks in blocks of &#8220;regular&#8221; text. I was suprised by the wave of negative comments he received, mainly because Jeff tried to solve a complex problem with a &#8220;simple&#8221; regular expression. I don&#8217;t agree with these comments at all. Software developers are too obsessed [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.codinghorror.com/blog/" target="_blank">Jeff Atwood (Coding Horror)</a> wrote an <a href="http://www.codinghorror.com/blog/archives/001181.html" target="_blank">interesting blog post</a> about detecting hyperlinks in blocks of &#8220;regular&#8221; text. I was suprised by the wave of negative comments he received, mainly because Jeff tried to solve a complex problem with a &#8220;simple&#8221; regular expression. I don&#8217;t agree with these comments at all. Software developers are too obsessed with borderline cases. What&#8217;s wrong with &#8220;good enough&#8221;? What&#8217;s wrong with solving 99.99% of all possible situations? After all, what&#8217;s the worst that can happen if the algorithm is not 100% correct? You&#8217;ll see a bad hyperlink. Big deal&#8230;</p>
<p>Anyway, the thing is, as Jeff points out, URL&#8217;s can contain some pretty weird characters you wouldn&#8217;t expect, like &#8216;(&#8216;, &#8216;)&#8217; and &#8216;,&#8217;. This can become quite frustrating when trying to parse something like this:</p>
<blockquote><p><em><span style="color: #408080;">My website (at http://www.mysite.com/coolpage) is becoming very popular, especially because of traffic coming from http://www.othersite.com/coolestpage, which is a cool site I recently found.</span></em></p></blockquote>
<p>For humans, it&#8217;s pretty obvious where the hyperlinks are, but what if the links contain some of the non-standard characters I mentioned above? For example:</p>
<p><span style="color: #ff0000;">http://www.mysite.com/coolpage(nice).aspx</span> or <span style="color: #ff0000;">http://www.othersite.com/coolest,wildestpage</span>. Both of these are valid URLs.</p>
<p>If you would implement a trivial URL detector, the following URLs would be extracted from the text snippet above:</p>
<p>&#8220;<span style="color: #ff0000;">http://www.mysite.com/coolpage)</span>&#8221; and &#8220;<span style="color: #ff0000;">http://www.othersite.com/coolestpage,</span>&#8220;.</p>
<p>Note the trailing parenthesis and comma. Obviously that is not what we want. The fact is that there is no way we can extract valid URLs by following a set of fixed rules, not even for humans. We humans will &#8220;parse&#8221; the URLs by looking at the context, but that&#8217;s a pretty hard, if not impossible task for software.<br />
What we can do is use some heuristics to satisfy at least 99.99% of all cases, so I started thinking about this a little bit and came up with a solution that uses regular expressions and requires no code at all.</p>
<p>Let&#8217;s start with the basics. A URL contains 3 distinct parts, of which the last part is optional:</p>
<p>protocol://host/path</p>
<p>&#8220;host&#8221; is a hostname (or IP address), optionally followed by a port number, so this is the regex we can use for this:</p>
<blockquote><p>([a-zA-Z-:@.0-9]+)</p></blockquote>
<p>Of course, this will not validate the host name part of the URL, but that&#8217;s not really our goal now.</p>
<p>Next we should specify what the path looks like. According to the specs, the path can contain any of these characters: <span style="color: #0000a0;">letters</span>, <span style="color: #0000a0;">digits</span> and any of <span style="color: #0000a0;">-;:@&amp;=$_.+!*&#8217;,()</span></p>
<p>In this example, we will only try to match http and https, so our trivial regex would look like:</p>
<blockquote><p>\b(https|http)://([a-zA-Z-:@.0-9]+)(/[-;:@&amp;=?a-zA-Z0-9$_.+!*',()])?</p></blockquote>
<p>That will work in most cases, but it fails miserably in our text snippet example.</p>
<p>Let&#8217;s make an assumption: we assume that a URL containing parentheses always has matching parentheses, as in &#8220;<span style="color: #ff0000;">http://www.mysite.com/Some(Nice)Page</span>&#8220;. This would exclude URLs with a single parenthesis, so &#8220;<span style="color: #ff0000;">http://www.mysite.com/Some(NicePage</span>&#8221; would not be recognized as a URL. That&#8217;s a sacrifice I&#8217;m willing to make.</p>
<p>There are several ways of writing a regex like this, but a simple one is:</p>
<blockquote><p>\b(https|http)://([a-zA-Z-:@.0-9]+)(/((\([-;:@&amp;=a-zA-Z0-9$_.+!*',]*?\))|[-;:@&amp;=?a-zA-Z0-9$_.+!*',]|%\d\d)+)?</p></blockquote>
<p>Note that I also added some regex code for escaped characters (%nn). Nested parentheses will not be matched.</p>
<p>This would solve the first match in our text snippet, but not the second one with the trailing &#8216;,&#8217;. Again, we will make an assumption: let&#8217;s assume that a URL will never <strong>end</strong> with a period or a comma. I think that&#8217;s a pretty safe assumption to make (although technically it is allowed).</p>
<p>Our final regex will then look like:</p>
<blockquote><p>\b(https|http)://([a-zA-Z-:@.0-9]+)(/((\([-;:@&amp;=a-zA-Z0-9$_.+!*',]*?\))|[-;:@&amp;=?a-zA-Z0-9$_.+!*',]|%\d\d)+)?(?&lt;![,.;])</p></blockquote>
<p>This regex will match any valid URL pattern, except URLs without matching parentheses. It will also exclude URLs with a period, comma or semicolon at the end.</p>
<p>Again, it&#8217;s not a perfect solution, but I bet it will be very hard to find a real-world example where this regex would fail to extract the URL from a piece of text. The regex can still use some tweaking, but you get the picture.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.activa.be/index.php/2008/10/extracting-urls-not-perfect-but-quotgood-enoughquot/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>The problem with dogfooding. You&#8217;re never done.</title>
		<link>http://blog.activa.be/index.php/2008/10/the-problem-with-dogfooding-youre-never-done/</link>
		<comments>http://blog.activa.be/index.php/2008/10/the-problem-with-dogfooding-youre-never-done/#comments</comments>
		<pubDate>Wed, 29 Oct 2008 21:32:35 +0000</pubDate>
		<dc:creator>Philippe Leybaert</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Frameworks]]></category>
		<category><![CDATA[Open Source]]></category>
		<category><![CDATA[Vici]]></category>

		<guid isPermaLink="false">http://www.blog.activa.be/PermaLink,guid,354d322b-8ea6-4094-b212-3f59c5c4dfc8.aspx</guid>
		<description><![CDATA[Most people believe dogfooding is the perfect way of ensuring the quality of the software you&#8217;re creating. I couldn&#8217;t agree more. The only problem is that when you use your own software, you always have the feeling that it&#8217;s not quite &#8220;done&#8221;. There&#8217;s always something that you can do better, always something that can be [...]]]></description>
			<content:encoded><![CDATA[<p>Most people believe dogfooding is the perfect way of ensuring the quality of the software you&#8217;re creating. I couldn&#8217;t agree more.</p>
<p>The only problem is that when you use your own software, you always have the feeling that it&#8217;s not quite &#8220;done&#8221;. There&#8217;s always something that you can do better, always something that can be improved, always some features that you feel would be nice.</p>
<p>Especially when building a framework this can become a real problem because you never feel done. Another problem is making sure your framework maintains backwards compatibility with previous releases.</p>
<p>Well, I just mentioned this because I finally decided to freeze <a href="http://www.codeplex.com/ProMesh">version 2.0</a> of <a href="http://www.promesh.net">ProMesh.NET</a> and get it ready for release. Release candidate 3 has just been published on CodePlex</p>
<p><strong><span style="text-decoration: underline;">Thoughts on open source frameworks</span></strong></p>
<p>A few weeks ago, a fellow developer asked me why I chose to make my projects open-source. That was a pretty good question because when you look at it: compared to just building a framework for your own use, it makes life more complicated: you have to write documentation, support users, and more headaches.</p>
<p>I didn&#8217;t have to think long before I could answer that question: releasing a custom framework as open source forces you to be disciplined about your code and documentation. After all, you can&#8217;t afford to write code you are ashamed of, can you? If you write software for your own use, you tend to write code that&#8230; well&#8230; sucks.</p>
<p>And of course, let&#8217;s not forget the whole point of open source software: letting other developers contribute. It creates a dynamic that you would never get when you&#8217;re just building and using your own little framework</p>
<p>If all of the above sounds like a bunch of crap, it&#8217;s probably because I&#8217;m not a native English speaker, or &#8230; it <strong>is</strong> just crap</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.activa.be/index.php/2008/10/the-problem-with-dogfooding-youre-never-done/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>What&#8217;s with the BOM in Visual Studio?</title>
		<link>http://blog.activa.be/index.php/2008/09/whats-with-the-bom-in-visual-studio/</link>
		<comments>http://blog.activa.be/index.php/2008/09/whats-with-the-bom-in-visual-studio/#comments</comments>
		<pubDate>Thu, 25 Sep 2008 19:27:45 +0000</pubDate>
		<dc:creator>Philippe Leybaert</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[BOM]]></category>
		<category><![CDATA[Visual Studio]]></category>

		<guid isPermaLink="false">http://www.blog.activa.be/PermaLink,guid,46ec57c0-3d43-4f27-ac1d-e8e566dee45a.aspx</guid>
		<description><![CDATA[A few days ago, I stumbled upon a problem that I never really noticed before Google Chrome was released. It seems that Google Chrome chokes on embedded javascript if some weird bytes are present in the HTML. It took a while to figure out what was going on. It seems the weird bytes were the [...]]]></description>
			<content:encoded><![CDATA[<p>A few days ago, I stumbled upon a problem that I never really noticed before <a href="http://www.google.com/chrome" target="_blank">Google Chrome</a> was released. It seems that <a href="http://www.google.com/chrome" target="_blank">Google Chrome</a> chokes on embedded javascript if some weird bytes are present in the HTML.</p>
<p>It took a while to figure out what was going on. It seems the weird bytes were the <a href="http://en.wikipedia.org/wiki/Byte-order_mark" target="_blank">byte order mark</a> for UTF-8 documents (hex EF BB BF). When Google Chrome finds these bytes within a &lt;script&gt; block, it will simply stop parsing javascript. No errors, no warnings.</p>
<p>You can argue that this is a problem with Google Chrome, but that still doesn&#8217;t explain why these bytes were in my javascript blocks to start with.</p>
<p>The problem is this: I inject javascript in the HTML output from embedded resources. The embedded resources are just .js files created in Visual Studio, marked as &#8220;embedded resource&#8221;. The resource is then read from the assembly and converted to a UTF8 string and inserted in the HTML script block. The problem is that Visual Studio ALWAYS adds the UTF-8 &#8220;byte order mark&#8221; when you save a text file. These bytes are also embedded in the embedded resource, which is&#8230; annoying.</p>
<p>Of course, you could tell Visual Studio to save your file without signature (&#8220;byte order mark&#8221;), but you have to do that EVERY time you&#8217;ve created a new javascript file. There&#8217;s no way to make that the default.</p>
<p>Bummer&#8230;</p>
<p>On a positive note, this gives me the perfect excuse to announce the release of <a href="http://www.codeplex.com/ProMesh/Release/ProjectReleases.aspx" target="_blank">Release Candidate 2</a> of <a href="http://www.promesh.net" target="_blank">ProMesh.NET</a> 2.0, which has built-in detection for BOM bytes on embedded resources <img src='http://blog.activa.be/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://blog.activa.be/index.php/2008/09/whats-with-the-bom-in-visual-studio/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>ProMesh.NET v2.0 RC1 is out</title>
		<link>http://blog.activa.be/index.php/2008/08/promesh-net-v2-0-rc1-is-out/</link>
		<comments>http://blog.activa.be/index.php/2008/08/promesh-net-v2-0-rc1-is-out/#comments</comments>
		<pubDate>Fri, 29 Aug 2008 20:55:08 +0000</pubDate>
		<dc:creator>Philippe Leybaert</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Frameworks]]></category>
		<category><![CDATA[MVC]]></category>
		<category><![CDATA[Vici]]></category>

		<guid isPermaLink="false">http://www.blog.activa.be/PermaLink,guid,b5a4cc0b-ac03-4d7f-90f7-a5808b17f4d1.aspx</guid>
		<description><![CDATA[What&#8217;s the hardest part of creating any open-source project? No, not writing the code. No, not helping users in the support forum&#8230; I&#8217;ll tell you: writing documentation, especially when the documentation is not in your native language. So that&#8217;s what I have been doing for the last few weeks (or should I say &#8220;months&#8221;?). In [...]]]></description>
			<content:encoded><![CDATA[<p><em><a href="http://www.promesh.net" target="_blank"><img style="margin: 0px 0px 0px 5px; border: 0px;" src="http://www.blog.activa.be/content/binary/WindowsLiveWriter/ProMesh.NETv2.0RC1isout_1423F/pmcap_3.jpg" border="0" alt="pmcap" width="356" height="318" align="right" /></a></em><span style="color: #0000ff;">What&#8217;s the hardest part of creating any open-source project?</span></p>
<p><em>No, not writing the code.</em></p>
<p><em>No, not helping users in the support forum&#8230;</em></p>
<p>I&#8217;ll tell you: <strong><em>writing documentation</em></strong>, especially when the documentation is not in your native language. So that&#8217;s what I have been doing for the last few weeks (or should I say &#8220;months&#8221;?).</p>
<p>In fact, the documentation project was the only thing that held back the release of ProMesh.NET version 2.0, and today <strong>I am proud to announce the release of the first release candidate of ProMesh.NET 2.0</strong>, with full documentation online. The documentation still needs a lot work, but at least (almost) all the features of the framework have been documented.</p>
<p>So, what&#8217;s new in ProMesh.NET 2.0 (RC1) ?</p>
<ul>
<li>Built-in routing engine. Routing can be added at runtime (at application startup), or can be specified using attributes on the controller classes and action methods.</li>
<li>Support for calling/rendering view components from templates. View components are special controllers that render a view, which will be inserted in the calling view.</li>
<li>Support for any page extension, including none at all (recommended for IIS 7 deployment)</li>
<li>New template engine (SharpTemplate.NET) which supports full C# expressions in view logic</li>
<li>Ajax validation of forms</li>
<li>Performance improvements</li>
</ul>
<p>Want to check it out? Why don&#8217;t you start where all the new stuff is: <a href="http://www.promesh.net" target="_blank"><span style="text-decoration: underline;">The Official ProMesh.NET Website</span></a></p>
<p>Or if you want to go straight to the download: <a href="http://www.codeplex.com/ProMesh/Release/ProjectReleases.aspx" target="_blank"><span style="text-decoration: underline;">Go to CodePlex</span></a></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.activa.be/index.php/2008/08/promesh-net-v2-0-rc1-is-out/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Why is Windows Mobile so slow?</title>
		<link>http://blog.activa.be/index.php/2008/08/why-is-windows-mobile-so-slow/</link>
		<comments>http://blog.activa.be/index.php/2008/08/why-is-windows-mobile-so-slow/#comments</comments>
		<pubDate>Thu, 21 Aug 2008 20:37:56 +0000</pubDate>
		<dc:creator>Philippe Leybaert</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[iPhone]]></category>
		<category><![CDATA[Mobile]]></category>

		<guid isPermaLink="false">http://www.blog.activa.be/PermaLink,guid,049f0513-5e29-4716-a815-296d7c97b681.aspx</guid>
		<description><![CDATA[I&#8217;m a SmartPhone addict, I admit. At the same time, I am very picky about the requirements of a smartphone: 3G (HSDPA) Support for push e-mail (MS Exchange Server) Web browsing (even if it&#8217;s flaky) Small form factor Looking at the list, I may not be that picky after all. Feature number 2 however forces [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;m a SmartPhone addict, I admit. At the same time, I am very picky about the requirements of a smartphone:</p>
<ol>
<li>3G (HSDPA)</li>
<li>Support for push e-mail (MS Exchange Server)</li>
<li>Web browsing (even if it&#8217;s flaky)</li>
<li>Small form factor</li>
</ol>
<p>Looking at the list, I may not be that picky after all. Feature number 2 however forces me to use Windows Mobile, and to be honest, I never think twice about that when deciding on a smartphone purchase. So these were my latest phones (in order of purchase)</p>
<ul>
<li>HTC MteoR (WM 5.0)</li>
<li><a href="http://www.htc.com/europe/product.aspx?id=15768" target="_blank">HTC S730</a> (WM 6.0)</li>
<li><a href="http://www.htc.com/europe/product.aspx?id=46638" target="_blank">HTC Touch Diamond</a> (WM 6.1) &#8211; my current phone</li>
</ul>
<p>What do these have in common? Of course, they&#8217;re all HTC, but most importantly they&#8217;re all Windows Mobile devices.</p>
<p>You would think progress means that every generation of a technology improves on features, power and responsiveness, but once you mix in products made by some huge company from Redmond, this universal law no longer applies.</p>
<p>Of the smartphones listed above, the fastest one was the MteoR, followed by the S730 and &#8230; well, I almost threw the damn thing into a concrete wall several times since I bought the Diamond 2 months ago.</p>
<p><strong>What the hell is wrong with Windows Mobile?</strong> Why, after so many years of development, after so many releases can&#8217;t they get their act together and create a user interface that does something within, like, <em>2 seconds</em> of acting upon it. Tapping something on the screen has become an act of blind faith because there&#8217;s no immediate feedback. You just hope something is going to happen, and when you&#8217;re in a hurry (you always are, otherwise you wouldn&#8217;t need a smartphone), you tap again, only to find out that the &#8220;system&#8221; was already processing your first tap and sending your second tap to the button or link that will be in that same spot on the next screen within 5 seconds or so. If you&#8217;re lucky, that button will delete an important file or hang up on an important client. Thank you so much, mighty Microsoft.</p>
<p>How does Microsoft expect to win the battle against Apple or Google (Android) in the smartphone world? If they even can&#8217;t get the basic stuff right. Don&#8217;t tell me it can&#8217;t be done on small devices. Apple did it, and from what I&#8217;ve seen so far, Google did it.</p>
<p>One small piece of advice for the Windows Mobile developers: focus on the immediate feedback of the user interface, NOT on features. Rewrite all the user interface handling from scratch, put the user interface code in a dedicated area of memory that can&#8217;t be &#8220;virtualized&#8221; (is there such a thing in Windows Mobile?) and get your act together.</p>
<p>My <a href="http://www.apple.com/iphone/" target="_blank">iPhone 3G</a> will arrive tomorrow. Amen. (thank you <a href="http://www.apple.com" target="_blank">Apple</a> for licensing MS Exchange for the iPhone 3G)</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.activa.be/index.php/2008/08/why-is-windows-mobile-so-slow/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>ProMesh.NET v2.0 just around the corner</title>
		<link>http://blog.activa.be/index.php/2008/08/promesh-net-v2-0-just-around-the-corner/</link>
		<comments>http://blog.activa.be/index.php/2008/08/promesh-net-v2-0-just-around-the-corner/#comments</comments>
		<pubDate>Fri, 15 Aug 2008 17:47:05 +0000</pubDate>
		<dc:creator>Philippe Leybaert</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[MVC]]></category>
		<category><![CDATA[Open Source]]></category>
		<category><![CDATA[Vici]]></category>

		<guid isPermaLink="false">http://www.blog.activa.be/PermaLink,guid,970ba386-0e5e-4d72-897d-5a3fecbe1845.aspx</guid>
		<description><![CDATA[Time for an update on the state of ProMesh.NET, the open-source MVC Web Application framework I started a few years ago. The last public release was almost 7 months ago, and a lot has been changed since then. The original plan was to create a version 1.5, but I decided against that and made it [...]]]></description>
			<content:encoded><![CDATA[<p>Time for an update on the state of <a href="http://www.codeplex.com/ProMesh" target="_blank">ProMesh.NET</a>, the open-source MVC Web Application framework I started a few years ago. The last public release was almost 7 months ago, and a lot has been changed since then. The original plan was to create a version 1.5, but I decided against that and made it in a full 2.0 release, for several reasons:</p>
<ul>
<li>The framework has a lot of new features, like a built-in routing engine similar to ASP.NET MVC and support for view components</li>
<li>Some small changes are required to existing application using ProMesh.NET v1.2</li>
</ul>
<p>At the same time of the release (late August, early September), the <strong>full documentation</strong> will be available on a dedicated website about ProMesh.NET.</p>
<p>A quick overview of the most important features in version 2.0:</p>
<ul>
<li>URL routing engine similar to ASP.NET MVC</li>
<li>Support for view components (combination of code+templates callable from templates)</li>
<li>Configurable template language syntax</li>
<li>Full C# expression parser available in the template language</li>
<li>New template language syntax (but the old one is still supported)</li>
<li>Support for extension-less URLs</li>
</ul>
<p>Watch this space for the release announcement in a few weeks!</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.activa.be/index.php/2008/08/promesh-net-v2-0-just-around-the-corner/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>CoolStorage.NET 1.2.0 released</title>
		<link>http://blog.activa.be/index.php/2008/05/coolstorage-net-1-2-0-released/</link>
		<comments>http://blog.activa.be/index.php/2008/05/coolstorage-net-1-2-0-released/#comments</comments>
		<pubDate>Thu, 29 May 2008 21:28:58 +0000</pubDate>
		<dc:creator>Philippe Leybaert</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Frameworks]]></category>
		<category><![CDATA[Vici Project]]></category>
		<category><![CDATA[CoolStorage]]></category>
		<category><![CDATA[Open Source]]></category>
		<category><![CDATA[Vici]]></category>

		<guid isPermaLink="false">http://www.blog.activa.be/PermaLink,guid,0bb5405a-ddc3-4f45-ac87-5ef35042cd23.aspx</guid>
		<description><![CDATA[It has been almost one year since the last public release of CoolStorage.NET (&#8220;cool&#8221; open-source object mapper for .NET 2.0), but this doesn&#8217;t mean the product was dead. A lot of people regularly downloaded the latest builds from CodePlex and I received a lot of great feedback, which finally lead to the release of version [...]]]></description>
			<content:encoded><![CDATA[<p>It has been almost one year since the last public release of <a href="http://www.codeplex.com/CoolStorage" target="_blank">CoolStorage.NET</a> (&#8220;cool&#8221; open-source object mapper for .NET 2.0), but this doesn&#8217;t mean the product was dead. A lot of people regularly downloaded the latest builds from CodePlex and I received a lot of great feedback, which finally lead to the release of version 1.2.</p>
<p>Besides a bunch of bug fixes and performance improvements, the new features in this release are:</p>
<ul>
<li>Support for prefetching of many-to-one, one-to-one and one-to-many relations (marked by the [Prefetch] attribute at compile-time or by using the .WithPrefetch() method). This change results in a spectacular performance improvement in most cases where lists of objects with related objects are retrieved from the database.</li>
<li>Support for paging at server level. Use the Range() method on the CSList class to get a specific range of records</li>
<li>Support for GUID fields (server-generated and client-generated)</li>
<li>Support for specifying a context when calling generic CSDatabase.RunQuery() methods</li>
<li>New method ToList&lt;T&gt; on CSList</li>
<li>New method ThenBy() on CSList (in line with the LINQ methods)</li>
<li>New attribute [ClientGenerated] for GUID fields</li>
<li>New attribute [NotMapped] for fields that are not mapped to a database column</li>
<li>Support for VistaDB 3.x database</li>
</ul>
<p>Databases currently supported are:</p>
<ul>
<li>MS SQL Server 2000/2005</li>
<li>MS Access</li>
<li>SQLite v3</li>
<li>VistaDB 3.x</li>
<li>MySql 5.x</li>
<li>IBM DB2</li>
</ul>
<p>The latest release can be <a href="http://www.codeplex.com/CoolStorage" target="_blank">downloaded from CodePlex</a>.</p>
<p><strong><em><span style="color: #0000ff;">In case you have no idea what CoolStorage.NET is:</span></em></strong></p>
<p><strong>CoolStorage.NET</strong> is a fully typed Object Relational Mapping library for .NET 2.0.</p>
<p>The main strength of CoolStorage.NET is the ease of use. Most ORM tools still require a lot of type casting and other plumbing to be written, CoolStorage.NET is designed to relieve the programmer from these tedious and error-prone tasks, making it very intuitive to use. It is &#8220;session-less&#8221;, meaning you don&#8217;t have to keep a connection or session object lying around to access objects in the database.</p>
<p>The main features are:</p>
<ul>
<li>Supports SQL Server 2000/2005, MySQL, IBM DB2, SQLite, MS Access, VistaDB</li>
<li>Any existing relational data model can be mapped to CoolStorage objects with minimal effort</li>
<li>All relation types are supported: One-To-One, One-To-Many, Many-To-One and Many-To-Many</li>
<li>Completely typed object model (no type casts required)</li>
<li>Full support for transactions, including .NET 2.0 TransactionScope</li>
<li>Nullable columns can be mapped to .NET 2.0 nullable fields or any other value</li>
<li>Delayed (lazy) loading of data to minimize database access</li>
<li>Selective pre-fetching of all relation types for improved query performance.</li>
<li>Powerful and intuitive database-independent object query language</li>
<li>Flexible event framework to intercept any event</li>
<li>Identity (auto-increment) keys are supported for all database types</li>
<li>Support for server and client generated Guid keys</li>
<li>Sessionless data access</li>
<li>Objects can be mapped to different databases, even across object relations</li>
<li>Pageable object collections</li>
<li>Extensive support for retrieving aggregate values on collections (count, sum, average, &#8230;)</li>
<li>Collections implement IBindingList so they can be used by controls (grids) as a data source</li>
<li>Underlying database engine uses optimized and parameterized SQL queries. SQL injection is impossible</li>
<li>Built specifically for .NET 2.0, taking full advantage of generics and nullable variables</li>
<li>Raw SQL and/or stored procedures can be called on the underlying database without the need for a separate database connection</li>
<li>Small footprint (less than 120 KB)</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://blog.activa.be/index.php/2008/05/coolstorage-net-1-2-0-released/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>A good coding font makes a difference</title>
		<link>http://blog.activa.be/index.php/2008/05/a-good-coding-font-makes-a-difference/</link>
		<comments>http://blog.activa.be/index.php/2008/05/a-good-coding-font-makes-a-difference/#comments</comments>
		<pubDate>Mon, 26 May 2008 10:13:51 +0000</pubDate>
		<dc:creator>Philippe Leybaert</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Fonts]]></category>
		<category><![CDATA[Visual Studio]]></category>

		<guid isPermaLink="false">http://www.blog.activa.be/PermaLink,guid,b5cabf73-8f29-4788-be32-a659f03b6158.aspx</guid>
		<description><![CDATA[Am I the only one who believes a great programming font can boost your productivity and increase your coding joy? Personally, when I&#8217;m using a nice, clean font for my coding, I feel happy about my code. The code just looks better. And I don&#8217;t mean it &#8220;looks&#8221; better, but it looks better (catch my [...]]]></description>
			<content:encoded><![CDATA[<p>Am I the only one who believes a great programming font can boost your productivity and increase your <strong><em>coding joy</em></strong>?</p>
<p>Personally, when I&#8217;m using a nice, clean font for my coding, I feel happy about my code. The code just looks better. And I don&#8217;t mean it &#8220;looks&#8221; better, but it looks <span style="text-decoration: underline;">better</span> (catch my drift?)</p>
<p>I have tried a lot of fonts, and for the last few years I&#8217;ve always gone back to <a href="http://damieng.com" target="_blank">Damien Guard</a>&#8216;s excellent Envy Code R font. It is (IMHO) the perfect font for source code.</p>
<p>Today Damien released &#8220;Preview #7&#8243; of his font, which is a big step forward: the font looks almost perfect at all sizes. I really recommend it to anyone. And it&#8217;s free! (he does accept donations, which he really deserves)</p>
<p>The link to his announcement: <a href="http://damieng.com/blog/2008/05/26/envy-code-r-preview-7-coding-font-released/trackback" target="_blank">Envy Code R Preview #7 released</a></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.activa.be/index.php/2008/05/a-good-coding-font-makes-a-difference/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>The problem(s) with value types</title>
		<link>http://blog.activa.be/index.php/2008/05/the-problems-with-value-types/</link>
		<comments>http://blog.activa.be/index.php/2008/05/the-problems-with-value-types/#comments</comments>
		<pubDate>Sun, 25 May 2008 23:27:05 +0000</pubDate>
		<dc:creator>Philippe Leybaert</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Types]]></category>

		<guid isPermaLink="false">http://www.blog.activa.be/PermaLink,guid,08aad8b7-4de8-4393-81e0-57a566efa3f4.aspx</guid>
		<description><![CDATA[First some basics: in .NET there are reference types and value types. Reference types are always accessed through a reference (a pointer actually) while value types, well, are not. The .NET documentation tries to sum it up in one sentence: A data type is a value type if it holds the data within its own [...]]]></description>
			<content:encoded><![CDATA[<p>First some basics: in .NET there are reference types and value types. Reference types are always accessed through a reference (a pointer actually) while value types, well, are not.</p>
<p>The .NET documentation tries to sum it up in one sentence:</p>
<blockquote><p>A data type is a value type if it holds the data within its own memory allocation. A reference type contains a pointer to another memory location that holds the data.</p></blockquote>
<p>This means several things:</p>
<ul>
<li>You cannot set a variable of a value type to null. It&#8217;s not a pointer. <span style="text-decoration: underline;">It&#8217;s just there</span>.</li>
<li>When returning a value type from a method, a copy is made and the whole value is returned, not just a reference.</li>
<li>Creating a variable always initializes it to &#8220;something&#8221;.</li>
</ul>
<p>All primitive numeric types are value types (Int32, Double, Int64, Boolean, &#8230;), as well as DateTime, enums and structs. Examples of reference types are String, all arrays (even when they contain value types) and all classes.</p>
<p>So far nothing new, but to make it interesting, let&#8217;s create a small sample application using a custom struct, which is a value type:</p>
<p><span style="text-decoration: underline;">Struct declaration</span>:</p>
<pre class="brush: csharp; title: ;">
struct MyStruct
{
  public int Value = 0;

  public void Update(int i) { Value = i; }
}
</pre>
<p><span style="text-decoration: underline;">Code sample:</span></p>
<pre class="brush: csharp; title: ;">
MyStruct[] list = new MyStruct[5];

for (int i=0;i&amp;lt;5;i++)
  Console.Write(list[i].Value + &quot; &quot;);

Console.WriteLine();

for (int i=0;i&amp;lt;5;i++)
  list[i].Update(i+1);

for (int i=0;i&amp;lt;5;i++)
  Console.Write(list[i].Value + &quot; &quot;);

Console.WriteLine();
</pre>
<p>The output of this code is:</p>
<pre>
0 0 0 0 0
1 2 3 4 5
</pre>
<p>Now let&#8217;s do the same, but substitute the array for a generic List&lt;&gt;:</p>
<pre class="brush: csharp; title: ;">
List&lt;MyStruct&gt; list = new List&lt;MyStruct&gt;(new MyStruct[5]); 

for (int i=0;i&amp;lt;5;i++)
  Console.Write(list[i].Value + &quot; &quot;);

Console.WriteLine();

for (int i=0;i&amp;lt;5;i++)
  list[i].Update(i+1);

for (int i=0;i&amp;lt;5;i++)
  Console.Write(list[i].Value + &quot; &quot;);

Console.WriteLine();
</pre>
<p>The output is:</p>
<pre>
0 0 0 0 0
0 0 0 0 0
</pre>
<p>Surprised? I was too, at first, but the explanation is very simple. No, it&#8217;s not boxing/unboxing&#8230;</p>
<p>When accessing elements from an array, the runtime will get the array elements directly, so the Update() method works on the array item itself. This means that the structs itself in the array are updated.</p>
<p>In the second example, we used a generic List&lt;&gt;. What happens when we access a specific element? Well, the indexer property is called, which is a method. As I mentioned earlier, value types are copied when they are returned by a method, so this is exactly what happens: the list&#8217;s indexer method retrieves the struct from an internal array and returns it to the caller. Because it concerns a value type, a copy will be made, and the Update() method will be called on the copy, which of course has no effect on the list&#8217;s original items.</p>
<p>What should we learn from this?</p>
<p><strong><span style="color: #ff0000;">Always make sure your structs are <span style="text-decoration: underline;">immutable</span></span></strong>, because you are never sure when a copy will be made. Most of the time it is obvious, but in some cases it can really surprise you&#8230;</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.activa.be/index.php/2008/05/the-problems-with-value-types/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

