<?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>CleanCode NZ</title>
	<atom:link href="http://www.cleancode.co.nz/feed" rel="self" type="application/rss+xml" />
	<link>http://www.cleancode.co.nz</link>
	<description>Web Application Development  and Engineering</description>
	<lastBuildDate>Tue, 14 Feb 2012 23:12:00 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Auto build for .NET using NANT</title>
		<link>http://www.cleancode.co.nz/blog/982/auto-build-net-nant</link>
		<comments>http://www.cleancode.co.nz/blog/982/auto-build-net-nant#comments</comments>
		<pubDate>Tue, 14 Feb 2012 23:12:00 +0000</pubDate>
		<dc:creator>CleanCodeNZ</dc:creator>
				<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[Software Engineering]]></category>

		<guid isPermaLink="false">http://www.cleancode.co.nz/?p=982</guid>
		<description><![CDATA[This is hands on example of using nant to build a .net solution, including the tricky deployment project type, auto versioning of assembly files and deployment project file. 1. Install NANT Download NANT, and unzip it, add nant.exe path to system path 2. Create build file under the project folder in the names like Yourprojectname.build [...]]]></description>
			<content:encoded><![CDATA[<p>This is hands on example of using nant to build a .net solution, including the tricky deployment project type, auto versioning of assembly files and deployment project file. <span id="more-982"></span></p>
<p>1. Install NANT<br />
Download NANT, and unzip it, add nant.exe path to system path</p>
<p>2. Create build file under the project folder  in the names like Yourprojectname.build<br />
In this way, nant will find *.build file automatically. All you need to do when doing a build is in cmd mode, cd to your project folder, then enter nant, all will be done</p>
<p>3. The build file is a xml file</p>
<pre class="brush: xml; title: ; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot; ?&gt;
&lt;project name=&quot;yourprojectname&quot; default=&quot;build&quot;&gt;
…
&lt;/ project &gt;
</pre>
<p>The root is project node, next level nodes are called <target>, here the default attribute is called build which means if you have not told nant which target to run, then nant will run build target as default.</p>
<p>4. Build target</p>
<pre class="brush: xml; title: ; notranslate">
&lt;target name=&quot;build&quot; depends=&quot;deploymentbuild&quot;&gt;
…
&lt;/target&gt;
</pre>
<p>This defines build target, where depends attribute means deploymentbuild needs to be run and successful before build target is run<br />
Through this you can split a build into many previous steps like running scripts, creating folders, running tests …</p>
<p>5. A few basic nant commands in build file</p>
<p>6. Define variables, they are called properties, placed just under project </p>
<pre class="brush: xml; title: ; notranslate">
&lt;property name=&quot;version.major&quot; value=&quot;1&quot; /&gt;
&lt;property name=&quot;version.minor&quot; value=&quot;0&quot; /&gt;
&lt;property name=&quot;version.build&quot; value=&quot;0&quot; /&gt;
&lt;property name=&quot;version.revision&quot; value=&quot;2&quot; /&gt;

&lt;property name=&quot;project.root&quot; value=&quot;D:\yourprojectfolder&quot; /&gt;
&lt;property name=&quot;build.root&quot; value=&quot;${project.root}\Releases&quot; /&gt;
</pre>
<p>To use the variable</p>
<pre class="brush: xml; title: ; notranslate">
&lt;property name=&quot;project.fullversion&quot; value=&quot;${version.major}.${version.minor}.${version.build}.${version.revision}&quot; dynamic=&quot;true&quot; /&gt;
</pre>
<p>7. To build a solution of Visual Studio</p>
<pre class="brush: xml; title: ; notranslate">
&lt;target name=&quot;buildcompile&quot; depends=&quot;version&quot;&gt;
    &lt;echo message=&quot;#### TARGET - build compile ####&quot;/&gt;
	&lt;solution configuration=&quot;debug&quot;
		solutionfile=&quot;yourprojectsolution.sln&quot; /&gt;
   &lt;/target&gt;
</pre>
<p>Build it in release mode</p>
<pre class="brush: xml; title: ; notranslate">
&lt;target name=&quot;releasebuild&quot; depends=&quot;buildcompile&quot;&gt;
	&lt;echo message=&quot;#### TARGET - release ####&quot;/&gt;
         &lt;solution configuration=&quot;release&quot;
	solutionfile=&quot;yourprojectsolution.sln&quot; /&gt;
   &lt;/target&gt;
</pre>
<p>8. To build a deployment project</p>
<p>If your solution has deployment project, above build does not generate setup.exe for your deployment project, it does not build vdproj, you will need to run this</p>
<pre class="brush: xml; title: ; notranslate">
&lt;!-- must build the dependency first (code project), before building the MSI deployment project --&gt;
&lt;exec program=&quot;${ide.dir}\Devenv.exe&quot; commandline='&quot;${solution}&quot; /rebuild &quot;Release&quot; /project &quot;${MSIprojectfile}&quot; /out &quot;${project.root}\release.log&quot;'/&gt;
</pre>
<p>This is also example of how to run an exe with arguments.</p>
<p>Here are my variables settings</p>
<pre class="brush: xml; title: ; notranslate">
&lt;property name=&quot;ide.dir&quot; value=&quot;C:\Program Files\Microsoft Visual Studio 10.0\Common7\IDE&quot; /&gt;
&lt;property name=&quot;solution&quot; value=&quot;yoursolutionfile.sln&quot; /&gt;
&lt;property name=&quot; MSIprojectfile &quot; value=&quot;${project.root}\ MSIproject \ MSIprojectfile.vdproj&quot; /&gt;
</pre>
<p>9. Delete a folder</p>
<pre class="brush: xml; title: ; notranslate">
&lt;delete dir=&quot;${build.dir}&quot; failonerror=&quot;false&quot; /&gt;
</pre>
<p>10. Create a folder</p>
<pre class="brush: xml; title: ; notranslate">
&lt;mkdir dir=&quot;${build.dir}&quot; /&gt;
</pre>
<p>11. Copy files</p>
<pre class="brush: xml; title: ; notranslate">
&lt;copy file=&quot;${project.root}\Releases\xxxx\bin\setup.exe&quot; tofile=&quot;${build.dir}\setup.exe&quot; /&gt;
&lt;copy todir=&quot;${build.dir}\Resources&quot;&gt;
&lt;fileset basedir=&quot;${project.root}\Releases\xxxx\Resources&quot;&gt;
 &lt;include name=&quot;*.*&quot; /&gt;
&lt;/fileset&gt;
&lt;/copy&gt;
</pre>
<p>12. Auto versioning<br />
Have you seen buildcompile depending on version, where is it and what it is for? We all want that this auto build toll can do auto versioning as the solution might have a dozen projects, it is pretty much a nuisance to go there to change versions manually.<br />
While there is no built versioning command in nant, I did one myself, here is it. There might be other versions on internet at the time of my research, but most of them did not work.</p>
<pre class="brush: xml; title: ; notranslate">
&lt;target name=&quot;version&quot;&gt;
		&lt;script language=&quot;C#&quot;&gt;
			&lt;references&gt;
					&lt;include name=&quot;System.dll&quot;/&gt;
			&lt;/references&gt;
			&lt;imports&gt;
				&lt;import namespace=&quot;System.Text.RegularExpressions&quot;/&gt;
			&lt;/imports&gt;
          &lt;code&gt;
		  &lt;![CDATA[

				public static void ScriptMain(Project project)
                {

					NAnt.Core.Tasks.EchoTask echo = new NAnt.Core.Tasks.EchoTask();
	                echo.Project = project;

					UpdateAssemblyVersion(project.Properties[&quot;projectassemblyfile&quot;], project.Properties[&quot;project.fullversion&quot;],echo);
					UpdateProductVersion(project.Properties[&quot;msiprojectfile&quot;], project.Properties[&quot;product.fullversion&quot;]);

  }

public static void UpdateAssemblyVersion(string filename,string version, NAnt.Core.Tasks.EchoTask echo)
				{

echo.Message = String.Format(&quot;Updating Assembly file: {0} and project new version:{1}&quot;, filename,version);
     echo.Execute();

StreamReader reader = new StreamReader(filename);
string contents = reader.ReadToEnd();
  reader.Close();

echo.Message = String.Format(&quot;contenst: {0}&quot;, contents);
 echo.Execute();

 Regex expressionForAssemblyVersion = new Regex(@&quot;(\[assembly:\s+AssemblyVersion\(&quot;&quot;)(?:[\d\.]+)(&quot;&quot;\)\])&quot;);

contents = expressionForAssemblyVersion.Replace(contents, &quot;${1}&quot; + version+&quot;${2}&quot;);

Regex expressionAssemblyFileVersionAttribute = new Regex(@&quot;(\[assembly:\s+AssemblyFileVersionAttribute\(&quot;&quot;)(?:[\d\.]+)(&quot;&quot;\)\])&quot;);

contents = expressionAssemblyFileVersionAttribute.Replace(contents, &quot;${1}&quot; + version+&quot;${2}&quot;);

 StreamWriter writer = new StreamWriter(filename, false);
  writer.Write(contents);
   writer.Close();

echo.Message = String.Format(&quot;next text: {0}&quot;, contents);
  echo.Execute();

}

public static void UpdateProductVersion(string setupFileName,string productVersion)
{
	string setupFileContents;

	//read in the .vdproj file
	using (StreamReader sr = new StreamReader(setupFileName))
	{
		setupFileContents = sr.ReadToEnd();
	}

	if (!string.IsNullOrEmpty(setupFileContents))
	{
 	Regex expression1 = new Regex(@&quot;(&quot;&quot;ARPCOMMENTS&quot;&quot; = &quot;&quot;8:.*Build )(?:[\d\.]+)&quot;);

	Regex expression2 = new Regex(@&quot;(&quot;&quot;ProductCode&quot;&quot; = &quot;&quot;8:{)(?:[\d\w-]+)&quot;);
	Regex expression3 = new Regex(@&quot;(&quot;&quot;PackageCode&quot;&quot; = &quot;&quot;8:{)(?:[\d\w-]+)&quot;);
	Regex expression4 = new Regex(@&quot;(&quot;&quot;ProductVersion&quot;&quot; = &quot;&quot;8:)(?:[\d\.]+)&quot;);

	setupFileContents = expression1.Replace(setupFileContents, &quot;${1}&quot;+productVersion);

	setupFileContents = expression2.Replace(setupFileContents,&quot;${1}&quot;+Guid.NewGuid().ToString().ToUpper());
	setupFileContents = expression3.Replace(setupFileContents,&quot;${1}&quot;+Guid.NewGuid().ToString().ToUpper());
	setupFileContents = expression4.Replace(setupFileContents,&quot;${1}&quot;+productVersion);

	using (TextWriter tw = new StreamWriter(setupFileName, false))
	{
		tw.WriteLine(setupFileContents);
	}
	}
	}

	]]&gt;
        &lt;/code&gt;

	&lt;/script&gt;

   &lt;/target&gt;
</pre>
<p>There are two functions I developed  UpdateAssemblyVersion and UpdateProductVersion, the first one is for normal assembly.cs, the other function is for vdproj file</p>
<pre class="brush: xml; title: ; notranslate">
&lt;property name=&quot; projectassemblyfile &quot; value=&quot;${project.root}\xxxxx\AssemblyInfo.cs&quot; /&gt;
&lt;property name=&quot; msiprojectfile &quot; value=&quot;${project.root}\xxxxx\yyyyyy. vdproj &quot; /&gt;
</pre>
<p>I am sure you have found other useful commands, you can share them here if you want, the purpose of this article is to provide you an example that can get you going right now rather than a complete tutorial.</p>
<p>Have fun</p>
]]></content:encoded>
			<wfw:commentRss>http://www.cleancode.co.nz/blog/982/auto-build-net-nant/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Dynamic configurable and resuable Linq</title>
		<link>http://www.cleancode.co.nz/blog/969/dynamic-configurable-resuable-linq</link>
		<comments>http://www.cleancode.co.nz/blog/969/dynamic-configurable-resuable-linq#comments</comments>
		<pubDate>Tue, 07 Feb 2012 07:21:41 +0000</pubDate>
		<dc:creator>CleanCodeNZ</dc:creator>
				<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[LINQ]]></category>

		<guid isPermaLink="false">http://www.cleancode.co.nz/?p=969</guid>
		<description><![CDATA[How to get past of writing static linq statements? Or how to include the parameters in your linq query? Or write your linq dynamically in order for it to be configurable and reusable? 1.Relationships and differences of delegate, expression and func Func, input is int, and output is int too, the last generic is output [...]]]></description>
			<content:encoded><![CDATA[<p>How to get past of writing static linq statements? Or how to include the parameters in your linq query? Or write your linq dynamically in order for it to be configurable and reusable?<span id="more-969"></span> </p>
<p>1.Relationships and differences of delegate, expression and func</p>
<pre class="brush: csharp; title: ; notranslate">
	   delegate int del(int i);

        private void button2_Click(object sender, EventArgs e)
        {

            del myDelegate = x =&gt; x * x;
            int j = myDelegate(5); //j = 25

            Func&lt;int, int&gt; myFunc = x =&gt; x*x ;

            j = myFunc(5);

            Expression&lt;del&gt; myET = x =&gt; x * x;

            del  myETFunc = myET.Compile();

            j = myETFunc(5);

            Expression&lt;Func&lt;int, int&gt;&gt; myExp = x =&gt; x * x;

            Func&lt;int, int&gt; myExpFunc = myExp.Compile();

            j = myExpFunc(5);

        }
</pre>
<p>Func<int, int>, input is int, and output is int too, the last generic is output type, the original type is:</p>
<pre class="brush: csharp; title: ; notranslate">
public delegate TResult Func&lt;in T, out TResult&gt;(T arg)
</pre>
<p>As an extreme, there is a type like this:</p>
<pre class="brush: csharp; title: ; notranslate">

public delegate TResult Func&lt;in T1, in T2, in T3, in T4, in T5, in T6, in T7, in T8, in T9, out TResult&gt;(
	T1 arg1,
	T2 arg2,
	T3 arg3,
	T4 arg4,
	T5 arg5,
	T6 arg6,
	T7 arg7,
	T8 arg8,
	T9 arg9
)
</pre>
<p>2. Dynamic Linq</p>
<pre class="brush: csharp; title: ; notranslate">
   private void button3_Click(object sender, EventArgs e)
   {
            Entities db = new Entities();

            Log log = db.Logs.Where(p =&gt; p.log_code == 1).FirstOrDefault();

            log = db.Logs.Where(FuncWhere(1)).FirstOrDefault();

            log = db.Logs.Where(ExpressionFuncWhere(1)).FirstOrDefault();
    }

        private Func&lt;Log, bool&gt; FuncWhere(int logcode)
        {
            Func&lt;Log, bool&gt; exp = p =&gt; p.log_code == logcode;

            return exp;
        }

        private Expression&lt;Func&lt;Log, bool&gt;&gt; ExpressionFuncWhere(int logcode)
        {
            Expression&lt;Func&lt;Log, bool&gt;&gt; exp = p =&gt; p.log_code == logcode;

            return exp;
        }
 </pre>
<p>3. Expression or Func</p>
<p>Using Expression<T> you are explicitly creating an expression tree &#8211; this means that you can deal with the code that makes up the query as if it were data.</p>
<p>4. Find the delegate type from system.linq </p>
<p>As an example of where implementation</p>
<pre class="brush: csharp; title: ; notranslate">
public static IQueryable&lt;TSource&gt; Where&lt;TSource&gt;(
this IQueryable&lt;TSource&gt; source, Expression&lt;Func&lt;TSource, bool&gt;&gt; predicate);
</pre>
<p>Where is an extension method.</p>
<p>Type inference from this key word for the data set where is applied on.  </p>
<p>Be aware of overloads</p>
<p>In System.Linq. Queryable, there are all sorts of Linq methods you can customize or make them dynamic according to your program needs, methods like : sum, orderby,selectmany etc</p>
<p>5. Expression Trees or not</p>
<p>When you need to combine query variables you might want to build your expression tree programmatically using expression tree, there is not an easy way, but I find it comfortable to just code my lambda in a static way.</p>
<pre class="brush: csharp; title: ; notranslate">
  private void button1_Click(object sender, EventArgs e)
        {
            Entities db = new Entities();

            Log log = db.Logs.Where(p =&gt; p.log_code ==1 &amp;&amp; p.log_text.Contains(&quot;Error&quot;) ).FirstOrDefault();

            log = db.Logs.Where(FuncCombinedWhere(1,&quot;Error&quot;)).FirstOrDefault();

        }
        private Func&lt;Log, bool&gt; FuncCombinedWhere(int logcode, string textseearch)
        {
            Func&lt;Log, bool&gt; exp = p =&gt; false;

            if (logcode != 0 &amp;&amp; !string.IsNullOrEmpty(textseearch))
            {
                exp = p =&gt; p.log_code == logcode &amp;&amp; p.log_text.Contains(textseearch);
            }
            else if (logcode != 0)
            {
                exp = p =&gt; p.log_code == logcode;
            }
            else if (!string.IsNullOrEmpty(textseearch))
            {
                exp = p =&gt; p.log_text.Contains(textseearch);

            }

            return exp;

        }
</pre>
<p>6. Reuse Linq through IQueryable<T> type</p>
<pre class="brush: csharp; title: ; notranslate">
public IQueryable&lt;Log&gt; AllErrorLog()
{
 return from log in db.Logs.where(p=&gt;p.log_level==1) select log;
}
</pre>
<p>AllErrorLog() can be used for contructing other queries.</p>
<p>Have fun.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.cleancode.co.nz/blog/969/dynamic-configurable-resuable-linq/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Name space programming in Javascript</title>
		<link>http://www.cleancode.co.nz/blog/959/namespace-programming-javascript</link>
		<comments>http://www.cleancode.co.nz/blog/959/namespace-programming-javascript#comments</comments>
		<pubDate>Fri, 13 Jan 2012 00:46:56 +0000</pubDate>
		<dc:creator>CleanCodeNZ</dc:creator>
				<category><![CDATA[Javascript]]></category>

		<guid isPermaLink="false">http://www.cleancode.co.nz/?p=959</guid>
		<description><![CDATA[We all start javascript programming in a procedure way, the functions and variables defined in the way everything are global, global variables are evil some even claim, on the other hand when scripts getting bigger, and object programming concept is being used more and more, you are facing with a daunting task of maintaining and [...]]]></description>
			<content:encoded><![CDATA[<p>We all start javascript programming in a procedure way, the functions and variables defined in the way everything are global, global variables are evil some even claim, on the other hand  when scripts getting bigger, and object programming concept is being used more and more, you are facing with a daunting task of maintaining and refactoring your existing scripts, developing new code is also getting more and more difficult. To organize the code into classes  is the right way to go down, further than that how about modules or  name spaces in javascript? The answer is yes.<span id="more-959"></span></p>
<p>Here is an example of procedural style of javascript where we all began with</p>
<pre class="brush: jscript; title: ; notranslate">
function foo()
{
};
function bar()
{
}
foo();
</pre>
<p>There is no name space concept in javascript, all we are going to do is to organize our code in a way that looks like a namespace that we are used to in other typed programming languages like java and .net, it is actually one global object.   </p>
<p>Basically there are two ways we can achieve this. One way is creating a literal object that</p>
<pre class="brush: jscript; title: ; notranslate">
  var ns1 = {
            foo: function () { },
            bar: function () { },
            v1: 'foo'
        };

        ns1.foo();

        var v2 = ns1.v1;
</pre>
<p>Another way is using a top level object with constructor(not literal)</p>
<pre class="brush: jscript; title: ; notranslate">
  var ns2 = new function() {

              this.foo = function () { };

              this.bar = function () { };

              this.v1 ='foo';
          };

          ns2.foo();

          var v3 = ns2.v1;

          alert(v3);
</pre>
<p>I prefer the second way than the first one, as object literal has more restrictive syntax than a function block, they are separated by commas and assigned values through ‘:’, like a json string which sometime might be diffuclt to read. the second way is also easier to wrap up your old procedure code into a name space by just including the block under a big function which is a global object served as name space (ns2)</p>
<p>All the functions that need to be exposed have to use &#8216;this&#8217; keyword to give a clear indication of scope within the object aka namespace.</p>
<p>Please take a notice of new keyword of ns2, without this, it is treated like a function, you basically cannot reference a function using dot annotation, in javascript even though you can do something like this </p>
<pre class="brush: jscript; title: ; notranslate">
   var ns3 = function () {

             this.foo = function () { alert('foofun') };

             this.bar = function () { };

             this.v1 = 'foo';
         };

         var ns3instance = new ns3();

         ns3instance.foo();

       //  ns3.foo(); // XXXX, it is not a function
</pre>
<p>So you will have to create an instance of ns3, it is hardly anything like the namespace we expected</p>
<p>There is another concept in javascript ‘self executing function’ which we do not find any equivalent in object oriented programming languages, but it is everywhere in functional programming languages like clojure or lisps</p>
<pre class="brush: jscript; title: ; notranslate">
     var ns4 = (function () {

             var pub = {};

             pub.foo = function () {

                 alert('ns4');
                 alert(this);

             };

             return pub;
         } ());

         ns4.foo();
</pre>
<p>Personally I would not go this way, as syntax is very hard to understand, one other thing is when you use ‘this’ keyword within self executing function, this always points to ‘window’, not the object itself, to me it does not have good modulation.</p>
<p>What I have shown is namespace.funcion() which is not exactly what we want for full scale object oriented programming. What we want is namespace.class references, here is the one, using foo as an object rather than function. and your modularised object oriented javascript programming starts from here.</p>
<pre class="brush: jscript; title: ; notranslate">
    var ns5 = new function () {

            this.foo = function () {

                alert('ns5');
                alert(this)
            };

        };

 var o = new ns5.foo();
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.cleancode.co.nz/blog/959/namespace-programming-javascript/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>C# Regex Gotchas</title>
		<link>http://www.cleancode.co.nz/blog/950/regex-gotchas</link>
		<comments>http://www.cleancode.co.nz/blog/950/regex-gotchas#comments</comments>
		<pubDate>Tue, 10 Jan 2012 01:24:40 +0000</pubDate>
		<dc:creator>CleanCodeNZ</dc:creator>
				<category><![CDATA[General]]></category>

		<guid isPermaLink="false">http://www.cleancode.co.nz/?p=950</guid>
		<description><![CDATA[Here I am going to show you how to understand a few confusing usages of regex in c#, like double quotes in pattern, find and replace, wrapping up with a real world example of version number replacing in automated build process. 1. Two ways of using regex for match,replace,etc, there is no difference using them [...]]]></description>
			<content:encoded><![CDATA[<p>Here I am going to show you how to understand a few confusing usages of regex in c#, like double quotes in pattern, find and replace, wrapping up with a real world example of version number replacing in automated build process.<span id="more-950"></span></p>
<p>1. Two ways of using regex for match,replace,etc, there is no difference using them either way as far as I am concerned:</p>
<p>1.1. Using Static Regex Class</p>
<pre class="brush: csharp; title: ; notranslate">
Match m = Regex.Match(&quot;abracadabra&quot;, &quot;(a|b|r)+&quot;);
string newString=Regex.Replace(&quot;  abra  &quot;, @&quot;^\s*(.*?)\s*$&quot;, &quot;$1&quot;);
</pre>
<p>1.2. Instantiated Regex Object</p>
<pre class="brush: csharp; title: ; notranslate">
string text = &quot;abracadabra1abracadabra2abracadabra3&quot;;
string pat = @&quot;
    (		# start the first group
      abra	# match the literal 'abra'
      (		# start the second (inner) group
      cad	# match the literal 'cad'
      )?	# end the second (optional) group
    )		# end the first group
    +		# match one or more occurences
    &quot;;
// use 'x' modifier to ignore comments
Regex r = new Regex(pat, &quot;x&quot;);

Match m = r.Match(text);
</pre>
<p>Regex.Replace needs to be assigned to get to the string that is replaced. </p>
<p>2. Double quote “ in pattern</p>
<p>Two ways of using double quote in pattern, the thrid way is bit of unusual but it does not do any harm.  </p>
<pre class="brush: csharp; title: ; notranslate">
// string literal
Regex expression1 = new Regex(@&quot;&quot;&quot;([\d\.]+)&quot;&quot;&quot;);
// escaped string
Regex expression11 = new Regex(&quot;\&quot;[\\d\\.]\&quot;&quot;);
// basically the same as first one
Regex expression111 = new Regex(@&quot;\&quot;&quot;([\d\.]+)\&quot;&quot;&quot;);
</pre>
<p>Double quote in string literal is double double quote “” or escape it with &#8220;\&#8221;.</p>
<p>3. Capture and Replace</p>
<p>There are two types of capture , one is non-capturing capture using (?:pattern) , the other one is using round brackets(pattern), to construct new string using “$1 “ to reference the first pattern match. Using &#8220;$1&#8243;+another string is very tricky, as when another string starts with a number then $referencenumber will point to none existing capture therefore &#8220;$1&#8243; will give you literal. Here is an example, you want to concatenate capture with string &#8220;123.456&#8243;, its not going to happen, all you get is &#8220;$1123.456&#8243;. to get around it you need &#8220;${1}&#8221; + &#8220;123.456&#8243;.</p>
<pre class="brush: csharp; title: ; notranslate">

// this gives you capture+ new version
str = expression1.Replace(str, &quot;$1&quot;+&quot;new version&quot; );
</pre>
<p>4. A useful example</p>
<p>When doing automated release, you will have the release tool like NAnt to do version replacement for you, the task is to extract the version number out and replace it with new one using regex</p>
<pre class="brush: csharp; title: ; notranslate">

   string setupFileContents = @&quot;&quot;&quot;ARPCOMMENTS&quot;&quot; = &quot;&quot;8:xxx Build 3.5.2000&quot;&quot;&quot;;

    Regex expression1 = new Regex(@&quot;(&quot;&quot;ARPCOMMENTS&quot;&quot; = &quot;&quot;8:.*Build )(?:[\d\.]+)&quot;);

    setupFileContents = expression1.Replace(setupFileContents, &quot;$1 &quot;+&quot;new version no&quot; );
</pre>
<p>Have fun and hope this clears some confusion for you and makes you more confident when using regex.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.cleancode.co.nz/blog/950/regex-gotchas/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Customization of Spring Security Authentication</title>
		<link>http://www.cleancode.co.nz/blog/937/customization-spring-security-authentication</link>
		<comments>http://www.cleancode.co.nz/blog/937/customization-spring-security-authentication#comments</comments>
		<pubDate>Sat, 05 Nov 2011 04:38:52 +0000</pubDate>
		<dc:creator>CleanCodeNZ</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Spring]]></category>

		<guid isPermaLink="false">http://www.cleancode.co.nz/?p=937</guid>
		<description><![CDATA[Normally we do application authentication against a database or authenticating through web services or even more complicated a mix of them. With this in mind, I start to investigate how to use spring security to achieve authentication in these scenarios. We have nice in memory authentication examples from its document, as following: But highly unlikely [...]]]></description>
			<content:encoded><![CDATA[<p>Normally we do application authentication against a database or authenticating through web services or even more complicated a mix of them. With this in mind, I start to investigate how to use spring security to achieve authentication in these scenarios.<span id="more-937"></span></p>
<p>We have nice in memory authentication examples from its document, as following:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;authentication-manager&gt;
    &lt;authentication-provider&gt;
      &lt;user-service&gt;
        &lt;user name=&quot;jimi&quot; password=&quot;jimispassword&quot; authorities=&quot;ROLE_USER, ROLE_ADMIN&quot; /&gt;
        &lt;user name=&quot;bob&quot; password=&quot;bobspassword&quot; authorities=&quot;ROLE_USER&quot; /&gt;
      &lt;/user-service&gt;
    &lt;/authentication-provider&gt;
  &lt;/authentication-manager&gt;
</pre>
<p>But highly unlikely your system only got a few known hardcoded users, we also have other out of box authentication providers to use, like LDAP or OpenId, which still let me wondering how to have more control on authentication.</p>
<p>There is an out of box authentication against database, but it needs the creation and existence of tables exactly in its desired schema, which is not very useful as well, plus if we want authenticate through web service,we are still stuck.</p>
<p>I know from my experience with other languages that the answer lies in customization of AuthenticationProvider. But I kept getting the suggestions of extension of UserDetailService, and I had a closer look of the UserDetailService interface it only has one function</p>
<pre class="brush: java; title: ; notranslate">
public UserDetails loadUserByUsername(String username)
            throws UsernameNotFoundException {
    }
</pre>
<p>This by the looks of it, only loads a user detail through user name, how can we authentication a user with user name and password? </p>
<p>One more frustration is that you can not even find any example out there telling you how to extend AuthenticationProvider, and most of examples of are telling you how to implement UserDetailService, What the hack this has got to do with authentication? Do we need to implement both AuthenticationProvider and UserDetailService to provide a proper authentication mechanism?</p>
<p>Here are the messages that are missing from Spring Security Document and there are paths wandering through AuthenticationProvider and UserDetailService.</p>
<p>You definitely need to customize AuthenticationProvider, which is the base class and starting point of making your own authentication, out of box LDAP and OpenId providers are implementations of it, then why we do not get told how to implement AuthenticationProvider? The answer is you hardly need to go down to that level of class hierarchy, you can get away with UserDetailService, sorry if I have confused you, but am not kidding.</p>
<p>Have a check of AbstractUserDetailsAuthenticationProvider, it is an extension of AuthenticationProvider, and it has an interesting method:</p>
<pre class="brush: java; title: ; notranslate">
protected abstract UserDetails retrieveUser(java.lang.String username,
                                            UsernamePasswordAuthenticationToken authentication)
                                     throws AuthenticationException
</pre>
<p>Is not UserDetails what UserDetailService provides? So another option is you can extend AbstractUserDetailsAuthenticationProvider instead of grand dad AuthenticationProvider, it is your choice, but still I have yet shown you why UserDetailService is so popular</p>
<p><strong>You can just implement UserDetailService to customize your authentication process either from a database or from web service, because it is provided by an out of box AuthenticationProvider implementation: DaoAuthenticationProvider</strong> which is a conceret class of  AbstractUserDetailsAuthenticationProvider and relies on UserDetailService to provide user name and password to compare them with user inputs to achieve authentication.</p>
<p>To put another way, even we only provide a user name to the UserDetailService, that leaves the UserDetailService implementation to return UserDetails that has user password, then DaoAuthenticationProvider will be responsible to check the credentials coming from login form with UserDetails, and take it from there.</p>
<p>To find the right spot of customization is important, and a sign of elegance of software development.</p>
<p>One last piece of puzzle, why from nowhere is DaoAuthenticationProvider mentioned? Or when you first saw its name you reckon it has anything to do with data access like database? All it is because it is the DEFAULT AuthenticationProvider when you config the authentication-provider node in security.xml, if you do not mention any AuthenticationProvider, then Spring Security assuems you use DaoAuthenticationProvider,</p>
<p>So if use:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;authentication-manager&gt;
    &lt;authentication-provider&gt;
      &lt;user-service&gt;
        &lt;user name=&quot;jimi&quot; password=&quot;jimispassword&quot; authorities=&quot;ROLE_USER, ROLE_ADMIN&quot; /&gt;
        &lt;user name=&quot;bob&quot; password=&quot;bobspassword&quot; authorities=&quot;ROLE_USER&quot; /&gt;
      &lt;/user-service&gt;
    &lt;/authentication-provider&gt;
  &lt;/authentication-manager&gt;
</pre>
<p>It is using DaoAuthenticationProvider, if you use</p>
<pre class="brush: xml; title: ; notranslate">
&lt;authentication-manager&gt;
		&lt;authentication-provider user-service-ref=&quot;cleancodeUserService&quot; &gt;
		&lt;/authentication-provider&gt;
	&lt;/authentication-manager&gt;
&lt;beans:bean id=&quot;cleancodeUserService&quot; class=&quot;com.cleancode.springmvc1.users.UserServiceImpl&quot;/&gt;
</pre>
<p>It is using DaoAuthenticationProvider too, even it is not in your config, as it is default.</p>
<p>It is time to show you some examples of how all these are done</p>
<p>Example 1 Customization of AuthenticationProvider:</p>
<p>Implementation of AuthenticationProvider, just presented as a prof of concept, not that I encourage you to start from this level. </p>
<pre class="brush: java; title: ; notranslate">
public class CleanCodeAuthenticationProvider implements AuthenticationProvider{

	public Authentication authenticate(Authentication authentication)
			throws AuthenticationException {

		List&lt;GrantedAuthority&gt; AUTHORITIES = new ArrayList&lt;GrantedAuthority&gt;();
		AUTHORITIES.add(new SimpleGrantedAuthority(&quot;ROLE_USER&quot;));
		if (authentication.getName().equals(authentication.getCredentials()))
			return new UsernamePasswordAuthenticationToken(authentication.getName(), authentication.getCredentials(), AUTHORITIES);
		else
			return null;

	}

	public boolean supports(Class&lt;? extends Object&gt; authentication) {
		return authentication.equals(UsernamePasswordAuthenticationToken.class);

	}

}
</pre>
<p>where authentication.getName().equals(authentication.getCredentials() is just an example, you can go off to somewhere else to get user according to its name and compare the password with authentication.getCredentials().</p>
<p>And security.xml is like</p>
<pre class="brush: xml; title: ; notranslate">
&lt;authentication-manager&gt;
		&lt;authentication-provider ref=&quot;customAuthenticationProvider&quot; &gt;
		&lt;/authentication-provider&gt;
	&lt;/authentication-manager&gt;
	&lt;beans:bean id=&quot;customAuthenticationProvider&quot; class=&quot;com.cleancode.springmvc1.users.CleanCodeAuthenticationProvider&quot;/&gt;
</pre>
<p>Example 2: Customization of UserDetailsService</p>
<pre class="brush: java; title: ; notranslate">
public class UserServiceImpl implements UserDetailsService {

    public UserDetails loadUserByUsername(String username)
            throws UsernameNotFoundException {

    	List&lt;GrantedAuthority&gt; AUTHORITIES = new ArrayList&lt;GrantedAuthority&gt;();

    	if(username.equals(&quot;rod&quot;))
    	{

    		AUTHORITIES.add(new SimpleGrantedAuthority(&quot;supervisor&quot;));
    		AUTHORITIES.add(new SimpleGrantedAuthority(&quot;user&quot;));
    		AUTHORITIES.add(new SimpleGrantedAuthority(&quot;teller&quot;));
    		return new User(&quot;rod&quot;,
    				&quot;4efe081594ce25ee4efd9f7067f7f678a347bccf2de201f3adf2a3eb544850b465b4e51cdc3fcdde&quot;,
    				 AUTHORITIES);

    	} else if (username.equals(&quot;scott&quot;)){

    		AUTHORITIES.add(new SimpleGrantedAuthority(&quot;user&quot;));
    		return new User(&quot;scott&quot;,
    				&quot;fb1f9e48058d30dc21c35ab4cf895e2a80f2f03fac549b51be637196dfb6b2b7276a89c65e38b7a1&quot;,
    				 AUTHORITIES);
    	}
    	else
    	{
    		throw new UsernameNotFoundException(&quot;User not found: &quot; + username);
    	}

    }
}
</pre>
<p>Here I am using hardcoded user names and passwords as an example, the thing is you can go to a database or web service to retrieve user details(including password) with user name, then pass the user name and password to User constructor, the password will be used later in the chain by DaoAuthenticationProvider</p>
<p>Security.xml</p>
<pre class="brush: xml; title: ; notranslate">
  &lt;beans:bean id=&quot;encoder&quot; class=&quot;org.springframework.security.crypto.password.StandardPasswordEncoder&quot;/&gt;

  &lt;!--
    Usernames/Passwords are
        rod/koala
        scott/wombat
    --&gt;
 	&lt;authentication-manager&gt;
		&lt;authentication-provider user-service-ref=&quot;cleancodeUserService&quot; &gt;
			&lt;password-encoder ref=&quot;encoder&quot;/&gt;
		&lt;/authentication-provider&gt;
	&lt;/authentication-manager&gt;
	&lt;beans:bean id=&quot;cleancodeUserService&quot; class=&quot;com.cleancode.springmvc1.users.UserServiceImpl&quot;/&gt;
</pre>
<p>You can see you do not need to point  DaoAuthenticationProvider as AuthenticationProvider, password-encoder is another feature provided by DaoAuthenticationProvider. </p>
<p>http config is not presented here.</p>
<p>Have fun.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.cleancode.co.nz/blog/937/customization-spring-security-authentication/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Using Springsource Tool Suite with Google App Engine</title>
		<link>http://www.cleancode.co.nz/blog/920/springsource-tool-suite-google-app-engine</link>
		<comments>http://www.cleancode.co.nz/blog/920/springsource-tool-suite-google-app-engine#comments</comments>
		<pubDate>Fri, 26 Aug 2011 09:04:40 +0000</pubDate>
		<dc:creator>CleanCodeNZ</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[GAE]]></category>
		<category><![CDATA[Spring]]></category>

		<guid isPermaLink="false">http://www.cleancode.co.nz/?p=920</guid>
		<description><![CDATA[Nowadays web application development relies on fast scaffolding based on templates, automated build and deploy tools. In java, you can find tools like ant and maven or leningen to create a stub application by just one command, build and deploy is not more complicated than just issuing two words command line command like maven build&#8230; [...]]]></description>
			<content:encoded><![CDATA[<p>Nowadays web application development relies on fast scaffolding based on templates, automated build and deploy tools. In java, you can find tools like ant and maven or leningen to create a stub application by just one command, build and deploy is not more complicated than just issuing two words command line command like maven build&#8230;</p>
<p>But when it comes to some frameworks it might be a big struggle to find a build tool that can do all of these, an example is how to fast scaffold  a stub  Google App Engine application that is going to use spring frame work.<span id="more-920"></span></p>
<p>You can find build tools for either Google app engine applications like Google plugin for Eclipse  or  spring application development provided by Springsource Tool Suite :STS.</p>
<p>There is the Google plugin for STS , but when you create a GAE application it hardly does anything.</p>
<p>One way you can have such application setup quick is using Roo, but for me it sounds a step too far, I want a tool to do scaffolding for me, but not all the views, by the way, project created by Roo can not build in STS out of box.</p>
<p>Some people blogged about creating a GAE stub first then manually add spring jars to the project, this is hardly satisfying as issues of versioning, upgrading are not addressed, and a tool like STS has all the guts of building spring application in it, the thing is just how are we going to do this in our attempted perspective.</p>
<p>Here I am going to document to set up spring framework based google app engine template on STS without using ROO, without adding spring jars manually.</p>
<p>It also applies to application that have been built using spring framework, but not targeting to GAE specifically. Through the same process, you can add GAE support to your application, but there might be some errors you need to sort out before it can be run on GAE.</p>
<p>It starts from a springmvc project template then adding the support of Google AppEngine, in the end  from this project you have built-in support from both GAE and spring, you can keep developing it as a spring project and run and debug it in tcServer, also you can run this as GAE project and deploy to GAE is also a click away.</p>
<p>File->New->Spring Template Project->Spring MVC Project<br />
<div id="attachment_924" class="wp-caption alignnone" style="width: 510px"><a href="http://www.cleancode.co.nz/wp-content/uploads/NewSpringMVCProject.png"><img src="http://www.cleancode.co.nz/wp-content/uploads/NewSpringMVCProject.png" alt="NewSpringMVCProject" title="NewSpringMVCProject" width="500" height="500" class="size-full wp-image-924" /></a><p class="wp-caption-text">NewSpringMVCProject</p></div></p>
<p>And what you have got is like:<br />
<div id="attachment_925" class="wp-caption alignnone" style="width: 522px"><a href="http://www.cleancode.co.nz/wp-content/uploads/SpringTemplate.png"><img src="http://www.cleancode.co.nz/wp-content/uploads/SpringTemplate.png" alt="SpringTemplate" title="SpringTemplate" width="512" height="384" class="size-full wp-image-925" /></a><p class="wp-caption-text">SpringTemplate</p></div><br />
This is a standard springmvc application from the out of box template, if you have already got a spring application, the last step can be ignored and start from the next step.</p>
<p>Right click the project Build path: Add Libraries&#8230;, Google App Engine<br />
<div id="attachment_926" class="wp-caption alignnone" style="width: 448px"><a href="http://www.cleancode.co.nz/wp-content/uploads/AddLibrary.png"><img src="http://www.cleancode.co.nz/wp-content/uploads/AddLibrary.png" alt="AddLibrary" title="AddLibrary" width="438" height="456" class="size-full wp-image-926" /></a><p class="wp-caption-text">AddLibrary</p></div></p>
<p>Add appengine-web.xml to src/main/webapp/WEB-INF/<br />
This has to be added by dropping it from IDE, rather than copying it under file system</p>
<p>Add lib folder  to src/main/webapp/WEB-INF/</p>
<p>Add gwt-serlet.jar to src/main/webapp/WEB-INF/lib</p>
<p>Right click the project -> Google->then properties for yourproject window ->	Web Application->tick this project has a WAR directory->point it to src/main/webapp</p>
<p>Right click the project again->Google->then properties for yourproject window -> Google-App-Engine, contents in appengine-web.xml should be picked up, and simply tick the box ‘use google app engine’</p>
<p>RunAs maven package(if you run as Google Web Application, it will ask for war packages) to build spring project, now it will be totally fine to debug or deploy this project to App Engine, when run it as Web Application, point war to src/target/ springmvcintegrationwithgae-1.0.0-BUILD-SNAPSHOT. </p>
<p>This means  you should be able to run it as both spring project  or gae project.</p>
<p>Final project structure will be like:</p>
<div id="attachment_927" class="wp-caption alignnone" style="width: 427px"><a href="http://www.cleancode.co.nz/wp-content/uploads/FinalProjectTree.png"><img src="http://www.cleancode.co.nz/wp-content/uploads/FinalProjectTree.png" alt="FinalSpringMVCGAEProjectTree" title="FinalSpringMVCGAEProjectTree" width="417" height="711" class="size-full wp-image-927" /></a><p class="wp-caption-text">FinalSpringMVCGAEProjectTree</p></div>
<p>STS Version : 2.7.1.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.cleancode.co.nz/blog/920/springsource-tool-suite-google-app-engine/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Springsource Tool Suite Server Error</title>
		<link>http://www.cleancode.co.nz/blog/913/springsource-tool-suite-server-error</link>
		<comments>http://www.cleancode.co.nz/blog/913/springsource-tool-suite-server-error#comments</comments>
		<pubDate>Fri, 19 Aug 2011 23:36:45 +0000</pubDate>
		<dc:creator>CleanCodeNZ</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Spring]]></category>

		<guid isPermaLink="false">http://www.cleancode.co.nz/?p=913</guid>
		<description><![CDATA[When you are using spring frame work for java web application development you must check out the development tool provided by VMware, which not only allows you debugging spring based application, but also comes with a web server tc Server. The problem is when I tried to use the IDE on my windows 7 pc, [...]]]></description>
			<content:encoded><![CDATA[<p>When you are using spring frame work for java web application development you must check out the development tool provided by VMware, which not only allows you debugging spring based application, but also comes with a web server tc Server. <span id="more-913"></span></p>
<p>The problem is when I tried to use the IDE on my windows 7 pc, I always get configuration corrupt or incomplete issue when starting the server, </p>
<p>The full error message is like :</p>
<p>Could not load the Tomcat server configuration at \Servers\VMware vFabric tc Server Developer Edition (runtime) v2.5 at localhost-config. The configuration may be corrupt or incomplete</p>
<p>Reason:</p>
<p>Could not load the Tomcat server configuration at \Servers\VMware vFabric tc Server Developer Edition (runtime) v2.5 at localhost-config. The configuration may be corrupt or incomplete</p>
<p>And screenshot is attached.<br />
<div id="attachment_916" class="wp-caption alignnone" style="width: 558px"><a href="http://www.cleancode.co.nz/wp-content/uploads/STS-Server-Error.png"><img src="http://www.cleancode.co.nz/wp-content/uploads/STS-Server-Error.png" alt="STS Server Error" title="STS Server Error" width="548" height="243" class="size-full wp-image-916" /></a><p class="wp-caption-text">STS Server Error</p></div></p>
<p>The problem about this issue in my case is sts.exe needs to be run AS ADMINISTRATOR, I guess you will have the same problem on vista, but not a problem for xp users.</p>
<p>Here are a few other issues that I have had with STS, but managed to find the solutions.<br />
[Update]<br />
Error :<br />
Setting property &#8216;source&#8217; to &#8216;org.eclipse.jst.jee.server:&#8217; did not find a matching property.</p>
<p>Symptom:<br />
Whenever running or debugging spring projects it went to 404 page straightway, while the sts console continue to process the compiling.</p>
<p>Solution:<br />
It turns out that I have tomcat installed on my pc, when you visit http://localhost:8080/ it goes to tomcat page, while sts has tc Server built in, when I turned off tomcat, I can run and debug project in sts as expected. while sts tc server is started, http://localhost:8080 should give you vmware server page.<br />
I searched the internet for the error, none has mentioned this issue, so I documented it here in case you might have the same issue.</p>
<p>Have fun.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.cleancode.co.nz/blog/913/springsource-tool-suite-server-error/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Absolute and Relative Path in XSLT</title>
		<link>http://www.cleancode.co.nz/blog/904/absolute-relative-path-xslt</link>
		<comments>http://www.cleancode.co.nz/blog/904/absolute-relative-path-xslt#comments</comments>
		<pubDate>Fri, 19 Aug 2011 23:08:09 +0000</pubDate>
		<dc:creator>CleanCodeNZ</dc:creator>
				<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[xslt]]></category>

		<guid isPermaLink="false">http://www.cleancode.co.nz/?p=904</guid>
		<description><![CDATA[The following is observed from xslt version 1.0 1. There are two important nodes that we must always be sure about &#8220;.&#8221; the current context node and &#8220;/&#8221; document root not current context node root &#8220;.&#8221; Context node can be changed while getting in and out of looping : xsl:for-each or xsl:apply-templates, in some circumstances [...]]]></description>
			<content:encoded><![CDATA[<p>The following is observed from xslt version 1.0</p>
<p>1. There are two important nodes that we must always be sure about </p>
<p>&#8220;.&#8221;  the current context node and<br />
&#8220;/&#8221; document root not current context node root<span id="more-904"></span></p>
<p>&#8220;.&#8221;  Context node can be changed while getting in and out of looping : xsl:for-each or xsl:apply-templates, in some circumstances &#8220;/&#8221; document root could also be changed.</p>
<p>2. Even within a for-each loop, you still can select elements out side of context node by using absolute path. like select=&#8221;/abolute level1/absolute level2&#8243;</p>
<p>3.How to tell the path is absolute or relative, there are only two ways for absolute path:</p>
<p>Absolute path 1: starts from &#8220;/&#8221;, select=&#8221;/abolute level1/absolute level2&#8243;</p>
<p>Absolute path2: abbreviated absolute location path, starts from &#8220;//&#8221;, select =&#8221;//absolute levelx from root/levely&#8221;, this is sometime confusing, as it could be deemed as context node downward searching rather than document root based downward searching.</p>
<p>Anything else is relative location path, you can explicitly use &#8220;.&#8221; to indicate that this is a relative location path to current context node  select=&#8221;./childlevel1/childlevel2&#8243;  which is the same as &#8220;childlevel1/childlevel2&#8243;<br />
or select &#8220;.//childlevel2&#8243;</p>
<p>But bear in mind, document has context too, in the following case, the document inside the for-each is switched from the one outside of for-each</p>
<pre class="brush: xml; title: ; notranslate">
&lt;xsl:variable name=&quot;nodeset&quot;&gt;
            &lt;xsl:copy-of select=&quot;//Groups/Group&quot;/&gt;
&lt;/xsl:variable&gt;
&lt;xsl:for-each select=&quot;msxsl:node-set($nodeset)/*&quot;&gt;
            &lt;xsl:variable name=&quot;whatisthis&quot; select=&quot;.&quot; /&gt;
            &lt;xsl:variable name=&quot;whatisthis2&quot; select=&quot;/&quot; /&gt;
&lt;/xsl:for-each&gt;
</pre>
<p>Whatisthis2 is the root of new document created by node-set conversion, rather than the root of &#8220;//Groups/Group&#8221;, copy-of only returns a result tree fragment , so needs to be converted into node-set to use xpath</p>
<p>Key() use:</p>
<p>key() function always selects nodes from the same document the context node belongs to, that means index is only built when first time  key is used, and has a document context, so be careful when first reference of key is called, the document context will be decided by then, not where you declare your key. So you can see difference in above example if key is called within the for-each $nodeset loop or out side loop.</p>
<p>Ways to avoid confusion:</p>
<p>Always be aware of context change in terms of both node and document<br />
Try not to use node-set extension function.</p>
<p>Cheers</p>
]]></content:encoded>
			<wfw:commentRss>http://www.cleancode.co.nz/blog/904/absolute-relative-path-xslt/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Anatomy of JSONP Ajax in GWT</title>
		<link>http://www.cleancode.co.nz/blog/900/anatomy-jsonp-ajax-gwt</link>
		<comments>http://www.cleancode.co.nz/blog/900/anatomy-jsonp-ajax-gwt#comments</comments>
		<pubDate>Fri, 29 Jul 2011 03:20:36 +0000</pubDate>
		<dc:creator>CleanCodeNZ</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[GWT]]></category>

		<guid isPermaLink="false">http://www.cleancode.co.nz/?p=900</guid>
		<description><![CDATA[It is just a self study note from http://code.google.com/webtoolkit/doc/latest/tutorial/Xsite.html Part 1: Cross site JSON web service So in my case I deployed the stockPrices.php onto my development php server and a call to: http://localhost:81/AliasTestSite/stockPrices.php?q=ABC&#038;callback=callback125 gives me a JSONP string: callback125([{"symbol":"ABC","price":68.826522738023,"change":-1.3483844858836}]); Part 2 : JSONP url Part 3: Data contract The same as JSON example Part [...]]]></description>
			<content:encoded><![CDATA[<p>It is just a self study note from http://code.google.com/webtoolkit/doc/latest/tutorial/Xsite.html<span id="more-900"></span></p>
<p>Part 1: Cross site JSON web service</p>
<p>So in my case I deployed the stockPrices.php onto my development php server and a call to:</p>
<p>http://localhost:81/AliasTestSite/stockPrices.php?q=ABC&#038;callback=callback125</p>
<p>gives me a JSONP string:<br />
callback125([{"symbol":"ABC","price":68.826522738023,"change":-1.3483844858836}]);</p>
<p>Part 2 : JSONP url</p>
<pre class="brush: java; title: ; notranslate">
private static final String JSON_URL = &quot;http://localhost:81/AliasTestSite/stockPrices.php?q=&quot;;
</pre>
<p>Part 3: Data contract</p>
<p>The same as JSON example</p>
<p>Part 4: Request </p>
<p>As it is cross site, JSONP call  has to be in src of
<pre class="brush: xml; title: ; notranslate">&lt;script&gt;</pre>
<p> element, it is implemented in a JSNI method called getJson. It does a couple of things:</p>
<p>Create a script element on fly, set the JSONP call in the src , inject the new script element into dom.</p>
<p>When jsonp is returned, callback wrapper is triggered, the wrapper sends the json object to Java method handleJsonResponse, sets the call back status flag </p>
<p>window[callback + "done"] = true </p>
<p>the call back status flag will be picked up by a timer, when it is true, getJson will clean up by deleting dynamic script element and call back wrapper functions.</p>
<pre class="brush: java; title: ; notranslate">
/**
   * Make call to remote server.
   */
  public native static void getJson(int requestId, String url,
      StockWatcher handler) /*-{
   var callback = &quot;callback&quot; + requestId;

   // [1] Create a script element.
   var script = document.createElement(&quot;script&quot;);
   script.setAttribute(&quot;src&quot;, url+callback);
   script.setAttribute(&quot;type&quot;, &quot;text/javascript&quot;);

   // [2] Define the callback function on the window object.
   window[callback] = function(jsonObj) {
   // [3]
     handler.@com.google.gwt.sample.stockwatcher.client.StockWatcher::handleJsonResponse(Lcom/google/gwt/core/client/JavaScriptObject;)(jsonObj);
     window[callback + &quot;done&quot;] = true;
   }

   // [4] JSON download has 1-second timeout.
   setTimeout(function() {
     if (!window[callback + &quot;done&quot;]) {
       handler.@com.google.gwt.sample.stockwatcher.client.StockWatcher::handleJsonResponse(Lcom/google/gwt/core/client/JavaScriptObject;)(null);
     }

     // [5] Cleanup. Remove script and callback elements.
     document.body.removeChild(script);
     delete window[callback];
     delete window[callback + &quot;done&quot;];
   }, 1000);

   // [6] Attach the script element to the document body.
   document.body.appendChild(script);
  }-*/;
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.cleancode.co.nz/blog/900/anatomy-jsonp-ajax-gwt/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Anatomy of JSON in GWT</title>
		<link>http://www.cleancode.co.nz/blog/896/anatomy-json-gwt</link>
		<comments>http://www.cleancode.co.nz/blog/896/anatomy-json-gwt#comments</comments>
		<pubDate>Fri, 29 Jul 2011 03:17:57 +0000</pubDate>
		<dc:creator>CleanCodeNZ</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[GWT]]></category>

		<guid isPermaLink="false">http://www.cleancode.co.nz/?p=896</guid>
		<description><![CDATA[Part 1: JSON Ajax Server It is just a simple HttpServlet which streams back a json string And servlet mapping in web.xml is Part 2 : url for JSON Ajax client Part 3: Data contract JSON Ajax client It extends JavaScriptObject. Part 4: request and response]]></description>
			<content:encoded><![CDATA[<p>Part 1: JSON Ajax Server</p>
<p>It is just a simple HttpServlet which streams back a json string<span id="more-896"></span></p>
<pre class="brush: java; title: ; notranslate">
public class JSONStockData extends HttpServlet {

  private static final double MAX_PRICE = 100.0; // $100.00
  private static final double MAX_PRICE_CHANGE = 0.02; // +/- 2%

  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {

    Random rnd = new Random();

    PrintWriter out = resp.getWriter();
    out.println('[');
    String[] stockSymbols = req.getParameter(&quot;q&quot;).split(&quot; &quot;);
    for (String stockSymbol : stockSymbols) {

      double price = rnd.nextDouble() * MAX_PRICE;
      double change = price * MAX_PRICE_CHANGE * (rnd.nextDouble() * 2f - 1f);

      out.println(&quot;  {&quot;);
      out.print(&quot;    \&quot;symbol\&quot;: \&quot;&quot;);
      out.print(stockSymbol);
      out.println(&quot;\&quot;,&quot;);
      out.print(&quot;    \&quot;price\&quot;: &quot;);
      out.print(price);
      out.println(',');
      out.print(&quot;    \&quot;change\&quot;: &quot;);
      out.println(change);
      out.println(&quot;  },&quot;);
    }
    out.println(']');
    out.flush();
  }

}
</pre>
<p>And servlet mapping in web.xml is</p>
<pre class="brush: xml; title: ; notranslate">
   &lt;!-- Servlets --&gt;
 &lt;servlet&gt;
    &lt;servlet-name&gt;jsonStockData&lt;/servlet-name&gt;
    &lt;servlet-class&gt; gwt.stockwatcherjson.server.JSONStockData&lt;/servlet-class&gt;
  &lt;/servlet&gt;

  &lt;servlet-mapping&gt;
    &lt;servlet-name&gt;jsonStockData&lt;/servlet-name&gt;
    &lt;url-pattern&gt;/yourgwtmodulepath/stockPrices&lt;/url-pattern&gt;
  &lt;/servlet-mapping&gt;
</pre>
<p>Part 2  : url  for JSON Ajax client</p>
<pre class="brush: java; title: ; notranslate">
private static final String JSON_URL = GWT.getModuleBaseURL() + &quot;stockPrices?q=&quot;;
</pre>
<p>Part 3: Data contract JSON Ajax client</p>
<pre class="brush: java; title: ; notranslate">
public class StockData extends JavaScriptObject {

	 // Overlay types always have protected, zero argument constructors.
	  protected StockData() {}   

	  // JSNI methods to get stock data.
	  public final native String getSymbol() /*-{ return this.symbol; }-*/; // (3)
	  public final native double getPrice() /*-{ return this.price; }-*/;
	  public final native double getChange() /*-{ return this.change; }-*/;

	  // Non-JSNI method to return change percentage.                       // (4)
	  public final double getChangePercent() {
	    return 100.0 * getChange() / getPrice();
	  }

}
</pre>
<p>It extends JavaScriptObject.</p>
<p>Part 4: request and response</p>
<pre class="brush: java; title: ; notranslate">
// Send request to server and catch any errors.
	      RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, url);

	      try {
	        Request request = builder.sendRequest(null, new RequestCallback() {
	          public void onError(Request request, Throwable exception) {
	            displayError(&quot;Couldn't retrieve JSON&quot;);
	          }

	          public void onResponseReceived(Request request, Response response) {
	            if (200 == response.getStatusCode()) {
	              updateTable(asArrayOfStockData(response.getText()));
	            } else {
	              displayError(&quot;Couldn't retrieve JSON (&quot; + response.getStatusText()
	                  + &quot;)&quot;);
	            }
	          }
	        });
	      } catch (RequestException e) {
	        displayError(&quot;Couldn't retrieve JSON&quot;);
	      }
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.cleancode.co.nz/blog/896/anatomy-json-gwt/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>

<!-- Performance optimized by W3 Total Cache. Learn more: http://www.w3-edge.com/wordpress-plugins/

Minified using disk: basic
Page Caching using disk: enhanced
Object Caching 798/890 objects using disk: basic

Served from: www.cleancode.co.nz @ 2012-02-22 22:03:15 -->
