<?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>Santiago Palladino</title>
	<atom:link href="http://weblogs.manas.com.ar/spalladino/feed/" rel="self" type="application/rss+xml" />
	<link>http://weblogs.manas.com.ar/spalladino</link>
	<description>Another spot on the blogosphere</description>
	<lastBuildDate>Thu, 22 Jul 2010 19:09:31 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0</generator>
		<item>
		<title>Partitioned Graph Coloring</title>
		<link>http://weblogs.manas.com.ar/spalladino/2010/07/22/partitioned-graph-coloring/</link>
		<comments>http://weblogs.manas.com.ar/spalladino/2010/07/22/partitioned-graph-coloring/#comments</comments>
		<pubDate>Thu, 22 Jul 2010 19:09:31 +0000</pubDate>
		<dc:creator>spalladino</dc:creator>
				<category><![CDATA[Graph coloring]]></category>

		<guid isPermaLink="false">http://weblogs.manas.com.ar/spalladino/?p=217</guid>
		<description><![CDATA[Before going into how to solve the partitioned graph coloring problem using integer linear programming (which is the goal of my thesis), I thought it would be a good idea to actually explain what is the partitioned graph coloring problem (or PCP from now on). Graphs and partitions First of all, graphs. Formally, a graph [...]]]></description>
			<content:encoded><![CDATA[<p>Before going into how to solve the partitioned graph coloring problem using integer linear programming (which is the goal of <a href="http://weblogs.manas.com.ar/spalladino/2010/06/30/making-a-thesis-2-0/">my thesis</a>), I thought it would be a good idea to actually explain <em>what</em> is the partitioned graph coloring problem (or PCP from now on).</p>
<h3>Graphs and partitions</h3>
<p>First of all, graphs. Formally, a graph is defined as two sets: a set of nodes which compose the graph, and a set of edges between pairs of nodes. For example, the definition for the so-called <em>diamond graph</em> is the following:</p>
<p><img src="http://weblogs.manas.com.ar/spalladino/wp-content/cache/tex_49deb4393e02e9f10a8480188a9cb730.png" align="absmiddle" class="tex" alt=" G = V,E = \{1,2,3,4\}, \{ (1,2),(2,3),(3,4),(4,1),(1,3) \} " /></p>
<p>And a representation for it could be the following:<br />
<br />
<a href="http://weblogs.manas.com.ar/spalladino/files/2010/07/Picture-2.png"><img src="http://weblogs.manas.com.ar/spalladino/files/2010/07/Picture-2.png" alt="Diamond graph" width="96" height="86" class="aligncenter size-full wp-image-221" /></a></p>
<p>While this is the simplest form of a graph, several additions can be made: weights or attributes can be assigned to either nodes or edges; edges can be directed; multiple edges can be allowed between pairs of nodes; etc. The modification we will be dealing with in this scenario is <em>partitioning</em> the graph&#8217;s nodes. As such, the graph is now defined as three sets: besides the nodes and edges, the set of partitions, where each partition is a non-empty set of nodes such that every node belongs to exactly one partition.</p>
<p>A possible partitioning of the diamond graph previously presented could be the following:<br />
<img src="http://weblogs.manas.com.ar/spalladino/wp-content/cache/tex_d5ca7fae539d5bbe8e1be150acdc1c11.png" align="absmiddle" class="tex" alt=" G = V,E,P = \{1,2,3,4\}, \{ (1,2),(2,3),(3,4),(4,1),(1,3) \}, \{ \{1,2\}, \{3,4\} \} " /></p>
<p>
<a href="http://weblogs.manas.com.ar/spalladino/files/2010/07/Picture-3.png"><img src="http://weblogs.manas.com.ar/spalladino/files/2010/07/Picture-3.png" alt="Partitioned diamond graph" width="145" height="80" class="aligncenter size-full wp-image-224" /></a></p>
<h3>Coloring</h3>
<p>Having defined the kind of graphs we will be working with, it&#8217;s time to define the problem itself. The graph coloring problem consists in defining a function that assigns a label (a &#8220;color&#8221;) to each node in the graph, with the restriction that every pair of adjacent nodes must have different colors.</p>
<p>For example, a valid coloring for the diamond graph presented earlier would be the following:</p>
<p>
<a href="http://weblogs.manas.com.ar/spalladino/files/2010/07/Picture-1.png"><img src="http://weblogs.manas.com.ar/spalladino/files/2010/07/Picture-1.png" alt="Colored diamond graph" width="92" height="86" class="aligncenter size-full wp-image-229" /></a></p>
<p>The goal here is to find a valid coloring that uses the minimum possible number of different colors. This value is called the <em>chromatic number</em> of a graph. </p>
<p>Determining if there is a valid <strong>k</strong>-coloring (coloring that uses exactly <strong>k</strong> colors) for a particular graph is usually difficult to determine, where difficult implies that it requires a huge computational effort; for those of you with background on CS, this problem is known to be NP-complete. </p>
<p>For .NET fans, it is worth <a href="http://blogs.msdn.com/b/ericlippert/archive/2010/07/12/graph-colouring-with-simple-backtracking-part-one.aspx">checking</a> <a href="http://blogs.msdn.com/b/ericlippert/archive/2010/07/15/graph-colouring-with-simple-backtracking-part-two.aspx">the</a> <a href="http://blogs.msdn.com/b/ericlippert/archive/2010/07/22/graph-colouring-with-simple-backtracking-part-three.aspx">posts</a> that Eric Lippert has been uploading recently on making a backtracking algorithm for the coloring problem using C#. </p>
<h3>Partitioned Coloring</h3>
<p>The coloring problem has several variants. For example, it might be of interest to minimize the not only the number of different colors used, but also the difference between how many nodes are painted with each color. Or allow that adjacent nodes have the same color, incurring in a penalty in an objective function, if it allows the usage of fewer colors.</p>
<p>In this case, the partitioned graph coloring consists in coloring one node per partition, with the restriction that two adjacent nodes may not have the same color. The difference with the standard coloring is that not all nodes must be colored, only one in each partition.</p>
<p>Going back to our diamond example, by cleverly picking which nodes to color in each partition, we can partition-color the whole graph using a single color:</p>
<p>
  <a href="http://weblogs.manas.com.ar/spalladino/files/2010/07/Picture-5.png"><img src="http://weblogs.manas.com.ar/spalladino/files/2010/07/Picture-5.png" alt="Coloring of partitioned diamond" width="145" height="80" class="aligncenter size-full wp-image-231" /></a></p>
<p>Even though not all nodes are to be colored, this variant of the problem is still computationally difficult (NP-complete) to solve. Most approaches to it are heuristic, this is, they do not find the optimal solution, but offer a reasonable one in a reasonable time, as all algorithms that guarantee finding the best solution take too long to execute for large graphs.</p>
<p>Our goal will be to use a technique called integer linear programming to solve this problem, obtaining the exact solution in a reasonable time, for medium-sized instances.</p>
]]></content:encoded>
			<wfw:commentRss>http://weblogs.manas.com.ar/spalladino/2010/07/22/partitioned-graph-coloring/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>What is Linear Programming</title>
		<link>http://weblogs.manas.com.ar/spalladino/2010/07/06/what-is-linear-programming/</link>
		<comments>http://weblogs.manas.com.ar/spalladino/2010/07/06/what-is-linear-programming/#comments</comments>
		<pubDate>Tue, 06 Jul 2010 18:52:57 +0000</pubDate>
		<dc:creator>spalladino</dc:creator>
				<category><![CDATA[Linear Programming]]></category>
		<category><![CDATA[Research]]></category>

		<guid isPermaLink="false">http://weblogs.manas.com.ar/spalladino/?p=193</guid>
		<description><![CDATA[Despite being able to simply provide a link to wikipedia&#8217;s already excellent article on Linear Programming, I wanted to provide a short introduction in order to present what I am doing exactly on my thesis in a future article. Linear Programming is best described as a technique, in which we want to maximize or minimize [...]]]></description>
			<content:encoded><![CDATA[<p>Despite being able to simply provide a link to wikipedia&#8217;s already <a href="http://en.wikipedia.org/wiki/Linear_programming">excellent article on Linear Programming</a>, I wanted to provide a short introduction in order to present what I am doing exactly on <a href="http://weblogs.manas.com.ar/spalladino/2010/06/30/making-a-thesis-2-0/">my thesis</a> in a future article.</p>
<p>Linear Programming is best described as a technique, in which we want to maximize or minimize an objective function subject to a set of constraints. It is called linear because both the objective function and the constraints are linear inequalities on the variables.</p>
<p>And just to make sure that no one is left behind: a linear function on a set of variables <img src="http://weblogs.manas.com.ar/spalladino/wp-content/cache/tex_1b9db4b01a27be1df822c286d143ce51.png" align="absmiddle" class="tex" alt="x_1, x_2, \ldots, x_n" /> is a function <img src="http://weblogs.manas.com.ar/spalladino/wp-content/cache/tex_0ab02f6433bdde74d3e80cb1a2bb0e62.png" align="absmiddle" class="tex" alt="a_0 + a_1 x_1 + a_2 x_2 + \ldots + a_n x_n" />, where <img src="http://weblogs.manas.com.ar/spalladino/wp-content/cache/tex_6b99601a6e28e540b506818e3bcb2703.png" align="absmiddle" class="tex" alt="a_0, a_1, a_2, \ldots, a_n" /> are numbers. For example, <img src="http://weblogs.manas.com.ar/spalladino/wp-content/cache/tex_7c34f1eb02dcef9be5ddd0349ca9128b.png" align="absmiddle" class="tex" alt="4 + 3x_1 - 2x_2" /> is a linear function, whereas <img src="http://weblogs.manas.com.ar/spalladino/wp-content/cache/tex_2f6c34c3a57465265b01efd3ade1849a.png" align="absmiddle" class="tex" alt="x_1 * x_2 / x_3" /> isn&#8217;t.</p>
<h3>Example: diet problem</h3>
<p>A classical example for linear programming is the diet problem. We want to determine a diet that satisfies all of our nutritional requirements while keeping it as cheap as possible. We have a set of different foods that fulfill certain requirements by containing a certain amount of proteins, vitamins, etc; and each food has a certain price per kilogram. Needless to say, the values in the following table are completely fictional.</p>
<table>
<tbody>
<tr>
<th>Food</th>
<th>Proteins per kg</th>
<th>Vitamins per kg</th>
<th>Carbohydrates per kg</th>
<th>Cost per kg</th>
</tr>
<tr>
<td>Apples</td>
<td>2</td>
<td>4</td>
<td>2</td>
<td>5</td>
</tr>
<tr>
<td>Beef</td>
<td>10</td>
<td>5</td>
<td>4</td>
<td>20</td>
</tr>
<tr>
<td>Cucumbers</td>
<td>4</td>
<td>3</td>
<td>3</td>
<td>6</td>
</tr>
<tr>
<td>Potatos</td>
<td>1</td>
<td>2</td>
<td>8</td>
<td>2</td>
</tr>
</tbody>
</table>
<p>Suppose also that we need at least 60 units of each nutrient in our diet. Our objective will be to find a solution that specifies how much food of each type we should buy to cover all of our needs while keeping budget to a minimum.</p>
<p>In order to create a linear programming model, we must first define which variables we will be working with. We will define <img src="http://weblogs.manas.com.ar/spalladino/wp-content/cache/tex_1ba8aaab47179b3d3e24b0ccea9f4e30.png" align="absmiddle" class="tex" alt="x_i" /> as how many kg of food <img src="http://weblogs.manas.com.ar/spalladino/wp-content/cache/tex_865c0c0b4ab0e063e5caa3387c1a8741.png" align="absmiddle" class="tex" alt="i" /> we will be purchasing; therefore, our variables will be <img src="http://weblogs.manas.com.ar/spalladino/wp-content/cache/tex_984d5eac45a79d0ca6f993c7c7e74074.png" align="absmiddle" class="tex" alt="x_A, x_B, x_C, x_P" />.</p>
<p>Now we must specify our restrictions. We want to consume at least 60 units of each nutrient, and each food provides a certain amount per kg of it. For instance, we may express that we need 60 units of carbs as:</p>
<p><center><img src="http://weblogs.manas.com.ar/spalladino/wp-content/cache/tex_c370aa7e35919f3e34df26459e932428.png" align="absmiddle" class="tex" alt=" 2 x_A + 4 x_B + 3 x_C + 8 x_P \geq 60" /></center></p>
<p>Note that each unit of apples provides 2 units of carbs, therefore the total amount of carbs provided by apples will be the product <img src="http://weblogs.manas.com.ar/spalladino/wp-content/cache/tex_8c8acdb8bd3ab2bf7fd45eabdb1b649a.png" align="absmiddle" class="tex" alt="2 \times x_A" />; same holds for all foods.</p>
<p>Similar expressions can be derived for vitamins:</p>
<p><center><img src="http://weblogs.manas.com.ar/spalladino/wp-content/cache/tex_8e7de61f1ade6e5f69324b16eb833c41.png" align="absmiddle" class="tex" alt=" 4 x_A + 5 x_B + 3 x_C + 2 x_P \geq 60" /></center></p>
<p>And for proteins:</p>
<p><center><img src="http://weblogs.manas.com.ar/spalladino/wp-content/cache/tex_1ff38776b8b990fa155b8fce16ccf433.png" align="absmiddle" class="tex" alt=" 2 x_A + 10 x_B + 4 x_C + 1 x_P \geq 60" /></center></p>
<p>Needless to say, all amounts must be positive, as we are buying food, not selling it. Therefore, we add constraints:</p>
<p><center><img src="http://weblogs.manas.com.ar/spalladino/wp-content/cache/tex_09ed64863f9bf3a7d6dc36c900442498.png" align="absmiddle" class="tex" alt=" x_A, x_B, x_C, x_P \geq 0 " /></center></p>
<p>The set of constraints we have built specify a set of valid or feasible solutions for us. For example, we will not accept a solution in which we purchase only 20kg of apples, since although that satisfies our vitamin intake, it does not satisfy carbs and proteins.</p>
<p>What we have to do now is, from every feasible solution, choose one that minimizes how much money we spend. So far, nothing prevents buying a whole supermarket of food from being a valid solution, albeit a very expensive one. In order to prevent that situation, we add an objective function to minimize, which is the cost of all the food we want to buy:</p>
<p><center><img src="http://weblogs.manas.com.ar/spalladino/wp-content/cache/tex_04a9971af10587a2cc44ba290bdfb79e.png" align="absmiddle" class="tex" alt=" c(x) =  5 x_A + 20 x_B + 6 x_C + 2 x_P  " /></center></p>
<p>The purpose of the objective function is to <em>measure</em> how good or bad a particular solution is, whereas the constraints restrict what we consider a valid solution for us. Putting all of them together, we have constructed a linear programming model for our diet problem.</p>
<h3>Generalizing</h3>
<p>A linear programming problem consists in the minimization of a linear objective function <img src="http://weblogs.manas.com.ar/spalladino/wp-content/cache/tex_8c837b189144aeb71b9f29ec07d9c553.png" align="absmiddle" class="tex" alt="c(x)" /> subject to a set of linear constraints, which can be expressed as <img src="http://weblogs.manas.com.ar/spalladino/wp-content/cache/tex_b85b5ed2813905b29040daddbeb9452b.png" align="absmiddle" class="tex" alt="Ax \geq b" />, where <img src="http://weblogs.manas.com.ar/spalladino/wp-content/cache/tex_7fc56270e7a70fa81a5935b72eacbe29.png" align="absmiddle" class="tex" alt="A" /> is a matrix in which element <img src="http://weblogs.manas.com.ar/spalladino/wp-content/cache/tex_9a59294d35ec9247478796ffb89359eb.png" align="absmiddle" class="tex" alt="a_{ij}" /> represents how much each unit of variable <img src="http://weblogs.manas.com.ar/spalladino/wp-content/cache/tex_363b122c528f54df4a0446b6bab05515.png" align="absmiddle" class="tex" alt="j" /> contributes to satisfying demand <img src="http://weblogs.manas.com.ar/spalladino/wp-content/cache/tex_fe3e01a305f27284ff5115f4c5ea0fa4.png" align="absmiddle" class="tex" alt="b_i" /> for product <img src="http://weblogs.manas.com.ar/spalladino/wp-content/cache/tex_865c0c0b4ab0e063e5caa3387c1a8741.png" align="absmiddle" class="tex" alt="i" />.</p>
<p>Note that by using simple algebraic operations we can include all kind of non-strict linear constraints: <img src="http://weblogs.manas.com.ar/spalladino/wp-content/cache/tex_15fb3d05afbf963d3175782b1fe8c35e.png" align="absmiddle" class="tex" alt="a(x) \leq \beta" />, <img src="http://weblogs.manas.com.ar/spalladino/wp-content/cache/tex_8c49e3c8aae4cdb80678dd6bd27be265.png" align="absmiddle" class="tex" alt="a(x) \geq \beta" /> and <img src="http://weblogs.manas.com.ar/spalladino/wp-content/cache/tex_9414e2c49a807495317d624d64cbf37b.png" align="absmiddle" class="tex" alt="a(x) = \beta" />. Therefore, there are different canonical ways to represent a linear programming problem, one of which is the one we have already seen:</p>
<p><center><img src="http://weblogs.manas.com.ar/spalladino/wp-content/cache/tex_929d263c3e0f81d4518d866906f0a502.png" align="absmiddle" class="tex" alt=" \min{c(x)} \quad \text{subject to } Ax \geq b" /></center></p>
<p>We may also express it as a maximization of the objective function:</p>
<p><center><img src="http://weblogs.manas.com.ar/spalladino/wp-content/cache/tex_8cbd25ad71c1e741a7a510178892998d.png" align="absmiddle" class="tex" alt=" \max{c(x)} \quad \text{subject to } Ax \leq b" /></center></p>
<p>Or either of them subject to a set of equalities:</p>
<p><center><img src="http://weblogs.manas.com.ar/spalladino/wp-content/cache/tex_38df84b8181139d323092b403ee68fea.png" align="absmiddle" class="tex" alt=" \max{c(x)} / \min{c(x)} \quad \text{subject to } Ax = b" /></center></p>
<p>In all canonical forms variables are usually restricted to be positive or zero, which makes sense in most scenarios. In a future post I would like to revisit this subject, using one of the canonical forms to go a little deeper into the economical interpretation of each of the variables and constraints. But for now, we will go straight to the resolution.</p>
<h3>Resolution</h3>
<p>We have seen how to model an optimization problem using linear programming, but we still need to know how to solve it. Luckily, there are several algorithms that deal with these specific problems, one of the most widely known is <a href="http://en.wikipedia.org/wiki/Simplex">simplex</a>.</p>
<p>How simplex works deserves another blog post of its own, but for now lets just say that it solves most models incredibly fast. The problem of solving an LPP (linear programming problem) is known to be polynomial, which means that it can be solved within an acceptable timespan.</p>
<p>Needless to say, linear programming is an invaluable tool for modeling several real life scenarios, and has multiple applications within operations research. In future posts I would like to dwelve deeper into linear programming, which I will do if I have some spare time, but for now I will go on blogging within the scope of my thesis: integer linear programming.</p>
]]></content:encoded>
			<wfw:commentRss>http://weblogs.manas.com.ar/spalladino/2010/07/06/what-is-linear-programming/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Making a thesis 2.0</title>
		<link>http://weblogs.manas.com.ar/spalladino/2010/06/30/making-a-thesis-2-0/</link>
		<comments>http://weblogs.manas.com.ar/spalladino/2010/06/30/making-a-thesis-2-0/#comments</comments>
		<pubDate>Wed, 30 Jun 2010 16:09:58 +0000</pubDate>
		<dc:creator>spalladino</dc:creator>
				<category><![CDATA[Research]]></category>
		<category><![CDATA[Thesis]]></category>

		<guid isPermaLink="false">http://weblogs.manas.com.ar/spalladino/?p=185</guid>
		<description><![CDATA[Continuing with the tradition started by Beta two years ago here in Manas, I am now dedicating all my efforts to finish my thesis in order to obtain my MSc degree in Computer Science at FCEN-UBA. Having started it a few months ago, Manas generously started sponsoring my work in May, so I can deal [...]]]></description>
			<content:encoded><![CDATA[<p>Continuing with <a href="http://weblogs.manas.com.ar/lziliani/2008/11/13/making-a-thesis/">the tradition started by Beta</a> two years ago here in Manas, I am now dedicating all my efforts to finish my thesis in order to obtain my MSc degree in <a href="http://dc.uba.ar/">Computer Science at FCEN-UBA</a>. Having started it a few months ago, Manas generously started sponsoring my work in May, so I can deal with the last steps in the project and give it the finishing touch it deserves.</p>
<p>This work gives <a href="http://www.manas.com.ar/node/12">Manas Research</a> division a very different direction than the one Beta gave it. Whereas <a href="http://weblogs.manas.com.ar/lziliani/">his work</a> was in the field of <a href="http://en.wikipedia.org/wiki/Lambda_calculus">lambda calculus</a>, my thesis is in <a href="http://en.wikipedia.org/wiki/Operations_research">operations research</a>, <a href="http://en.wikipedia.org/wiki/Integer_programming">integer linear programming</a> to be more specific, dealing with a generalization of the <a href="http://mathworld.wolfram.com/VertexColoring.html">graph coloring problem</a>.</p>
<p>During these weeks I will be blogging about linear programming in general and the scope of my thesis, but for now I will upload the <a href="http://weblogs.manas.com.ar/spalladino/files/2010/06/AlioInforms.pdf">presentation</a> I gave during the first days of June in the last <a href="http://meetings2.informs.org/BuenosAires2010/">ALIO/INFORMS joint meeting</a> that took place in Buenos Aires so you can get a preview of what has been done so far.</p>
]]></content:encoded>
			<wfw:commentRss>http://weblogs.manas.com.ar/spalladino/2010/06/30/making-a-thesis-2-0/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Deleting children with accepts_nested_attributes_for in Rails</title>
		<link>http://weblogs.manas.com.ar/spalladino/2010/03/15/deleting-children-with-accepts_nested_attributes_for-in-rails/</link>
		<comments>http://weblogs.manas.com.ar/spalladino/2010/03/15/deleting-children-with-accepts_nested_attributes_for-in-rails/#comments</comments>
		<pubDate>Mon, 15 Mar 2010 19:23:51 +0000</pubDate>
		<dc:creator>spalladino</dc:creator>
				<category><![CDATA[Rails]]></category>
		<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://weblogs.manas.com.ar/spalladino/?p=180</guid>
		<description><![CDATA[On the previous post I wrote a few lines on the basic usage of the accepts_nested_attributes_for method in rails models. I strongly recommend reading that post before this one if you haven’t. Although there is a standard way for deleting items, there is few information on how to deal with them on the model or [...]]]></description>
			<content:encoded><![CDATA[<p>On the <a href="http://weblogs.manas.com.ar/spalladino/2010/03/03/handling-children-with-accepts_nested_attributes_for-in-rails/">previous post</a> I wrote a few lines on the basic usage of the <font face="courier new">accepts_nested_attributes_for</font> method in rails models. I strongly recommend reading that post before this one if you haven’t.</p>
<p>Although there is a standard way for deleting items, there is few information on how to deal with them on the model or the controllers without messing with the unprocessed parameters. I’ll try to go over some of the different ways for deleting (or rejecting) children.</p>
<h3>Do not create at all</h3>
<p>Before actually deleting, it is important to consider the case in which you do not want to create the child in the first place. Doing this is easy and handled completely on the model: there is a very useful <font face="courier new">reject_if</font> option that allows you to specify conditions under which you do not want to process a specific child. </p>
<div class="csharpcode-wrapper">
<pre>accepts_nested_attributes_for :children
  :reject_if =<span class="str">&gt;</span> proc { |att| att['name']<span class="cls">.blank</span>? }</pre>
</div>
<p>The procedure runs for every child, if it evaluates to true, that set of parameters is ignored. Note that this is not the same as a validation: the child will be ignored simply rejected, and will not raise a validation error (children validation and parental control will be left for another post).</p>
<p>Remember that here you must predicate on the raw attributes. The class is not constructed (unless you manually do it in the procedure) so you do not have access to any model fields or instance methods.</p>
<p>This method is useful when you display a text field for the user to complete, which represents the child. If the user does not want to fill that field (<em>name</em> in the example), the child will not be created. </p>
<p>Suppose you have 5 empty text fields for the user to fill his/her hobbies. Should a user have only 3 hobbies, then you want to create only 3 instances of the Hobby class that belong_to that user.</p>
<h3>Check _delete</h3>
<p>The recommended option for deleting an item is setting a _delete parameter to true in the attributes. This is, if you have a set of parameters like the following:</p>
<div class="csharpcode-wrapper">
<pre>children_attributes =<span class="str">&gt;</span>
    1 =<span class="str">&gt;</span> { id =<span class="str">&gt;</span> 16, :name =<span class="str">&gt;</span> Jack, :_delete =<span class="str">&gt;</span> true }
    2 =<span class="str">&gt;</span> { id =<span class="str">&gt;</span> 18, :name =<span class="str">&gt;</span> Mary }</pre>
</div>
<p>Then Jack will be removed from the association to his parent. If the association has <font face="Courier New">:dependent =&gt; :destroy</font> set, Jack will be completely destroyed.</p>
<p>It is critical not to forget adding the allow_destroy option to the nested attributes method:</p>
<div class="csharpcode-wrapper">
<pre>accepts_nested_attributes_for :children,
  :reject_if =<span class="str">&gt;</span> proc { |att| att['name']<span class="cls">.blank</span>? },
  :allow_destroy =<span class="str">&gt;</span> true</pre>
</div>
<p>The rationale behind this feature is that if the user wants to delete an item, he/she must simply check a box named <font face="Courier New">_delete</font> and the controller will forward the parameter to the model, which will remove the child.</p>
<p>If you want to use a different method for deleting (in the hobbies example, delete when the user clears the textbox) you can use javascript to toggle a hidden checkbox whenever a textbox changes, for example. But this is clearly delegating model logic to the view, so a different approach is needed.</p>
<h3>Let the controller do it</h3>
<p>Since we are messing with the raw params representation of the object, the controller could simply iterate over each of the <font face="courier new">children_attributes</font> and add a <font face="courier new">_delete</font> parameter whenever needed, if a certain condition occurs.</p>
</p>
<p>However, if we had rejected the previous javascript-based solution for deleting a child since it implies keeping model logic in the view, why should we be happy by moving it to the controller? We have to move another step further.</p>
<h3>Mark for destruction</h3>
<p>No, we will not hack the <a href="http://api.rubyonrails.org/classes/ActiveRecord/Base.html#M002347">attributes=</a> method to manually walk the <font face="courier new">children_attributes</font> params and add the deletion flag. Since we are in the model, we will use the objects themselves.</p>
<p>The AutosaveAssociation class has a handy method for <a href="http://api.rubyonrails.org/classes/ActiveRecord/AutosaveAssociation.html#M002196">marking objects for removal</a> which allows you to flag certain objects that should be destroyed when the parent is saved.</p>
<p>Therefore, you can add a callback before the parent is saved that walks through the children and marks for removal those who match a certain condition. And this time, you have the actual children, not some raw-params representation:</p>
<div class="csharpcode-wrapper">
<pre>before_save :mark_children_for_removal

def mark_children_for_removal
  children<span class="cls">.each</span> do |child|
    child<span class="cls">.mark_for_destruction</span> if child<span class="cls">.name</span><span class="cls">.blank</span>?
  end
end</pre>
</div>
<p>This allows you to keep all your model logic in your model, where it belongs, and avoid messing with nested parameters in the view or the controller.</p>
]]></content:encoded>
			<wfw:commentRss>http://weblogs.manas.com.ar/spalladino/2010/03/15/deleting-children-with-accepts_nested_attributes_for-in-rails/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Handling children with accepts_nested_attributes_for in Rails</title>
		<link>http://weblogs.manas.com.ar/spalladino/2010/03/03/handling-children-with-accepts_nested_attributes_for-in-rails/</link>
		<comments>http://weblogs.manas.com.ar/spalladino/2010/03/03/handling-children-with-accepts_nested_attributes_for-in-rails/#comments</comments>
		<pubDate>Wed, 03 Mar 2010 19:44:45 +0000</pubDate>
		<dc:creator>spalladino</dc:creator>
				<category><![CDATA[Rails]]></category>
		<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://weblogs.manas.com.ar/spalladino/?p=174</guid>
		<description><![CDATA[Rails makes it easy to build HTML forms associated to a certain model. Simply using the form_for instruction on the view, writing a simple update method in the controller and setting validation logic on the model, makes standard CRUD operations incredibly easy to code. Since version 2.3, Rails also provides a convenient way of dealing [...]]]></description>
			<content:encoded><![CDATA[<p>Rails makes it easy to build HTML forms associated to a certain model. Simply using the <a href="http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html#M001604">form_for</a> instruction on the view, writing a simple update method in the controller and setting validation logic on the model, makes standard CRUD operations incredibly easy to code.</p>
<p>Since version 2.3, Rails also provides a convenient way of dealing with multi-model forms, specifically parent-children relations. Ryan has an <a href="http://ryandaigle.com/articles/2009/2/1/what-s-new-in-edge-rails-nested-attributes">excellent blog post</a> on the subject, I strongly recommend taking a look at it before going on reading if you have never used <a href="http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html#M002132">accepts_nested_attributes_for</a> or <a href="http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html#M001605">fields_for</a>.</p>
<p>To make a long story short, the accepts_nested_attributes_for method applied to a model allows you to <strong>assign values directly to the children</strong>, using the same hash format as for standard attributes.</p>
<h3>An example</h3>
<p>For example, having a Parent class which <font face="courier new">has_many children</font> of class Child, a typical POST with data for both classes would look like the following:</p>
<div class="csharpcode-wrapper">
<pre>params =<span class="str">&gt;</span>
    action =<span class="str">&gt;</span> update
    id =<span class="str">&gt;</span> 1
    controller =<span class="str">&gt;</span> parents
    parent =<span class="str">&gt;</span>
        first_name =<span class="str">&gt;</span> John
        last_name =<span class="str">&gt;</span> Doe
        age =<span class="str">&gt;</span> 40
        children_attributes =<span class="str">&gt;</span>
            1 =<span class="str">&gt;</span> { id =<span class="str">&gt;</span> 16, :name =<span class="str">&gt;</span> Jack }
            2 =<span class="str">&gt;</span> { id =<span class="str">&gt;</span> 18, :name =<span class="str">&gt;</span> Mary }</pre>
</div>
<p>(I removed several symbols from the hash to improve readability)</p>
<p>Note the <font face="Courier new">children_attributes</font> element among the parent’s attributes. The fields_for command produces the necessary syntax to produce POST data that will be converted to a hash in the convenient way for accepts_nested_attributes_for to interpret.</p>
<p>The <font face="courier new">children_attributes</font> is not an array but a hash, and its keys are a simple indexer, not the IDs of the model, which is used to group attributes from a single child entity toghether. </p>
<p>The reason for not using IDs is simple once you think about it: the model being edited might not be saved by the time it is sent to the client (therefore its id is nil), so it is a good practice to keep a hidden field with the id for each of the children being displayed.</p>
<h3>On the view</h3>
<p>Taking a look at the page source generated, we can see the naming convention rails uses to generate a hash with the previous structure:</p>
<div class="csharpcode-wrapper">
<pre>parent[children_attributes][0][name]</pre>
</div>
<p>This naming is automatically generated by opening a new context using the fields_for instruction in the view.</p>
<h3>On the model</h3>
<p>The change in the model is really simple, as it involves simply telling Rails which classes might be updated directly from the parent:</p>
<div class="csharpcode-wrapper">
<pre>accepts_nested_attributes_for :children</pre>
</div>
<p>We will look into additional options (rejecting and deleting) later.</p>
<h3>On the controller</h3>
<p>Note that all these changes only involve the view (clearly) and a single line in the model to specify which classes may be modified through the <a href="http://api.rubyonrails.org/classes/ActiveRecord/Base.html#M002347">attributes</a> accessor. <strong>The controller remains as dumb as before:</strong></p>
<div class="csharpcode-wrapper">
<pre>def update
    if @parent<span class="cls">.update_attributes</span> params[:parent]
        redirect_to :action =<span class="str">&gt;</span> 'success_page'
    else
        render :action =<span class="str">&gt;</span> 'edit'
    end
end</pre>
</div>
<p>Not even a single mention to the children, the method is untouched.</p>
<h3>After that…</h3>
<p>Once you start dealing with certain validations and callbacks, keeping in mind when are these children validated created, updated and deleted is extemely important. Deleting items is specially delicate here, and will make a good subject for the next post!</p>
]]></content:encoded>
			<wfw:commentRss>http://weblogs.manas.com.ar/spalladino/2010/03/03/handling-children-with-accepts_nested_attributes_for-in-rails/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Status Update</title>
		<link>http://weblogs.manas.com.ar/spalladino/2010/03/03/status-update/</link>
		<comments>http://weblogs.manas.com.ar/spalladino/2010/03/03/status-update/#comments</comments>
		<pubDate>Wed, 03 Mar 2010 18:53:03 +0000</pubDate>
		<dc:creator>spalladino</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://weblogs.manas.com.ar/spalladino/?p=171</guid>
		<description><![CDATA[It’s been a while since the last time I wrote something here. I realize I’ve promised several posts which never got written, such as some experiments with bizarre random number generators, the architecture of the silverlight DynamicDeepZoom app we hacked toghether with Martin for Codecamp 09, and the full code for the silverlight PagingListBox (which [...]]]></description>
			<content:encoded><![CDATA[<p>It’s been a while since the last time I wrote something here. I realize I’ve promised several posts which never got written, such as some experiments with bizarre <a href="http://weblogs.manas.com.ar/spalladino/2009/03/02/randomness/">random number generators</a>, the architecture of the silverlight <a href="http://weblogs.manas.com.ar/spalladino/2009/09/26/microsoft-codecamp-buenos-aires-2009-source-code-and-presentation/">DynamicDeepZoom app</a> we hacked toghether with <a href="http://weblogs.manas.com.ar/mverzilli">Martin</a> for Codecamp 09, and the full code for the silverlight <a href="http://weblogs.manas.com.ar/spalladino/2008/07/02/paging-in-data-bound-listbox-in-silverlight/">PagingListBox</a> (which I’m sure it must have been implemented in some toolkit out there by now).</p>
<p>However, since I’ve been working with Ruby on Rails during the last months, I would like to start going in that direction.</p>
<p>And the first post on the subject will not be eternally delayed as the other ones.</p>
]]></content:encoded>
			<wfw:commentRss>http://weblogs.manas.com.ar/spalladino/2010/03/03/status-update/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Javascript strings translation with gettext</title>
		<link>http://weblogs.manas.com.ar/spalladino/2009/11/13/javascript-strings-translation-with-gettext/</link>
		<comments>http://weblogs.manas.com.ar/spalladino/2009/11/13/javascript-strings-translation-with-gettext/#comments</comments>
		<pubDate>Fri, 13 Nov 2009 14:49:14 +0000</pubDate>
		<dc:creator>spalladino</dc:creator>
				<category><![CDATA[Gettext]]></category>
		<category><![CDATA[Web]]></category>
		<category><![CDATA[i18n]]></category>

		<guid isPermaLink="false">http://weblogs.manas.com.ar/spalladino/?p=168</guid>
		<description><![CDATA[In a previous post I mentioned a few ways of dealing with i18n of strings in ASP.NET pages with gettext. Now it’s time for javascript code. Although javascript code in ASP.NET pages can be internationalized using the &#60;%= %&#62; syntax, pure js files are not processed, and therefore a different mechanism for dealing with javascript [...]]]></description>
			<content:encoded><![CDATA[<p>In a <a href="http://weblogs.manas.com.ar/spalladino/2009/10/07/gettext-i18n-strings-in-asp-net-controls/">previous post</a> I mentioned a few ways of dealing with i18n of strings in ASP.NET pages with <a href="http://www.gnu.org/software/gettext/">gettext</a>. Now it’s time for javascript code.</p>
<p>Although javascript code in ASP.NET pages can be internationalized using the <font face="courier new">&lt;%= %&gt; </font>syntax, pure js files are not processed, and therefore a different mechanism for dealing with javascript is needed.</p>
<p>A quick google search will return multiple results. <a href="http://developer.berlios.de/projects/jsgettext/">BerliOS javascript gettext</a> implementation provides an interface with the same methods as the ones provided by any other port. It requires that the content of the translation files is available as a dictionary visible to the script.</p>
<p>Note that it is not necessary to have a full implementation of gettext client side. Having a simple function for translation, checking a simple dictionary will do:</p>
<div>
<pre>Resources.T = function(str) { <span style="color: #0000ff">return</span> Resources[str] || str };&quot;</pre>
</div>
<p>The <em>Resources</em> dictionary can be easily passed to the client via JSON, by retrieving the full dictionary on the server and encoding it. </p>
<p>An efficient approach for including this data is having a server endpoint returning this dictionary as json and including it as a referenced script in all master pages. This will cause the browser to download the full set of resources the first time and then used it cached version; therefore it is not necessary to send the full load of strings on every request. Make sure to add the culture of the requested resource to the URL, so when a user changes his/her language the new resource set is loaded.</p>
<p>As for .po generation, xgettext seems to crawl javascript code without too many issues, so this point should not pose any problems.</p>
<p>On the other hand, the <a href="http://code.google.com/p/gettext-js/source/browse/trunk/js/gettext.js">gettext-js library</a> provides client side methods for parsing .po files. Therefore, it is not necessary to add a server endpoint with the intelligence to convert the po file into its json representation: the library will take care of this by itself, just point itself to an URL containing the file to parse and voila!</p>
<p>Note, however, that since the po file may have some metadata which is used only during translation time (such as in which files is the string referenced, the format, etc), its size may actually double or triple its json representation, making it more expensive to be sent to the client. </p>
<p>Also, conversion of the .po files into json can be done a single time in the server and sent to every client, instead of having each of them spend extra browser processing time parsing and processing.</p>
<p>Either approach you take, gettext remains an excellent tool for internationalizing your web application.</p>
]]></content:encoded>
			<wfw:commentRss>http://weblogs.manas.com.ar/spalladino/2009/11/13/javascript-strings-translation-with-gettext/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Parameterized Tests</title>
		<link>http://weblogs.manas.com.ar/spalladino/2009/11/13/parameterized-tests/</link>
		<comments>http://weblogs.manas.com.ar/spalladino/2009/11/13/parameterized-tests/#comments</comments>
		<pubDate>Fri, 13 Nov 2009 14:06:08 +0000</pubDate>
		<dc:creator>spalladino</dc:creator>
				<category><![CDATA[Testing]]></category>

		<guid isPermaLink="false">http://weblogs.manas.com.ar/spalladino/?p=152</guid>
		<description><![CDATA[In order to prevent the dreadful copy-paste habits in unit tests (remember, tests are also code, so all the good practices you use when writing code should also apply to tests) a common pattern to test similar behaviour when slightly changing the input is to extract the test itself into a separate method. The scenario [...]]]></description>
			<content:encoded><![CDATA[<p>In order to prevent the dreadful copy-paste habits in unit tests (remember, <a href="http://weblogs.manas.com.ar/spalladino/2009/05/18/tests-are-also-code/">tests are also code</a>, so all the good practices you use when writing code should also apply to tests) a common pattern to test similar behaviour when slightly changing the input is to extract the test itself into a separate method.</p>
<h3>The scenario</h3>
<p>Suppose we want to test the behaviour of a class in charge of setting a user’s position based on supplied lat/long values.</p>
<div>
<pre><span style="color: #0000ff">interface</span> IUserLocator
{
    <span style="color: #0000ff">bool </span>Place(User user, <span style="color: #0000ff">double</span> latitude, <span style="color: #0000ff">double</span> longitude);
}</pre>
</div>
<p></p>
<h3>Doing it the wrong way</h3>
<p>A typical fixture covering some invalid scenarios, developed by a copy paste fan, would look like the following:</p>
<div>
<pre>[Test]
<span style="color: #0000ff">public</span> <span style="color: #0000ff">void</span> ShouldFailLatitudeLessThanNeg90()
{
    <span style="color: #0000ff">bool</span> result = locator.Place(user, -100, 20);
    Assert.False(result);
    Assert.AreEqual(previousLatitude, user.Lat);
    Assert.AreEqual(previousLongitude, user.Long);
}

[Test]
<span style="color: #0000ff">public</span> <span style="color: #0000ff">void</span> ShouldFailLatitudeMoreThan90()
{
    <span style="color: #0000ff">bool</span> result = locator.Place(user, 100, 20);
    Assert.False(result);
    Assert.AreEqual(previousLatitude, user.Lat);
    Assert.AreEqual(previousLongitude, user.Long);
}

[Test]
<span style="color: #0000ff">public</span> <span style="color: #0000ff">void</span> ShouldFailLongitudeLessThanNeg180()
{
    <span style="color: #0000ff">bool</span> result = locator.Place(user, 20, -190);
    Assert.False(result);
    Assert.AreEqual(previousLatitude, user.Lat);
    Assert.AreEqual(previousLongitude, user.Long);
}</pre>
</div>
<p></p>
<h3>Refactoring</h3>
<p>After the 3rd copy-pasted method, it should be pretty obvious that our code is demanding to extract the common code into a separate method which executes the body of the test. After this refactor we would have:</p>
<div>
<pre><span style="color: #0000ff">private</span> <span style="color: #0000ff">void</span> ShouldFailInvalidLatLong(<span style="color: #0000ff">double</span> lat, <span style="color: #0000ff">double</span> lng)
{
    <span style="color: #0000ff">bool</span> result = locator.Place(user, lat, lng);
    Assert.False(result);
    Assert.AreEqual(previousLatitude, user.Latitude);
    Assert.AreEqual(previousLongitude, user.Longitude);
}

[Test]
<span style="color: #0000ff">public</span> <span style="color: #0000ff">void</span> ShouldFailLatitudeLessThanNeg90()
{
    ShouldFailInvalidLatLong(-100, 20);
}

[Test]
<span style="color: #0000ff">public</span> <span style="color: #0000ff">void</span> ShouldFailLatitudeMoreThan90()
{
    ShouldFailInvalidLatLong(100, 20);
}

[Test]
<span style="color: #0000ff">public</span> <span style="color: #0000ff">void</span> ShouldFailLongitudeLessThanNeg180()
{
    ShouldFailInvalidLatLong(20, 190);
}</pre>
</div>
<p>Which is a lot better than before. However, we are forced to keep a different method for each of the different parameter combinations we are injecting into the auxiliary testing function. </p>
<p>We could keep all of them in a single method and loop through a list of parameters configurations, but in this case NUnit would not be able to distinguish them as different tests and fail the whole set if a single one does. And even worse, we don’t get a SetUp method for every case unless we call it explicitly, which is a huge drawback.</p>
<h3>Injecting parameter values</h3>
<p>Luckily, NUnit included native support for handling lists of parameters in version 2.5. Now we can simply write:</p>
<div>
<pre>[Test]
[Sequential]
<span style="color: #0000ff">public</span> <span style="color: #0000ff">void</span> ShouldFailInvalidLatLng(
    [Values(-100, 100, 20)] <span style="color: #0000ff">double</span> lat,
    [Values(20, 20, 190)] <span style="color: #0000ff">double</span> lng)
{
    <span style="color: #0000ff">bool</span> result = locator.Place(user, lat, lng);
    Assert.False(result);
    Assert.AreEqual(previousLatitude, user.Latitude);
    Assert.AreEqual(previousLongitude, user.Longitude);
}</pre>
</div>
<p>The <a href="http://www.nunit.org/index.php?p=values&amp;r=2.5">Values</a> attribute applied to a parameter lets us define which set of values we want to inject into that parameter for testing. NUnit will simply iterate through all the values, generating a different test for each of them.</p>
<p>Note the <a href="http://www.nunit.org/index.php?p=sequential&amp;r=2.5">Sequential</a> attribute applied to the test. By default, NUnit will generate all possible <a href="http://www.nunit.org/index.php?p=combinatorial&amp;r=2.5">combinations</a> of the parameters’ values; in this case, we want a sequential approach to only generate 3 tests: one with the first set of values (-100, 20), another one with (100, 20) and the last one with (20, 190). Another option is to use the <a href="http://www.nunit.org/index.php?p=pairwise&amp;r=2.5">Pairwise</a> attribute, which is a restricted variation of the combinatorial, that guarantees that every pair of different parameters will be executed, which is useful to control the amount of tests generated when handling multiple input parameters; however, it is not what we want in this case.</p>
<p>Now, this is how it looks like when ran in the console:</p>
</p>
</p>
</p>
</p>
<p><a href="http://weblogs.manas.com.ar/spalladino/files/2009/11/image.png"><img style="border-top-width: 0px;border-left-width: 0px;float: none;border-bottom-width: 0px;margin-left: auto;margin-right: auto;border-right-width: 0px" height="182" alt="image" src="http://weblogs.manas.com.ar/spalladino/files/2009/11/image_thumb.png" width="242" border="0" /></a> </p>
<p>It is even clearer than its verbose counterpart when you look at them together, as its groups all the instances of the same method under the same treenode.</p>
<h3>Generating parameter values</h3>
<p>Besides handling parameter combinations, NUnit also offers multiple options for injecting parameter values, such as the <a href="http://www.nunit.org/index.php?p=range&amp;r=2.5">Range</a> and the <a href="http://www.nunit.org/index.php?p=random&amp;r=2.5">Random</a> attribute, which generate values inside a specified range with a certain step (in the former) or in a completely random fashion (in the latter).</p>
<p>The following example will generate four different values for latitude, and three different random values for longitude, all of them in a valid range.</p>
<div>
<pre>[Test]
[Combinatorial]
<span style="color: #0000ff">public</span> <span style="color: #0000ff">void</span> ShouldSetLatLng(
    [Range(-90, 90, 60)] <span style="color: #0000ff">double</span> lat,
    [Random(-180, 180, 3)] <span style="color: #0000ff">double</span> lng)
{
    <span style="color: #0000ff">bool</span> result = locator.Place(user, lat, lng);
    Assert.That(result);
    Assert.AreEqual(lat, user.Latitude);
    Assert.AreEqual(lng, user.Longitude);
}</pre>
</div>
<p><a href="http://weblogs.manas.com.ar/spalladino/files/2009/11/image1.png"><img style="border-top-width: 0px;border-left-width: 0px;border-bottom-width: 0px;margin-left: 0px;margin-right: 0px;border-right-width: 0px" height="218" alt="image" src="http://weblogs.manas.com.ar/spalladino/files/2009/11/image_thumb1.png" width="209" align="right" border="0" /></a></p>
<p>Whenever we reload the test suite, NUnit will generate new fresh values for the randomized parameter. Losing determinism in your test suite is not something to overlook, so you should actually think twice before adding a random attribute to a parameter.</p>
<p>On the right is the tests generated as output of the test case above. Note that with very little effort the values generators, paired with the combinatorial attribute, produce a considerable number of test cases.</p>
</p>
</p>
<p>&#160;</p>
<h3>Extracting common data</h3>
<p>Yet another way to supply values is, if you don’t the noise generated by the values attribute applied on every parameter, or if you want to reuse a set of data, is the <a href="http://www.nunit.org/index.php?p=valueSource&amp;r=2.5">ValueSource</a> attribute, which lets you pull data from another source, in the following fashion:</p>
<div>
<pre><span style="color: #0000ff">public</span> <span style="color: #0000ff">class</span> LocatorPoints
{
    <span style="color: #0000ff">double</span>[] latitudes = { -90, -60, -30, 0, 30, 60, 90 };
    <span style="color: #0000ff">double</span>[] longitudes = { -180, -90, 0, 90, 180 };
}

[Test, Sequential]
<span style="color: #0000ff">public</span> <span style="color: #0000ff">void</span> ShouldSetLatLng(
    [ValueSource(<span style="color: #0000ff">typeof</span>(LocatorPoints), <span style="color: #006080">&quot;latitudes&quot;</span>)] <span style="color: #0000ff">double</span> lat,
    [ValueSource(<span style="color: #0000ff">typeof</span>(LocatorPoints), <span style="color: #006080">&quot;longitudes&quot;</span>)] <span style="color: #0000ff">double</span> lng)
{
    <span style="color: #0000ff">bool</span> result = locator.Place(user, lat, lng);
    Assert.That(result);
    Assert.AreEqual(lat, user.Latitude);
    Assert.AreEqual(lng, user.Longitude);
}</pre>
</div>
<p>This allows you to define the data sets and the tests applied separately, and reuse sets of data whenever necessary. With this feature we are not only extracting common code, but also extracting common datasets, and generating all combinations between them with ease.</p>
<h3>The TestCaseSource attribute</h3>
<p>You may choose to have even more control on the data supplied (and even on the values returned by the test!) with the <a href="http://www.nunit.org/index.php?p=testCaseSource&amp;r=2.5">TestCaseSource</a> attribute. </p>
<p>One way of using it is simply as a collection of value sources, specifying together all the input parameter combinations you are interested in:</p>
<div>
<pre><span style="color: #0000ff">public</span> <span style="color: #0000ff">class</span> LocatorPoints
{
    <span style="color: #0000ff">object</span>[] valid =
    {
        <span style="color: #0000ff">new</span>[] { -90, -180 },
        <span style="color: #0000ff">new</span> <span style="color: #0000ff">double</span>[] {  90,  180 },
        <span style="color: #0000ff">new</span> TestCaseData(30, 180)
    };
}

[Test]
[TestCaseSource(<span style="color: #0000ff">typeof</span>(LocatorPoints), <span style="color: #006080">&quot;valid&quot;</span>)]
<span style="color: #0000ff">public</span> <span style="color: #0000ff">void</span> ShouldSetLatLng(<span style="color: #0000ff">double</span> lat, <span style="color: #0000ff">double</span> lng)
{
    <span style="color: #0000ff">bool</span> result = locator.Place(user, lat, lng);
    Assert.That(result);
    Assert.AreEqual(lat, user.Latitude);
    Assert.AreEqual(lng, user.Longitude);
}</pre>
</div>
<p>The source of points may be a method instead of a field, which allows you to dynamically generate the parameter values you may want. </p>
<p>Note the way the combination (30, 180) is injected: it uses the <a href="http://www.nunit.org/index.php?p=testCaseSource&amp;r=2.5">TestCaseData</a> class. This class grants much more control over the parameterization than only specifying the input parameters. It provides a fluent interface to set the return value, expected exception, description, name, category, etc. </p>
<p>Let’s see how a complete fixture, for both valid and invalid tests, would look like when written using this interface:</p>
<div>
<pre><span style="color: #0000ff">public</span> IEnumerable&lt;TestCaseData&gt; Values()
{
    <span style="color: #0000ff">yield</span> <span style="color: #0000ff">return</span> <span style="color: #0000ff">new</span> TestCaseData(0, 0).Returns(<span style="color: #0000ff">true</span>)
        .SetName(<span style="color: #006080">&quot;ShouldSetLatLongOrigin&quot;</span>).SetCategory(<span style="color: #006080">&quot;valid&quot;</span>);

    <span style="color: #0000ff">yield</span> <span style="color: #0000ff">return</span> <span style="color: #0000ff">new</span> TestCaseData(90, 180).Returns(<span style="color: #0000ff">true</span>)
        .SetName(<span style="color: #006080">&quot;ShouldSetLatLongMaxValues&quot;</span>).SetCategory(<span style="color: #006080">&quot;valid&quot;</span>);

    <span style="color: #0000ff">yield</span> <span style="color: #0000ff">return</span> <span style="color: #0000ff">new</span> TestCaseData(100, 30).Returns(<span style="color: #0000ff">false</span>)
        .SetName(<span style="color: #006080">&quot;ShouldNotSetInvalidLat&quot;</span>).SetCategory(<span style="color: #006080">&quot;wronglat&quot;</span>);

    <span style="color: #0000ff">yield</span> <span style="color: #0000ff">return</span> <span style="color: #0000ff">new</span> TestCaseData(20, 190).Returns(<span style="color: #0000ff">false</span>)
        .SetName(<span style="color: #006080">&quot;ShouldNotSetInvalidLng&quot;</span>).SetCategory(<span style="color: #006080">&quot;wronglng&quot;</span>);
}

[Test]
[TestCaseSource(<span style="color: #006080">&quot;Values&quot;</span>)]
<span style="color: #0000ff">public</span> <span style="color: #0000ff">bool</span> SetLatLng(<span style="color: #0000ff">double</span> lat, <span style="color: #0000ff">double</span> lng)
{
    <span style="color: #0000ff">bool</span> result = locator.Place(user, lat, lng);

    Assert.AreEqual(result ? lat : previousLatitude, user.Latitude);
    Assert.AreEqual(result ? lng : previousLongitude, user.Longitude);

    <span style="color: #0000ff">return</span> result;
}</pre>
</div>
<p><a href="http://weblogs.manas.com.ar/spalladino/files/2009/11/image2.png"><img style="border-right: 0px;border-top: 0px;margin-left: 0px;border-left: 0px;margin-right: 0px;border-bottom: 0px" height="99" alt="image" src="http://weblogs.manas.com.ar/spalladino/files/2009/11/image_thumb2.png" width="223" align="right" border="0" /></a>By using a simple method that yields different configurations for our parameterized&#160; test we can set the input values, the expected return value, a specific name, category, etc. Basically we can write nearly a whole fixture using a single test and adequate parameters. </p>
<p>Whether this is too much injection over the tests or not is another discussion, finding a right balance is no easy task. In the very end, it is just another way of writing tests. </p>
]]></content:encoded>
			<wfw:commentRss>http://weblogs.manas.com.ar/spalladino/2009/11/13/parameterized-tests/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Gettext i18n strings in ASP.NET controls</title>
		<link>http://weblogs.manas.com.ar/spalladino/2009/10/07/gettext-i18n-strings-in-asp-net-controls/</link>
		<comments>http://weblogs.manas.com.ar/spalladino/2009/10/07/gettext-i18n-strings-in-asp-net-controls/#comments</comments>
		<pubDate>Wed, 07 Oct 2009 19:36:27 +0000</pubDate>
		<dc:creator>spalladino</dc:creator>
				<category><![CDATA[Gettext]]></category>
		<category><![CDATA[NET]]></category>
		<category><![CDATA[Web]]></category>
		<category><![CDATA[i18n]]></category>

		<guid isPermaLink="false">http://weblogs.manas.com.ar/spalladino/?p=148</guid>
		<description><![CDATA[In the last post I blogged about using gettext to internationalize strings in C#. However, using the Messages.T(&#34;Hello world&#34;) syntax in ASP.NET can be a little cumbersome. Luckily, ASP.NET controls can work as a solution for this issue. Adding a simple control which we will name just “t” (and place it in namespace “t” as [...]]]></description>
			<content:encoded><![CDATA[<p>In the <a href="http://weblogs.manas.com.ar/spalladino/2009/10/01/using-gnu-gettext-for-i18n-in-c-and-asp-net/">last post</a> I blogged about using gettext to internationalize strings in C#. However, using the <font face="Courier New">Messages.T(&quot;Hello world&quot;) </font>syntax in ASP.NET can be a little cumbersome. Luckily, ASP.NET controls can work as a solution for this issue. </p>
<p>Adding a simple control which we will name just “t” (and place it in namespace “t” as well) that handles translation of strings contained within can prevent the need of the code syntax in an ASP.NET. Therefore, we can write</p>
<div>
<pre><span style="color: #0000ff">&lt;</span><span style="color: #800000">h1</span><span style="color: #0000ff">&gt;&lt;</span><span style="color: #800000">t:t runat=”server”</span><span style="color: #0000ff">&gt;</span>My Title<span style="color: #0000ff">&lt;/</span><span style="color: #800000">t:t</span><span style="color: #0000ff">&gt;&lt;/</span><span style="color: #800000">h1</span><span style="color: #0000ff">&gt;</span></pre>
</div>
<p>instead of having to fall back to</p>
<div>
<pre><span style="color: #006080">&lt;</span><span style="color: #0000ff">h1</span><span style="color: #006080">&gt;</span><span style="color: #006080">&lt;</span>%= Messages<span style="color: #cc6633">.T</span>(&quot;My Title&quot;) %<span style="color: #006080">&gt;</span><span style="color: #006080">&lt;</span>/<span style="color: #0000ff">h1</span><span style="color: #006080">&gt;</span></pre>
</div>
<p>The angle bracket syntax feels more consistent with the rest of the HTML, and is much more comfortable to write. The only drawback is the need of the run at server attribute which is unavoidable.</p>
<p>The code for this control is fairly straightforward:</p>
<div>
<pre>[ParseChildren(<span style="color: #0000ff">false</span>)]
<span style="color: #0000ff">public</span> <span style="color: #0000ff">class</span> t : Control
{
    <span style="color: #0000ff">string</span> content;

    <span style="color: #0000ff">protected</span> <span style="color: #0000ff">override</span> <span style="color: #0000ff">void</span> AddParsedSubObject(<span style="color: #0000ff">object</span> obj)
    {
        <span style="color: #0000ff">if</span> (obj <span style="color: #0000ff">is</span> LiteralControl)
        {
            content = Strings.T(((LiteralControl)obj).Text);
        }
    }

    <span style="color: #0000ff">protected</span> <span style="color: #0000ff">override</span> <span style="color: #0000ff">void</span> Render(HtmlTextWriter writer)
    {
        writer.Write(content);
    }
}</pre>
</div>
<h3>&#160;</h3>
<h3>Extracting the content</h3>
<p>The problem with this approach is that the <a href="http://www.gnu.org/software/hello/manual/gettext/xgettext-Invocation.html">xgettext</a> tool only supports function calls, not tags. Therefore it is necessary to write a custom code crawler that extracts them. The easiest way to do this is having a tool run right before the invocation to xgettext and generate additional files that contain only the invocations to the <font face="Courier New">Messages.T</font> function, so they are actually recognised by xgettext.</p>
<p>The incredible simple regex for doing this is:</p>
<div>
<pre><span style="color: #006080">@&quot;&lt;\s*{0}\s*[^&gt;]*&gt;(?&lt;text&gt;.+?)&lt;/\s*{0}\s*&gt;&quot;</span></pre>
</div>
<p>Well, maybe not that simple, but it does work. It must be formatted with the name of the tag (in our case, “t:t”) and it will extract whatever content it can find between this tags in the “text” capturing group.</p>
<p>We can then write a new file containing all of this captures, each of them enclosed in an invocation of Messages.T(), and this file will be easily handled by xgettext.</p>
<h3>Handling standard C# calls</h3>
<p>But this is not all. If you do use the &lt;%= syntax in ASP.NET code and want xgettext to find calls to Messages.T() within them, you will find out that it throws a lot of errors. Evidently, xgettext was thought to parse standard C# code and not the one embedded within an ASP.NET page. </p>
<p>The best practice here is to also extract those strings into a separate well formed files. <a href="http://www.regular-expressions.info/examplesprogrammer.html">A nice regex</a> to capture them is:</p>
<div>
<pre><span style="color: #006080">@&quot;(?&lt;!\w){0}\(&quot;</span><span style="color: #006080">&quot;(?&lt;text&gt;[^&quot;</span><span style="color: #006080">&quot;\\]*(?:\\.[^&quot;</span><span style="color: #006080">&quot;\\]*)*)&quot;</span><span style="color: #006080">&quot;&quot;</span></pre>
</div>
<p>Remember to format this regex with the function name (Messages.T in this case), otherwise looking for a function named {0} will not return any matches whatsoever.</p>
<p>If you are interested in this processing, you may want to take a look at the tool we developed <a href="http://code.google.com/p/geochat/source/browse/#svn/trunk/Tools/Gettext.AspExtract">here</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://weblogs.manas.com.ar/spalladino/2009/10/07/gettext-i18n-strings-in-asp-net-controls/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Using GNU Gettext for i18n in C# and ASP.NET</title>
		<link>http://weblogs.manas.com.ar/spalladino/2009/10/01/using-gnu-gettext-for-i18n-in-c-and-asp-net/</link>
		<comments>http://weblogs.manas.com.ar/spalladino/2009/10/01/using-gnu-gettext-for-i18n-in-c-and-asp-net/#comments</comments>
		<pubDate>Thu, 01 Oct 2009 15:32:39 +0000</pubDate>
		<dc:creator>spalladino</dc:creator>
				<category><![CDATA[Gettext]]></category>
		<category><![CDATA[NET]]></category>
		<category><![CDATA[Web]]></category>
		<category><![CDATA[i18n]]></category>

		<guid isPermaLink="false">http://weblogs.manas.com.ar/spalladino/?p=115</guid>
		<description><![CDATA[We are in the process of dealing with the internationalization and localization of one of our open source web applications, which is fully developed using C# and ASP.NET MVC. Although ASP.NET already provides easy support for i18n via the usage of resx resource files, these are not very user friendly for translators. A resx file [...]]]></description>
			<content:encoded><![CDATA[<p>We are in the process of dealing with the internationalization and localization of one of our <a href="http://geochat.instedd.org/">open source web applications</a>, which is fully developed using C# and ASP.NET MVC. Although ASP.NET already provides easy support for i18n via the usage of <a href="http://msdn.microsoft.com/en-us/library/ms227427.aspx">resx resource</a> files, these are not very user friendly for translators.</p>
<p>A resx file is actually just an XML, but there are not many open source tools oriented for translators to easily handle them. Therefore we decided to try <a href="http://www.gnu.org/software/gettext/manual/gettext.html">GNU gettext</a>.</p>
<p>Gettext uses <a href="http://www.gnu.org/software/gettext/manual/gettext.html#PO-Files">.po file format</a> which basically consists of pairs of key/values. The interesting thing here is that keys in Gettext are the original untranslated text, so there is no need to keep the extra file containing untranslated strings. These files also keep tags, occurrences of the string in the code, and any other annotation inside comments, and there are plenty of helpful tools to handle them, specially designed to be used by translators, such as <a href="http://www.poedit.net/">PoEdit</a>, or the <a href="http://translate.sourceforge.net/wiki/pootle/index">Pootle server</a> which provides an online store for uploading, translating and merging .po files.</p>
<p>(just as a side note, NET resource files can be converted to a plain key=value text format using the <a href="http://msdn.microsoft.com/en-us/library/ccec7sz1.aspx">ResGen</a> utility; however, this format lacks all the added value provided by po files.)</p>
<p>GNU Gettext for windows can be downloaded from <a href="http://gnuwin32.sourceforge.net/packages/gettext.htm">here</a>, or you may want to directly use the tools included in the <a href="http://www.cygwin.com/">CygWin</a> environment.</p>
<h3>Handling messages</h3>
<p>As gettext does not require an extra untranslated resource file, with the default key=value mappings for each message, it provides an utility (<a href="http://www.gnu.org/software/hello/manual/gettext/xgettext-Invocation.html">xgettext</a>) to extract all calls to any specified &quot;translator&quot; function in code.</p>
<p>For example, suppose we have the traditional example:</p>
<div>
<div>
<pre>Console.WriteLine(<span style="color: #006080">&quot;Hello {0}!&quot;</span>, name);</pre>
</p></div>
</div>
<p>Using traditional .NET resource files, we should create a Resources file, add an entry with the text, and reference it:</p>
<div>
<div>
<pre>Console.WriteLine(Resources.Hello, name);</pre>
</p></div>
</div>
<p>However, using gettext, we define a function (one of the defaults is GetString, although we may change it to a much shorter one) that marks and translates strings and enclose the string within it:</p>
<div>
<div>
<pre>Console.WriteLine(Resources.GetString(<span style="color: #006080">&quot;Hello {0}!&quot;</span>), name);</pre>
</p></div>
</div>
<p>Using a shorter version with format string included:</p>
<div>
<div>
<pre>Console.WriteLine(Messages.T(<span style="color: #006080">&quot;Hello {0}!&quot;</span>, name));</pre>
</p></div>
</div>
<p>This ends up being a much faster way of manipulating strings, without requiring the need of editing a separate file.</p>
<h3>Behind GetString</h3>
<p>Although GNU gettext tools already provide a default implementation of a Resources Manager, I prefer writing a custom version with more control over strings manipulation, and using the default .NET logic for satellite culture assemblies lookup (as the default implementation does it manually).</p>
<p>A resources manager, which we shall name Messages , can be implemented by using a very similar structure to the <a href="http://codeview.aspcode.net/asp.net/aspcodedemos/BlogClient/BlogClient/Properties/Resources.Designer.cs.aspx">Resource class generated by .NET</a> when we add a resx file. That code loads the resource dictionary, and if you take a closer look, every method for accessing the externalized strings is just wrapping the key string:</p>
</p>
</p>
</p>
</p>
<div>
<pre><span style="color: #008000">/// &lt;summary&gt;</span>
<span style="color: #008000">/// Looks up a localized string similar to This is a test.</span>
<span style="color: #008000">/// &lt;/summary&gt;</span>
<span style="color: #0000ff">internal</span> <span style="color: #0000ff">static</span> <span style="color: #0000ff">string</span> TestString {
    get {
        <span style="color: #0000ff">return</span> ResourceManager.GetString(<span style="color: #006080">&quot;E_NoScriptManager&quot;</span>, resourceCulture);
    }
}</pre>
</div>
<p>Therefore, we can bypass those strongly typed methods and provide direct access to the dictionary itself. Since the keys are the untranslated version of the strings, we can simply write:</p>
</p>
<div>
<pre><span style="color: #008000">/// &lt;summary&gt;</span>
<span style="color: #008000">/// Looks up a localized string.</span>
<span style="color: #008000">/// &lt;/summary&gt;</span>
<span style="color: #008000">/// &lt;param name=&quot;t&quot;&gt;The untranslated string.&lt;/param&gt;</span>
<span style="color: #008000">/// &lt;returns&gt;Translated string according to the resource culture.&lt;/returns&gt;</span>
<span style="color: #0000ff">public</span> <span style="color: #0000ff">static</span> <span style="color: #0000ff">string</span> T(<span style="color: #0000ff">string</span> t)
{
    <span style="color: #0000ff">return</span> ResourceManager.GetString(t, resourceCulture);
}</pre>
</div>
<p>Here is the <a href="http://code.google.com/p/geochat/source/browse/trunk/Source/Core/CoreStrings.cs">full version</a> we are currently using with multiple overloads to handle string formatting and specifying a certain culture, in case you want to use it.</p>
<p>Note that the <a href="http://msdn.microsoft.com/en-us/library/system.resources.resourcemanager.aspx">ResourceManager</a> NET’s class automatically looks up the string based on the invoker thread’s <a href="http://msdn.microsoft.com/en-us/library/system.threading.thread.currentuiculture.aspx">current UI culture</a> property, unless you specify a different one.</p>
<h3>Creating the PO files</h3>
<p>If we want to get our strings localized, we must generate the po files to be distributed to the translators and then reincluded in the project. Creating these files is extremely easy using the xgettext tool as we had previously said.</p>
<p>The first step is to create a files list to be crawled by this tool. The simplest way is using a <a href="http://en.wikipedia.org/wiki/List_of_DOS_commands#dir">DOS dir</a> command to retrieve all csharp files and store them into a list. This can be done by using:</p>
<div>
<div>
<pre>dir .\Source\*.cs /S /B &gt; Strings.filelist</pre>
</p></div>
</div>
<p>The /S option forces to check on subdirs (a behaviour that xgettext cannot be instructed to have) and the /B prints a plain list with only filenames. </p>
<p>Then we run xgettext feeding it with the filelist we have just generated, and instructing it to process strings included in calls to <strong>Messages.T</strong>:</p>
<div>
<pre>xgettext.exe -k -kMessages.T
    --from-code=UTF-8 -LC# --omit-header
    -oMessages.po -fStrings.filelist</pre>
</div>
<p>The –k parameter specifies the function we want to extract strings from, –f is the filelist we use and –o the output po file, which will look like this:</p>
<div>
<pre>#: D:\Test\Source\Hello.cs:10
#, csharp-format
msgid <span style="color: #006080">&quot;Hello {0}!&quot;</span>
msgstr <span style="color: #006080">&quot;&quot;</span></pre>
</div>
<p>This file can be interpreted by any of the tools discussed before (like PoEdit). One for each different language is generated and distributed to translators.</p>
<h3><font color="#3f3f3f"></font></h3>
<h3>Creating the resources files</h3>
<p>We have marked the strings for translation, extracted them and are translating them at runtime using the <strong>T</strong> function. What we are missing is actually creating the resources files to be retrieved by NET’s ResourceManager, using the translated <strong>po</strong> files. </p>
<p>These files must conform to a specific resource format understood by the resource manager. Luckily, .NET provides a both a <a href="http://msdn.microsoft.com/en-us/library/ccec7sz1.aspx">ResGen</a> tool for creating them from other simpler formats, such as a plain text <em>name=value</em> file, as well as a <a href="http://msdn.microsoft.com/en-us/library/system.resources.resourcewriter.aspx">ResourceWriter</a> class.</p>
<p>What we did is develop a simple tool using this class which parses <strong>po</strong> files and outputs them as a NET resources file; you can find the code <a href="http://code.google.com/p/geochat/source/browse/trunk/#trunk/Tools/Gettext.Msgfmt">here</a>. So all you have to do is invoke it with the input po file:</p>
<div>
<div>
<pre>Msgfmt.exe -iMessages.es.po -oMessages.es.resources</pre>
</p></div>
</div>
</p>
<p>By including this resources file in the Visual Studio project, a satellite assembly for the specific culture will be automatically generated. Note that if you add it in a folder Resources, for example, the path to access it when creating the resources manager will be <em>ProjectName.Resources.Strings</em>.</p>
<p>In the case of ASP.NET projects, you should deploy the resources file to the App_GlobalResources folder, and access it via <em>Resources.Strings:</em></p>
<p><a href="http://weblogs.manas.com.ar/spalladino/files/2009/10/image.png"><img style="border-right: 0px;border-top: 0px;border-left: 0px;border-bottom: 0px" height="188" alt="image" src="http://weblogs.manas.com.ar/spalladino/files/2009/10/image_thumb.png" width="239" border="0" /></a> </p>
<h3>Getting the user’s culture</h3>
<p>After all this work, we still have to enable some mechanism for getting the user’s preferred culture and use it in the current thread, so our application will be effectively displayed in the chosen language.</p>
<p>I will not be going deep into this subject, as setting the culture for desktop applications is mostly automatic, and <a href="http://weblogs.manas.com.ar/smedina/">Sergio</a> has an <a href="http://weblogs.manas.com.ar/smedina/2008/12/17/internationalization-in-aspnet-mvc/">excellent post</a> about how to deal with i18n of ASP NET MVC websites via configuration, cookies and HttpModules.</p>
<h3>More to come…</h3>
<p>There are some non typical scenarios which you may run into when dealing with this solutions. Some of the most interesting we ran into are how to deal with internationalization of message sending, when the recipient’s culture may differ from the sender’s, or how to make an easy translation function for the ASP NET views.</p>
<p>I hope to be publishing more on this subjects soon.</p>
]]></content:encoded>
			<wfw:commentRss>http://weblogs.manas.com.ar/spalladino/2009/10/01/using-gnu-gettext-for-i18n-in-c-and-asp-net/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
	</channel>
</rss>
