tag:blogger.com,1999:blog-31989353749943459812024-02-21T02:26:31.072+01:00Coding Instinct"We are survival machines - robot vehicles blindly programmed to preserve the selfish molecules known as genes" - Richard DawkinsUnknownnoreply@blogger.comBlogger97125tag:blogger.com,1999:blog-3198935374994345981.post-37704509691868049092014-05-25T15:32:00.001+02:002014-05-25T15:32:20.291+02:00Grafana video and demo and playground site<p>I have been very busy the last couple of months working on my open source project <a title="http://grafana.org/" href="http://grafana.org/">Grafana</a>. New releases and new project web site. </p> <p>I was recently in the US speaking at a great conference called <a href="http://monitorama.com/">Monitorama</a>. The video is now online:</p> <p><iframe height="281" src="//player.vimeo.com/video/95316672?portrait=0" frameborder="0" width="500" allowfullscreen="allowfullscreen" mozallowfullscreen="mozallowfullscreen" webkitallowfullscreen="webkitallowfullscreen"></iframe></p> <p> </p> <h1>Live demo site</h1> <p>You can try Grafana & Graphite at <a href="http://play.grafana.org">play.grafana.org</a></p> Unknownnoreply@blogger.comtag:blogger.com,1999:blog-3198935374994345981.post-63041164345665305012014-02-23T18:40:00.001+01:002014-02-23T18:42:49.694+01:00Grafana - Graphite Dashboard and graph editor<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://grafana.org/assets/img/edit_dashboards.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://grafana.org/assets/img/edit_dashboards.png" height="517" width="640" /></a></div>
<br />
Almost a year ago I blogged about <a href="http://www.codinginstinct.com/2013/03/metrics-and-graphite.html">Metrics and Graphite</a>. Since then graphite has become an increasingly used and important tool used by all teams at my current customer. Graphite is used in many interesting ways, not only to monitor, visualize and understand a complex distributed system but to understand user behavior, A / B testing analysis and much more. <br />
<br />
The default graphite web is not that great, it is cumbersome to construct dashboards and graphs and does not allow click and drag to zoom in on an area of interest in a graph. As a result of this there are many alternative dashboards for graphite, some that focus on a narrow use case like presenting many metrics, and some that just try to improve on some aspect (like zoom in, client side rendering, nicer looks, etc). Most require editing of json files to construct the dashboards and define the graphs.<br />
<br />
About 4-6 months ago I introducing <a href="http://www.elasticsearch.org/overview/kibana/">Kibana</a> at my customer, an INCREDIBLE search and visualization dashboard for logs. All our application logs are feed into Elasticsearch and become instantly searchable in Kibana that can show trends per application, server, or specific error or message and much more. Kibana is a single page, client side only application that lets you construct dashboards filled with different types of panels that show results of your log queries in useful ways. I will try to blog more about Kibana and how incredibly helpful it is!<br />
<br />
Anyway, Kibana has a great architecture and ui design for creating dashboards and organizing panels into rows and columns. Something I felt was missing in all graphite dashboards. So I started by creating a copy of the histogram panel in Kibana and added graphite support. It was done relatively quickly. With only that step done I already could construct dashboards full with graph panels, click and drag to zoom in, save dashboard and load dashboards to/from Elasticsearch.<br />
<br />
It was then that I realized that this could actually be a pretty great general purpose graphite dashboard. If I focused a lot on graph editing and composing it could fill a gap in the current alternative dashboards.<br />
<br />
So after a very intensive December and January where I coded almost every free hour I could find (in spare time, not work time) I managed to create a graphite dashboard which I named <a href="http://grafana.org/">Grafana</a>. I created a website for it (<a href="http://grafana.org/">grafana.org</a>) to showcase its features.<br />
<br />
One of its many signature features is a graphite expression parser that allows better editing of functions and parameters. It also makes understanding and reading graphite target expressions much easier.<br />
<br />
Example:<br />
<pre>alias(summarize(sumSeries(prod.apps.touchweb.*.timers.requests.startpage_index_get.count),'1min'),'start page')
</pre>
<br />
An expression like the one above is in Grafana visualized as:<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhtTsnzV6rTiBFc4QglsNxlGtHRnfp4OWZqkLKDg9J6M4uzCJeAkJATX2IpvFFm2-7C4avp7o74PmzE7UDOoXOaxKO_YZFV1g_GMtcfUtevbLCHo9Kf7BHZEEtAs1XhsgxNOnuxHxfh6uY/s1600/grafana_target_funcs.PNG" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhtTsnzV6rTiBFc4QglsNxlGtHRnfp4OWZqkLKDg9J6M4uzCJeAkJATX2IpvFFm2-7C4avp7o74PmzE7UDOoXOaxKO_YZFV1g_GMtcfUtevbLCHo9Kf7BHZEEtAs1XhsgxNOnuxHxfh6uY/s1600/grafana_target_funcs.PNG" /></a></div>
<br />
<br />
<br />
You can click any metric segment to select alternatives, click on the function and edit parameters. You can click the pen and edit the target expression in a text box if you want.<br />
<br />
Since the initial release of Grafana the response and feedback has been amazing. Over 1238 starts on github, 91 closed issues, 41 open, 9 releases with many fixes and new features. In Grafana 1.4 which was recently released I added support for annotations.<br />
<br />
View this video for a quick intro and a tour of the features in Grafana.<br />
<iframe allowfullscreen="" frameborder="0" height="347" src="//www.youtube.com/embed/OUvJamHeMpw?vq=hd1080" width="543"></iframe><br />
<br />
<br />
Github project: <a href="https://github.com/torkelo/grafana">github.com/torkelo/grafana</a><br />
<br />
<br />
<br />
<br />Unknownnoreply@blogger.comtag:blogger.com,1999:blog-3198935374994345981.post-52003284443507165722013-03-21T09:23:00.001+01:002013-03-21T09:23:46.786+01:00Powershell and psake background file watcher<p>Your starting a new web project and you want to use sass/less for css and require.js for javascript dependency management. Maybe you want to use jslint/jshint to verify your javascript syntax and csslint to verify your css. To make this a smooth developing experience you want to run a background file watcher that runs tasks whenever you change a file. </p> <p>So when you modify a javascript file, all js files are verified for syntax, require js optimizer is executed to traverse your dependency tree (and spits out combined files). Maybe javascript tests are executed on the fly as well. Same thing when you modify a sass file you want the generated css to be created behind the scenes automatically. </p> <p>I have used <a href="https://github.com/psake/psake">psake</a> (Powershell build script framework) for almost all my build scripts lately. I am not a big fan of Powershell, at least the Powershell syntax. But psake makes writing build scripts a lot easier than msbuild ever has. </p> <p>I wrote a little powershell utility function that sets up file watchers that when triggered executes a psake task. </p> <p>Example:</p> <pre>task Watch {
WatchFiles "$scripts_dir" "*.js" "JsCheck"
WatchFiles "$touch_test_proj_dir\JavaScript" "*.js" "JsCheck"
WatchFiles "$styles_dir" "*.scss" "Sass"
}</pre>
<p>Whenever a js file is modified in the scripts folder (or subfolders) execute psake task JsCheck (this task will run jshint, require js optimizer, and javascript tests). </p>
<p>Here is the gist for the WatchFiles function: </p>
<script src="https://gist.github.com/torkelo/f770dd62d026ebbe4d13.js"></script>
<p>The only trouble I had was dealing if duplicate events, the .NET file watcher class is a little buggy, generating duplicate file changed events which required a little hack to filter them out. </p>
<p>There are many file watchers for node / grunt but I found them a little buggy and CPU intensive. And by using powershell and a regular .NET file watcher does not block the console, you can still use the Powershell console that is running the file watchers. </p>
<h2><strong>Growl<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjQjbQ-bwdQ9zcr6Y5-NcPeKPgNtrdiU0ybH5_CjLIqkI_RS61L6TxOImFf025-EvqJJU6_PmglCQkaTtDXrbm3mze05cM2X93sejZOoC5UTEhdY0uRs9vaiwGBam2MAUWif3hnqdr2-do/s1600-h/image%25255B5%25255D.png"><img title="image" style="border-top: 0px; border-right: 0px; background-image: none; border-bottom: 0px; float: left; padding-top: 0px; padding-left: 0px; margin: 0px 50px 0px 0px; border-left: 0px; display: inline; padding-right: 0px" border="0" alt="image" align="left" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEifPQPanKYICXinwcmIbzxjQme4R6olrIGBNsA_Lk9pD6fSLVe8qsjyq4XkwVdQNwQ2P9IX9_0YQE5yxpia5hM6IXIde2sYY7QlmwCnriNoSmQWR5HbM1rBn0W63C2IlCL_P7wnjW9nMtg/?imgmax=800" width="299" height="139" /></a><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEid2WahYZ4zXmwL-jV5OGLwRFVCmAeos7TgccYQDe3tWdnbu_5C8AtcNq7TyCNHB-TaYjMKscb2mgTWfkUn2irvCUNPuWfiLgU5MHtMLJmzca-YKW8cXb8S0rc-zj-9fgeqf9pvrY68NLk/s1600-h/image%25255B13%25255D.png"><img title="image" style="border-top: 0px; border-right: 0px; background-image: none; border-bottom: 0px; float: left; padding-top: 0px; padding-left: 0px; border-left: 0px; display: inline; padding-right: 0px" border="0" alt="image" align="left" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhMkR4Q_xEvdWeVtP0SmJAi-3QLYR693VAZjfUrn_70vGS5QGt-cIKqGm8P6-Bl66-4RuW3ibsFHcpilpbsC6DXA6mZaeQU404bACSLlao0c6JSEo4eTupG8iSjlB5V7mq4RvjFm3erK_0/?imgmax=800" width="293" height="139" /></a></strong></h2>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
<p>Another thing that is very nice to have when you run background tasks is notification when things go bad or good. This is where <a href="http://www.growlforwindows.com/gfw/">Growl for Windows</a> is handy. If a powershell psake task throws an exception I can call growlnotify like this:</p>
<pre>function growl($title, $message, $icon) {
if (Test-Path "C:\Program Files (x86)\Growl for Windows") {
$iconUri = ([system.uri] "$base_dir\build\images\$icon.png").AbsoluteUri
Write-Host $iconUri
& growlnotify /t:$title /i:"$iconUri" "$message"
}
}</pre>
<p>That way you instantly know when you have missed a comma, broke the code style guidelines, wrote the wrong require js dependency path etc. </p> Unknownnoreply@blogger.comtag:blogger.com,1999:blog-3198935374994345981.post-86944992474283496832013-03-20T17:01:00.001+01:002014-02-23T18:44:08.065+01:00Metrics and GraphiteI have been spending a lot of time thinking about and playing with Metrics. It started as an innovation project at my current customer but I have had a hard time not to think and work on it on my spare time. <br />
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgPyA9KGcFNxc-4CR-kDUpK8SjQ-K35as4sdR6l-PTaPs7enZQpqpwMwo38qIbwLN-n-sxThDngbsUjLZUhavqxfZ_Jcpl9EgajaQnyBQWIqmK8nc5z0rnREUpHUxqnytLgDyQIaYyzcks/s1600-h/image%25255B4%25255D.png"><img alt="image" border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEijvqVTit9sJ7Ym4Q5SjUgAKWEOUhkx6HvkPpO2YbZ63vwKYSOZgorb5faqK6el4mH2SweMKl52ifkjLHs7XUIPcdwhelQwH9AMUiONMSiD4Vb1SqO-u7eBwIJwb8oRdaX1i0yqocObEbY/?imgmax=800" height="527" style="background-image: none; border-bottom-width: 0px; border-left-width: 0px; border-right-width: 0px; border-top-width: 0px; display: inline; padding-left: 0px; padding-right: 0px; padding-top: 0px;" title="image" width="917" /></a><br />
It all centers around a small metrics framework that pushes application performance timing, health, and most importantly business counters and metrics to a backend system called <a href="http://graphite.wikidot.com/">Graphite</a>. Graphite is a real time scalable graphing system that can handle a huge amount of metrics. You can define flexible persistence and aggregation rules, and most importantly you can plot your metrics in graphs using a large amount of <a href="http://graphite.readthedocs.org/en/1.0/functions.html">flexible functions</a>. Functions that can combine metrics, stack metrics from different servers, calculate percentiles, standard deviation, moving average, summarize, filter out outliers, etc. <br />
I wrote a small metrics framework that can handle counters, gauges and timers. These are aggregated and sent to Graphite via UDP every x seconds (depending on how real time your want your metrics). <br />
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEib5m0i_Q8JANkPhXdeR0CQYwS7EYPaMoQF-vigf1UExKv2bNEdGoR0zQe5WxWSFMDkN0zN_eGOT_ye6TuZ1k-ZICNlepd-CGWodlomB0_p2bc-Su4WmZ0VQklJidz2psgdXz40VFkoY7c/s1600-h/image%25255B9%25255D.png"><img alt="image" border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjpsJqzg_GKp-IxY9gknTwL2Fbcia8nNXh4dD488c41Mg3pywso5Lxd7SaVxP1qEp8Yjj0DX0PphryOsqaxtbRS-DgmKXbcjYnKsEvWBFj-X4qfVOBXcs2ZA0epOIKEhhvq4FeSkpkEtqU/?imgmax=800" height="41" style="background-image: none; border-bottom-width: 0px; border-left-width: 0px; border-right-width: 0px; border-top-width: 0px; display: inline; padding-left: 0px; padding-right: 0px; padding-top: 0px;" title="image" width="390" /></a><br />
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgNbhcPxjed-RgIqB2peL0YaeysaaFmDGV9gt4ppkmp1YW2QYE3xv3cbezyQMyYAnEV5YgXlMpUhK6VemApw7xvbD5RzdfDfNlVYjpooq1vzUclK-q2vAggKsDgyn7uNgJiEOd5-DJeqZo/s1600-h/image%25255B19%25255D.png"><img alt="image" border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEho7EU-Zgu3qLv0Cp0paPNsonuE8q7XLsAvbAD9QqvHXXPAB6N-AGAtVMSsjlbW-79eNg9BBDr7tvBXODZQa0X1osNrkyeK6Xuh1H5yzWQi1-lHdJCUcoZvlMyBDaPofyIUNlDwcFGfcm8/?imgmax=800" height="98" style="background-image: none; border-bottom-width: 0px; border-left-width: 0px; border-right-width: 0px; border-top-width: 0px; display: inline; padding-left: 0px; padding-right: 0px; padding-top: 0px;" title="image" width="482" /></a><br />
Examples of how to increment a counter and time a lambda function. The real power comes from how graphite can aggregate metrics from all production servers, compare or summarize them. <br />
Example:<br />
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg5QUF_QuS85TAEtJFJCtMVSE1e07ic4l6ThyeNnRnGSlVbBmPiGxEuKnUB_aoS3vkRjwbGE1x0pQhkMeeYmRgEKGjgjJe33YeDSezyaTBs_s-yZu4jc8FZ7OpoymEuWELGDXEsl6hkih4/s1600-h/image%25255B27%25255D.png"><img alt="image" border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhkLUjUeEBvxvF0JV8ovxWWNZRE2-t2PajZMHOEWGhtzKou9a4SeswiPw-9cyUKyspTYzDpB-wDgzk2IMimD9jelcEVVABV6DOsYqfJFcspH19cb1YFeEuij8zntOlUTNPliegqAMk8m0U/?imgmax=800" height="191" style="background-image: none; border-bottom-width: 0px; border-left-width: 0px; border-right-width: 0px; border-top-width: 0px; display: inline; padding-left: 0px; padding-right: 0px; padding-top: 0px;" title="image" width="640" /></a><br />
<pre> aliasByNode(test.servers.*.gauges.cpu.processor_time, 2)</pre>
With a single line like this we can stack cpu usage on all test servers (notice the wild card in the above expression). New test servers would automatically appear in the above graph. <br />
You can also aggregate metrics from different servers like this:
<br />
<pre> sumSeries(carbon.agents.*.metricsReceived)</pre>
Graphite gives you a lot control of how to persist and aggregate metics in the backend as well. <br />
storage-schemas.conf
<br />
<pre>[stats]
pattern = ^prod.*
retentions = 10s:6h,1min:7d,10min:5y</pre>
This translates to: for all metrics starting with 'prod' , capture:<br />
<ul>
<li>6 hours of 10 second data </li>
<li>1 week of 1 minute data </li>
<li>5 years of 10 minute data </li>
</ul>
In another config file you specify how metrics should be rolled up (for example how 10 second data should be rolled up / aggregated to 1 minute data). For example you want counters to be summed, and timings to be averaged. <br />
You can also have a graphite aggregator that aggregates and persists aggregated metrics. For example most of the time you don’t want to see business metrics split per server so to make it easier to plot graphs you can have graphite create and persist an aggregated metric for you (this could be done by graph functions as well). This is can be done using format rules like this: <br />
<pre><env>.applications.<app>.all.counters.<metric_name> (60) = sum <env>.applications.<app>.*.counters.<metric_name></pre>
Given metrics with names like:<br />
<pre> prod.applications.member-notifications.server-1.counters.order_mail_sent
prod.applications.member-notifications.server-2.counters.order_mail_sent
prod.applications.member-notifications.server-3.counters.order_mail_sent
prod.applications.member-notifications.server-4.counters.order_mail_sent</pre>
Graphite will every 60 seconds summarize the counter received for each server and generate a new metric with name name “all” instead of the server name. <br />
Graphite is bundled with a web application that lets you view and create graphs and dashboards (shown in the first screenshot in this blog post). The standard graphing component utilizes image based graphs. There is an experimental canvas based graph as well but it is not very good. Luckily there are a great number of alternative frontends for graphite that support live graph dashboards that use canvas or svg graphics. I like <a href="https://github.com/kenhub/giraffe">Giraffe</a>, but its styling was not very nice, so after a quick css makeover it looked like this: <br />
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh90Y78gWfOb9QB12Mh0l1av33mXm637q_3B2wiAFU-xrMFdjs3m7j631VJcC0joM_wT06daL5BPgIxMXzymUHzM49_PoCB548ushOy6JmB0kXjaxj0DJng_3Vpq77MbVgokJzuXXtADi8/s1600-h/image%25255B32%25255D.png"><img alt="image" border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgj4-r1x-zaaiUMQ8Ar431qWeL8Q_hvpjp4HhQ8THdOCBI59kMXrRKDX5fXmFoPeVdngQssQ0v9oxkvXunhkAmns1c_fn7xPhUtYn6kHtah55_B_BhDkeoiW5IjnQl_NlU-6y-oDP7dL2w/?imgmax=800" height="383" style="background-image: none; border-bottom: 0px; border-left: 0px; border-right: 0px; border-top: 0px; display: inline; padding-left: 0px; padding-right: 0px; padding-top: 0px;" title="image" width="519" /></a><br />
With Giraffe and other svg/canvas based dashboards and graphing engines you can get real time moving graphs (graph data is fetched from graphite HTTP API).<br />
There is a large community built around Graphite, with everything from metric frameworks, machine metric daemons, alternative frontends, support tools and integration with monitoring systems like Nagios and Ganglia. <br />
Graphite is not easy to install and setup (do not even try to get it running on windows). And it takes time to understand it’s persistence model and configuration options. It is extremely specialized to do one thing and one thing only: persist, aggregate and graph time series data. This specialization is also it’s strength as a single Graphite server can handle millions of metrics per minute and store them in a very optimized format (12 bytes per metric per time interval). So 6 hours of 10 second data is just 2160 bytes per distinct metric. <br />
Lets say you have 10 servers with 2 applications, each application sends 200 distinct metrics (business counters, performance timings, operation metrics, etc) every 10 seconds. The storage required for 6 hours of data: 10 (servers) * 2 (applications) * 200 (distinct metrics) * 6 (measures per minute) * 60 (minutes) * 6 (hours) = 8640 KB<br />
Metrics older than 6 hours will be rolled up into one minute buckets which will reduce storage to 1/6th of the above. <br />
Links:<br />
<ul>
<li><a href="http://graphite.wikidot.com/" title="http://graphite.wikidot.com/">Official graphite site</a></li>
<li><a href="https://github.com/etsy/statsd/" title="https://github.com/etsy/statsd/">Statsd</a></li>
<li><a href="http://codeascraft.etsy.com/2011/02/15/measure-anything-measure-everything/">Measure anything, measure everyting</a></li>
<li><a href="https://github.com/danielcrenna/metrics-net">Metrics.net</a> (.net metrics framework based on a java metrics framework, the C# port does not have graphite writer, but the java version has)</li>
<li><a href="https://github.com/ewhauser/OstrichNet">Ostrich.net</a> (port of twitters ostrich metrics framework, does have a basic graphite writer), I used this framework as inspiration for the one I wrote</li>
</ul>
<div>
Update (2014-02-23): </div>
<div>
I have since this post created a new graphite dashboard replacement called Grafana, visit <a href="http://grafana.org/">grafana.org</a> for more info!. </div>
Unknownnoreply@blogger.comtag:blogger.com,1999:blog-3198935374994345981.post-14200270591644902682013-03-19T09:33:00.001+01:002013-03-19T09:33:35.727+01:00ASP.NET MVC Folder structure<p>I have been working a lot with <a href="http://nodejs.org/">node.js</a> lately and some <a href="https://github.com/NancyFx/Nancy">Nancy</a> (low weight .net web framework). I love how explicit they are in the HTTP interface you define and how they allow you to structure your application as you find appropriate (for example around features or feature groups). </p> <p>Node.js example: </p> <p><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhbCMQiCmIqYy-HBJCNvwWcCLWAKfmPKspDH1kmrmaae1yTxHUV0J2ybh_SRJ67QciQu9rpv-oHgBrrmqPLAHoFGsackXQogVIfn4Edy2mEULN2yBaZHCDmpWJP-VXAzi_ycbJSUxSMygI/s1600-h/image%25255B5%25255D.png"><img title="image" style="border-top: 0px; border-right: 0px; background-image: none; border-bottom: 0px; padding-top: 0px; padding-left: 0px; border-left: 0px; display: inline; padding-right: 0px" border="0" alt="image" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj56GCujjX9un6Gl4LkWVozNB8LF3GZ68SZ82S1HynQRCybcKtBquOOrmgUY0bneBa6b3HBFr7he-Zxo0oF2nFKz7Xqj681tSYO96wtQuDLwOAZCurUy1JLP0gjKKZ0JGESuV7OC-hhl5s/?imgmax=800" width="724" height="134" /></a></p> <p>Nancy example:</p> <p><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiZ7LflScl5v58jWQOrjujr9hBuUkdP_9uk33Mb1Ba8MDUZChfbZrODJTOHjhYSnywkjV9HRV9jdcj1vwRYRxlDtFVcGpdJVT0EuJRzMDsFxzzOc7r8_GYgmHtLpVGevuLNgMfaAR5mLl4/s1600-h/image%25255B10%25255D.png"><img title="image" style="border-top: 0px; border-right: 0px; background-image: none; border-bottom: 0px; padding-top: 0px; padding-left: 0px; border-left: 0px; display: inline; padding-right: 0px" border="0" alt="image" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEivvaH_YjkF62uEfRX05b-ZxsPHuiztjJBY3oxfg6-ACKaaFqyqxqgY9jae1Ws-qodotSG-4bbzWZLmnSY9OXnrAuiqWxuWSKGhSgnpft3RPPb_ciUmETe4-xVz7HpTE26P065XmIiBHJk/?imgmax=800" width="763" height="401" /></a></p> <p>They give you full control how you structure and organize http handlers (code, folders, view locations). So when I now started a new ASP.NET MVC project I am struck by how awkward I find the default mvc folder structure and url –> controller routing mechanism. </p> <p>Default ASP.NET MVC project folder structure:</p> <p><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEimnTJZOAVfp9ob36Hpiv5Vvt1o1fbj9dWtK2WexGFbwCQj6QoRTHBI3OkgmnQ2WXc-O_vUdWtlLdJLVqHTStofxT8tijV7lMr9AbNSWGquVtUsbziXO8t4Ln61c13DqLvJvmfZumba59o/s1600-h/image%25255B16%25255D.png"><img title="image" style="border-top: 0px; border-right: 0px; background-image: none; border-bottom: 0px; padding-top: 0px; padding-left: 0px; border-left: 0px; display: inline; padding-right: 0px" border="0" alt="image" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEirCiH1fcv9C-OO3I-e3xNjpgXQo7JcOJyuAVESeg_CpD-2uHuL1V8XjlRzDJLszHEQ-1_A1Dh5PV8KmoB76h33f1fB350NV1F_lvzM4oP7JDPMYMA6iZc2isb4x5leXFF4Wd0ycsI-tWk/?imgmax=800" width="272" height="326" /></a></p> <p>Having Controllers, Models and Views in the root folder feel strange to me, they are basic building blocks in mvc projects and have nothing to to do with features or the application domain. ASP.NET MVC has support for areas which allow you to organize your code around application domains or features but the default controllers and views cannot be in an area folder. Try for example to have an controller in an area be your default route and it will be looking for views in the default root view folder. </p> <p>Luckily MVC is extensible enough to partially solve this. We can move the default controllers, views and models into a “default” area folder, this won’t really be an area in the same sense as other areas. Because we will trick ASP.NET MVC to look for “no area” views and controllers in this folder instead. </p> <p><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgY7XWFqHKsVqqly_vU8-8AffegU7xQYKm6pnfY1ejZnpY83_PB3JqCzAf4yrkDCi2AJAmx8tmZ6GgzSZqXdKLpHOqkj-5oMIzS4qKCILWzR4P9XB4xdXlBLQ0wI61RwHo93PqBBGB6Qe0/s1600-h/image%25255B21%25255D.png"><img title="image" style="border-top: 0px; border-right: 0px; background-image: none; border-bottom: 0px; padding-top: 0px; padding-left: 0px; border-left: 0px; display: inline; padding-right: 0px" border="0" alt="image" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjUQd3ilg28nwlnObC3Ni1Rx6920wXYtnLrs7PfsltFKaiuSGT_VDd6uDWK3XD9NA08Rsvu_UK1T8PecTJwVD7NArP8mR16ug2WLGMYzHhjjKMn4RlAbx66tPA-CJHKjgWEQujw9sfkU3I/?imgmax=800" width="656" height="471" /></a></p> <p>By removing the standard Razing engine and instantiating a new we can modify the view location formats to make razor look for views for the “no area” routes/controllers in the default folder inside the areas folder. Now we can clean up the root folder structure. </p> <p><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhReytT6WX7SULK2MIj0r3zAS2v1cg6mAGKXykwkQMK5l0UmgEPPWZZl8YnJwR9uLG2H1yTNq9l22t2f5v-G1hASmJntLjXIl2BMubmz5xz70DBkcZPNQ03zeHW9Nn4RR8he2ohE9zLSdE/s1600-h/image%25255B26%25255D.png"><img title="image" style="border-top: 0px; border-right: 0px; background-image: none; border-bottom: 0px; padding-top: 0px; padding-left: 0px; border-left: 0px; display: inline; padding-right: 0px" border="0" alt="image" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj4pmbGkk85cWr-G5JNPMQfk2ggjYIhqpDLc-qLi8TXiBBOCTU0hNw6QC3bCWYlJfJ65Gts2t3huE7URXBXMX3wzWO0-DbpF8SvQxWGQnXfiTKWhLNCo2DcqSEL8QuPgGwIb4FlRp1jKT0/?imgmax=800" width="245" height="238" /></a></p> <p>This feels so much better, we can have default views and layouts in the default area folder, maybe a few controllers but preferably every controller should be placed within an area (feature / feature group). I still find the url –> controller action routing obstructing the clarity and simplicity of HTTP, but it has it uses. Also the whole area feature in ASP.NET MVC feels tacked on and not well implemented as they complicate all url routing and url generation. When using areas Url, Action and Form helpers need to be told which area the controller you are referring to resides. </p> <p><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgo8RgvRyjOXNf8DzlLnA9tR9OcZmcfFOTG6WjCjBLilU6diWHTq2aSrNotKOxVtAA9Gn3apwYnmMc15VOEqhL1zzMUfnmDwxBmrir1rfMjivycPwas1S9JJbdmIzz2nhZ1hRpfRjwpPlw/s1600-h/image%25255B31%25255D.png"><img title="image" style="border-top: 0px; border-right: 0px; background-image: none; border-bottom: 0px; padding-top: 0px; padding-left: 0px; border-left: 0px; display: inline; padding-right: 0px" border="0" alt="image" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgvD40MvYuJedxPKGiAe4akzKqaCSNQfy_PCKSrfrSeCzqmd56gnlJiQJmkBJg6Dko-NFWUDLP18cIKdh2ntF_2czpj8dDqOPHi7pT5Qv9ZjY3uP9qJ9tDcQDoVbrUJACryTnfBdAJQXME/?imgmax=800" width="581" height="40" /></a> </p> <p>This can be overcome by using smart lambda based (typed) helpers:  </p> <p><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh1dcHvmdIQ7xEzgzg-1PCfL3KZWBpn2v_qdk00WnffIgRnvlavgvKttiOMkAjCRvf_26btQ0U9VXWfJoSW1P7URPdGqt_5kBpESBDWIGUowHWOh-UrL7G0fD0Fdah7OjW1Jbfh6nvfs1s/s1600-h/image%25255B36%25255D.png"><img title="image" style="border-top: 0px; border-right: 0px; background-image: none; border-bottom: 0px; padding-top: 0px; padding-left: 0px; border-left: 0px; display: inline; padding-right: 0px" border="0" alt="image" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhzKBs78nYi8K-6h-0QoGRJgO103VsZIqBRGHJKuFys9Vi47qAcjz1eMeZeMPbpgC80Ti8KmxEugqukmzR-CyDGbxoNruhNO4qCW7PE9i3E_bKIb0cno3cwSEaHIOHcy4RUg8Qztq-rFgk/?imgmax=800" width="505" height="25" /></a></p> <p>But sadly no such helpers come included in vanilla ASP.NET MVC (they did/do exist in MVC Futures and MVC Contrib if I remember correctly). Anyway after this small change I feel a little better using ASP.NET MVC, still miss node.js though. </p> Unknownnoreply@blogger.comtag:blogger.com,1999:blog-3198935374994345981.post-26922779686969356802011-12-22T10:34:00.001+01:002011-12-22T13:47:47.286+01:00Testing item values in lists<p>It is not uncommon when when writing tests that you want check that the correct items with correct data exists in a list. You can do this in many ways, most of which I have found to be problematic at times.</p> <p>Example: </p> <p><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgzj7tmcs_VY6mnIfLa7bhmvC0ldp4WI72c4TMKLzhxBzmCbOFc-9jmSrTFwWkDSC39iFCRagmdMiq3mDGOzCOhuyyqGDrfvbj0Hb95vCpkdL4zDzdS6gDIbMXSi5w1cLefKWKLxYR9zYk/s1600-h/image%25255B14%25255D.png"><img title="image" style="border-right: 0px; border-top: 0px; display: inline; border-left: 0px; border-bottom: 0px" height="170" alt="image" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjaPi6mlPVORAVmbrDQXJOfwjnFkRC8DMFsS-3uN1yg4BYMktsxuRs5gGlf4ybOjsaoBf_j4uQW_-LtmBoH82gj8I5VrPqIPOuvnNE3kocSntjOvE3pQvx2hL96sjCKVCkd3syQiBwxWi0/?imgmax=800" width="360" border="0" /></a> </p> <p>This approach forces the item order to be the one you expect. This can be overcome by sorting the list before. Another approach that I do not like, but have seen a lot:</p> <p><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgdA4cCxCkVbGkZ_JnQgT_Pf51ftJR4mg8_wbLQlpGRSUYiCoFzQElNWvwfRmv5LGaINNf_vh95Bzl2SIx6OgzbxnQur_Gzg4N9tR1fUZtpYGQzk48h8eEjXIodIMnLvUKVjM25-_IX0lE/s1600-h/image%25255B19%25255D.png"><img title="image" style="border-right: 0px; border-top: 0px; display: inline; border-left: 0px; border-bottom: 0px" height="111" alt="image" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgRFIi5FsvWtu7sWnEGo4coYmweNgg95qTG4wImKMoS1-6YsvxvFVWnF2si_3RLcrO1HaAz0KHzj9mTDCH6dcAgVWXNuIgtqePGwMMIiI06Arxmopdf6IayXt318jGDBq7Sxf-RJnzF2bU/?imgmax=800" width="715" border="0" /></a> </p> <p>This approach do not care about the order of the items, but will not generate instructive errors. When the test fails you get no hint of which property was wrong, was there any items in the list, was it the project number or the quantity that caused the mismatch?</p> <p>I have been working on a reporting story that denormalized a big document into a single class with a large number of properties. This required a number of tests that checked the items and their generated properties. However I wanted a nice syntax and good instructive test errors that explain what property caused the mismatch and what alternative values that property was found with.</p> <p>I set out to create this in a generic way to be reusable in other tests. And ended up with this:</p> <p><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEigDFk9QLAWFKG0Ff2z9O9Jfo-FDm0hPyquMRNIjl9_GTY3gaUlXV-Xf8pOupx-uIJOCbcQZzdRB5ybl4vqWusZDtPS4WfNjmfGJinaUscATgPJ299M0xtWj4cz_yUkSZ3dRwrQYSqaKwU/s1600-h/image%25255B29%25255D.png"><img title="image" style="border-right: 0px; border-top: 0px; display: inline; border-left: 0px; border-bottom: 0px" height="122" alt="image" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjtRVUTXm2T1SUsAxucAa5XVrEXsVmrqRC0X40DGwt4fYSRD9Tm09_5XDp3Y1xmBu5LmaR_S1eUwUDgZPC3Hh7qkFzRti-94iIBj8Gg8R7jE78Ij_yDriWBxHkahNlI9mu6_dsT-i3uoOg/?imgmax=800" width="747" border="0" /></a> </p> <p>Lets say there only exists an item with project number 123 and placement “Front”, and maybe 10 rows with other project numbers, then the fist line would throw a test fail like this: </p> <p><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhtZzZPxyW2sYubnopU16PFmBgv3ZQflleqR7qMBaJXMHDTDh7ivIabWnUkuz7b0c6U1ki6o_rZkN0EJqnvwqddbAZnxQ5ebTspTu6IQuTbKNid3CFWj-dEmaw5pHsAxzlFMyrfQlTfOYI/s1600-h/image%25255B39%25255D.png"><img title="image" style="border-right: 0px; border-top: 0px; display: inline; border-left: 0px; border-bottom: 0px" height="105" alt="image" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh1CqFnkrDyfyKiSf8bx9wk62yGsACZXigpibcqIsoNh6XT5QEifLmke3djtBU0sa5FyMc7aPptukacxDgsHk1CdiwuDYcR234zTrw8PCaXrB8ozEMbjTMVvRbU-L3YD9bk6_2yFJSiU9M/?imgmax=800" width="455" border="0" /></a> </p> <p>The important point here is that not only do I get what property caused the mismatch but also the alternative values for that value given the project number filter of 123 (that is I do not get all values for the mismatched property).  </p> <p>This becomes useful when you have many properties and multiple rows you want to check. Because all filters that results in hits will be applied, and all that give no hits will not be used, so you can present an error that includes the mismatches, but also found alternative values for the mismatched properties. I am not sure if I am making any sense.  </p> <p>Maybe the filter logic will help, CollectionTestHelper:</p> <p><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEihYGFwls-_ANz778rPIFYLSrZQYjeqyf8qtgw57qeq-Z7bFghOHoAOSlviTnrg58i9Hq1uLF-8GaQLglwzMiQXSLMz2neQIKWBqp8aili-TAx9_JHw1SaaWdmXr_EIYqapLNKEVyeSXto/s1600-h/image%25255B45%25255D.png"><img title="image" style="border-right: 0px; border-top: 0px; display: inline; border-left: 0px; border-bottom: 0px" height="354" alt="image" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhGAwouNvRysyWASi6pdwRsJGtynLRTFs9hyrXbamjFbjDw23bDcmFmmKV4JuBWV7F8to2MsLzK5vx3gKvlhv2iqExWSk3ONawZpas6KTPBNuQD0KroxnhAW3pGMAKuPEIKDxkMrv-HXHM/?imgmax=800" width="659" border="0" /></a> </p> <p>I try to filter the list using the property function and value, if no hits are found I revert to the “unfiltered” list and add the property expression and value to a dictionary. I then revert to the “unfiltered” list, which is a bad term as it is the list with all matching filters applied. </p> <p>The complete code for the CollectionTestHelper look at this gist: <a href="https://gist.github.com/1509663">https://gist.github.com/1509663</a></p> <p>In one case I made a helper method in the test class that has 14 optional parameters, so I can get this syntax:</p> <p>Example:</p> <p><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiwW9CQ0m4D_TxFJqn6DRJoT6ccuLCw4XmJS_hgcnxZjOe6rzagtfYFYjbYusVlh4jski23E3YBhyphenhyphen2VnE2do3ZSnL1pV92olrQwvHn7-3pZt3fxEmk3aSLstVxJ8AX8ppWIBnHROmxOGIo/s1600-h/image%25255B24%25255D.png"><img title="image" style="border-right: 0px; border-top: 0px; display: inline; border-left: 0px; border-bottom: 0px" height="122" alt="image" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgWCahT98zzioqn0rMh1GHw1OGkvlWkXJPQJr2th-LAz9b775zHcrm2KmwdCQNSAxXODm27ybtkeIBiY0LqcNSk4kK6DinN0tnsieBRaO-nqiZZwdKMM_KI30CsOwmMBT6ckvZ_mhOv7Ps/?imgmax=800" width="612" border="0" /></a> ‘</p> <p>Optional parameters are great for making tests and setups clearer. </p> Unknownnoreply@blogger.comtag:blogger.com,1999:blog-3198935374994345981.post-49383322486357088742011-04-14T15:45:00.001+02:002011-04-14T15:45:43.205+02:00Queries & Aggregates & DDD<p>What i like about command query segregation is that it allows you to clearly distinguish between operations that modify states (via persisting aggregates) and queries that only read. Reads require very little business logic or behavior so why do many system still handle reads the same way (architecturally speaking) as writes? Why do reads need to pass through a domain repository, a domain entity and (god forbid a domain “manager” class), then only to get mapped to a DTO and later a view model? </p> <p>Realizing the big difference between reads and writes has been the biggest change in mindset for me the last year. When you realize this you can create different architectures and layering for reads and for writes. </p> <p>For example queries can be handled like this:</p> <p><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhDqtCr5WW06Q0eMIJODv52OvifKA_U_LuoP4ZeEWJMEdHj3E09weKIZ76GXLDHDNOJpehR1Fq58lxP1Nx0llEMA7dhEGM9Lv2csd45nz7pXOZYVMAMMNl_7Xc-6gwo5MnnEBKAgNY6uK8/s1600-h/image%5B10%5D.png"><img title="image" style="border-right: 0px; border-top: 0px; display: inline; border-left: 0px; border-bottom: 0px" height="527" alt="image" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhxRKqB72PV_anIAn8OKqw-Ei2qOO8EhWTstvxAt5BQMDNxAZWdDoP5cRUjZZ5t8zQV8fFLD8mt4P2JZzHiAlx1yKG8Ec62EEQ8Wmg8TaRIRlhrW3hhDFbcQAA5YQ8fKk61OLJVZJi2HxI/?imgmax=800" width="723" border="0" /></a> </p> <p>The above query handler needs to return product details and the order count in which that product exists. No behavior, no business rules, no domain entities or aggregates needed, just data that needs to be returned to later be displayed in a GUI. So no repository needed! So how do you test the query handler? The same way you would test the repository method, using a database test (preferably in-memory). </p> <p>If you read a whole aggregate in a query handler something is most likely wrong, aggregates should only be read if you need to perform a command (modify it’s state). </p> <p>Separating between read models and write models makes a huge difference. Write models will be modeled using domain driven design, aggregate roots should correspond to transactional boundaries. Aggregates should not require a change just because we need to display more data in the GUI.  I have seen domain entities filled with relationships and properties only there because some part of the GUI requires it. </p> <p>If you use your domain aggregates when reading and displaying data it can lead to a huge amount of unnecessary data in the aggregate, data that is never used by the business rules but is still being read from the database on every write operation. </p> <p>There is an interesting consequence in event sourcing, in that it allows you to create a domain model state that only contains state (data) that is necessary for the behavior, if you have data that is only required for reads then you can ignore that data in your aggregate (it will be stored in the event store, and in the read model). </p> <p>I am only a novice when it comes to Event Sourcing and CQRS but I find both incredibly interesting. I like how they both create pretty big limitations that force you toward something good, and it makes you think more are about domain driven design, about boundaries and responsibilities and about intent. I would love to get the chance to try event sourcing and pure CQRS (separate read/write model and persistence) in a real project. </p> <p>For more on CQRS:</p> <ul> <li><a href="http://cqrsinfo.com/">http://cqrsinfo.com/</a>  (there is a nice and short 6 hour long presentation by Greg Young there!) </li> <li><a href="http://martinfowler.com/eaaDev/EventSourcing.html">Martin Fowler on Event Sourcing</a></li> <li><a href="http://codebetter.com/gregyoung/2010/02/20/why-use-event-sourcing/">Greg Young on why use event sourcing</a></li> <li><a title="http://vimeo.com/19428577" href="http://vimeo.com/19428577">Unleash Your Domain (Greg Young Talk)</a></li> <li><a href="http://elegantcode.com/2010/02/05/cqrs-event-sourcing/">Mark Nijhof on Event Sourcing</a></li> </ul> Unknownnoreply@blogger.comtag:blogger.com,1999:blog-3198935374994345981.post-73662758129026151232011-03-22T13:22:00.001+01:002011-03-22T13:32:02.145+01:00No way to remove posts from Google Reader cache<p>Interesting, there is apparently no way to remove posts from google reader cache (even when the post is deleted from site/rss feed). Google reader will never ever remove deleted posts from its cache. </p> <p>Good to know when you accidentally post to the wrong blog :) If that happens it is better to change the content of the post than delete it, then google reader will at least update it’s cache with the new content. </p> <p>For more info: </p> <p><a href="http://superuser.com/questions/56908/remove-deleted-posts-from-central-google-reader-cache">http://superuser.com/questions/56908/remove-deleted-posts-from-central-google-reader-cache</a></p> Unknownnoreply@blogger.comtag:blogger.com,1999:blog-3198935374994345981.post-11149101825701414352010-11-25T18:58:00.001+01:002010-11-25T18:58:33.877+01:00Command / Query service in WCFThe last year I have been working on a WPF frontend application that speaks to backend services through WCF. The WCF services were pretty standard request/response style services. For example: <p><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiVW0QIhef3Ksjzn5L8mmAD0gr_pKR3bA9pBYO0LQFK7sVyTbVDUaAjKMkgp3ZN7z9mWlBUIPqLikKQsRHIRk5BLEye6ky_kupW4qbYQlY28qcKaiSs_MV9j5iKt4h5ChiQeKYW1z9d2-k/s1600-h/image%5B9%5D.png"><img title="image" style="border-right: 0px; border-top: 0px; display: inline; border-left: 0px; border-bottom: 0px" height="170" alt="image" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhKSNQu_Wt_ZL-WAnOT4o2dR0ITdP7UVwKlpIZ6i4f8IrwlBqVVCuMskrbwoBsAJM7gtPx_X2KApnWO_xVym2vqO2h9Nfp5hWdrOa90FypKzMkr-0v0I7kMLZMj_dLYw4_W1iJyPEqhCuA/?imgmax=800" width="577" border="0" /></a> </p> <p>The problem with this approach is that the services quickly got bloated. Some operations gut lumped into a MasterDataService which got pretty big. Another problem was that there was no real distinction between service operations that caused side effects (changed domain state) and read only operations. </p> <p>Since then we have switched to a more simple service contract that looks like this:</p> <p><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjispKzyPoDzuO1tOfGVzJ_ddSbO0RcrevSjTDaMVThtTHRES4TOO4vxfV5EnVwB_iQqoHrE7ey2mCMLxjdwI4DYjZ0V54tde7hpWs_h_4dEvenXHXNiQanEjm5X0Q9iLQfq5evDkPaaB4/s1600-h/image%5B14%5D.png"><img title="image" style="border-right: 0px; border-top: 0px; display: inline; border-left: 0px; border-bottom: 0px" height="190" alt="image" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjFoLVfuquwnRFHIQLkgMr4SXNw4j8kjglDUnT2XsOju5zcjy0zayAnUl1-8odTuvi3vwa-z3SDtURu42SUS4gEzVYj1zXeu7MC0lD2iwQ_3zJxD2uOXwd-GT4QF0VwXy3iRI0lGeGtn7M/?imgmax=800" width="387" border="0" /></a> </p> <p>Now all backend interactions go through this service. All operations in get to be their own command or query, so we get clear distinction between commands that modify state and queries that only read data and have no side effect. This interface requires that all commands inherit from the <em>Command</em> type and all queries inherit from the <em>Query</em> type. When you use inheritance in WCF you need to specify all subtypes using the <em>KnownType </em>attribute on the base type<em>,</em> for example:</p> <p><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhE_Uc0XwMevon7JSC7RzXT3kix4KO36AzmbN25Dtjj2H5k7onVnaKTjKHjOBfR-qAJiMBMqaX1bwaFtdQo1gFaFk6ZTpj24g7L4ZXjFN6DyrgWG-_1YeNOgBIEKtSky7KKSxBTRD_uc5k/s1600-h/image%5B19%5D.png"><img title="image" style="border-right: 0px; border-top: 0px; display: inline; border-left: 0px; border-bottom: 0px" height="165" alt="image" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg6QlA83pKBvwEGKYbDsuQRPeehkGyibOlJN1OZb1Sic4OhJZYVnnqqyMpSpum-oG9hL3JROT9ycnN80-uAO4v-VbdZhexPmUWMs1bXvK3qL8onvGvLykFNCypTBbKbRp1Ri7clmfHRyvo/?imgmax=800" width="342" border="0" /></a> </p> <p>This sucks, because this means that every time you add a new command you need to remember to add it as a known type to the base class. Fortunately the WCF team provides a way to provide known types at runtime by specify a static method:</p> <p><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiFukE6okwDAKqkvn24kbg92XpqIQK0cI4RsXdN4RE8bOA1rN0YLgiGJM8tCzs8Um8KjFZll_9-U22WmqE02PEe9Z2f0vhe4qn4bWUAIq2XsqdoLBQcV5nJJ0oUOJWyGcwsvIECI61k5do/s1600-h/image%5B32%5D.png"><img title="image" style="border-right: 0px; border-top: 0px; display: inline; border-left: 0px; border-bottom: 0px" height="190" alt="image" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiUIWvHGenGzjoENcAf4K18O6u9A2SFN98sLZq3goedGJgsg9KFYPvtLHkWWw9x2o1ErGCruRpqzutI5eiTFg5-r8MMDQPoQ-DOHlSinGOMEwnAewZxKdA3z9rZ4fgEdB6KigNW_DmPpEU/?imgmax=800" width="487" border="0" /></a> </p> <p>The KnownTypesHelper will scan the contracts assembly for types inheriting from <em>Command. </em></p> <p> <p></p> <p></p> <p></p> <p></p> <p>The implementation of the Backend service will lookup a command handler based on the type of command coming in. All command handlers implement the generic interface <em>IHandleCommand<TCommand>.</em> These command (and query) handlers are automatically registered in the inversion of control container. I really like the idea of having a separate handler for all service operations, it enforces the single responsibility principle in that each command handler only handles one command (compared to normal service implementations that might handler multiple operations). It also conforms to the open closed principle in that adding a new command and command handler requires no change to any other classes. </p> <p>Example of a command handler:</p> <p><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgcJvNbCFI3YtFfdkVxTNxMDyz6W5vRgYevSHs1LcMN1J_7o71EMsX8KyePKlyY1oXhfuj8x39BhkqNUUk7KblKWvcyspHYIQ6UVrjHXLuK8_tjHwmycdcczv6Uzx2a3enUBFKEbTmBa08/s1600-h/image%5B37%5D.png"><img title="image" style="border-right: 0px; border-top: 0px; display: inline; border-left: 0px; border-bottom: 0px" height="294" alt="image" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj16KrLvVTqFAOU_e_5uwhyphenhyphenXua9oybw9hoTSn35nUP1B46g-U_kLqxDJGHdV-ucAgeaG9jT-Jwn3a3ziVlWf719g8Mdo-0hocLBUAt2J9FsbMnVy6-vufALxxQxUcNnL6vxmXw49JlIWf0/?imgmax=800" width="624" border="0" /></a> </p> </p> <p>One could ask why we did not use a message system like NServiceBus. The reason was that we figured that it would be an easier transition to move to a new WCF service contract than bring in a whole new framework. With this service in place it was really easy to rewrite operations (requests) into commands and operations that required a response to queries. Some operations that changed state AND returned data were split into a separate command and query (commands cannot return data). </p> <p>Anyway, it has been working really well for us so try it out! </p> Unknownnoreply@blogger.comtag:blogger.com,1999:blog-3198935374994345981.post-40264327921861909962010-11-25T18:23:00.001+01:002010-11-25T18:23:56.376+01:00Pimp My Conventions<p>Yesterday I held a talk at a cornerstone event titled <a href="http://www.cornerstone.se/sv/Event/Pimp-my-Code-2010/?gclid=CNT6o-m3vKUCFVEA4woduiXPYg">Pimp My Code</a> at Hard Rock Café in Göteborg. The talk was about convention over configuration. I began by quickly describing the design philosophy and it's origins (in for example ruby on rails) and after that it was all code demo. </p> <p>The code demo was a walkthrough of an application I had written (with some bits requiring live coding) that showcased a bunch of conventions. The application uses a lot of frameworks, for example Fluent NHibernate, StructureMap and AutoMapper. My point was not to dig deep into these frameworks but show show how they provide support for conventions and how that can be utilized in your application architecture. Among other things I showed how a Command/Query WCF service with automatic handler lookup could be achieved. </p> <p>The frontend part of the application was taken from Rob Eisenberg MVVM mix talk. I modified it a bit and connected it to a real backend system. This application is treasure trove of brilliant ideas. Ideas that later materialized in the excellent <a href="http://caliburnmicro.codeplex.com/">Caliburn Micro</a> framework. </p> <strong>Links</strong> <ul> <li>The code and powerpoint is at github: <a href="http://github.com/torkelo/pimpmycode">http://github.com/torkelo/pimpmycode</a> </li> <li>Rob Eisenberg MVVM talk from Mix: <a href="http://live.visitmix.com/MIX10/Sessions/EX15">Build Your Own MVVM Framework</a></li> <li>Caliburn Micro: <a title="http://caliburnmicro.codeplex.com/" href="http://caliburnmicro.codeplex.com/">http://caliburnmicro.codeplex.com/</a></li> <li>AutoMapper: <a href="http://automapper.codeplex.com/">http://automapper.codeplex.com/</a></li> <li>MSDN Article <a href="http://msdn.microsoft.com/en-us/magazine/dd419655.aspx">Design For Convention Over Configuration</a> (by Jeremy Miller)</li> <li>Fluent NHibernate: <a href="http://fluentnhibernate.org/">http://fluentnhibernate.org/</a></li> </ul> <p>I will be doing the same presentation in Stockholm on december 6th at Debaser Medis. It is fully booked, so for those that have managed to get tickets, see you there! </p> Unknownnoreply@blogger.comtag:blogger.com,1999:blog-3198935374994345981.post-90904089410682905122010-06-23T07:46:00.001+02:002010-06-23T07:47:24.385+02:00WPF and convention based binding<p>An another interesting aspect about <a href="http://devlicio.us/blogs/rob_eisenberg">Rob Eisenberg</a> MVVM <a href="http://devlicio.us/cfs-file.ashx/__key/CommunityServer.Components.PostAttachments/00.00.05.61.16/Build-Your-Own-MVVM-Framework.zip">sample application</a> is how it handles binding solely through conventions. That is no binding expressions in the XAML and no event hookups in the code behind. This is accomplished through a class named ViewModelBinder. This class takes a view model instance and a view instance. For each public property on the view model it will try to find a corresponding control with that name in the view, if found it will define the binding expression in code. </p> <p>A simplified version of the method that handles the property bindings: </p> <pre class="csharpcode"><span class="kwrd">private</span> <span class="kwrd">static</span> <span class="kwrd">void</span> BindProperties(<span class="type">FrameworkElement</span> view, IEnumerable<<span class="type">PropertyInfo</span>> properties)
{
<span class="kwrd">foreach</span> (var property <span class="kwrd">in</span> properties)
{
var foundControl = view.FindName(property.Name) <span class="kwrd">as</span> <span class="type">DependencyObject</span>;
<span class="kwrd">if</span>(foundControl == <span class="kwrd">null</span>)
<span class="kwrd">continue</span>;
<span class="type">DependencyProperty</span> boundProperty;
<span class="kwrd">if</span>(!_boundProperties.TryGetValue(foundControl.GetType(), <span class="kwrd">out</span> boundProperty))
<span class="kwrd">continue</span>;
<span class="kwrd">if</span>(((<span class="type">FrameworkElement</span>)foundControl).GetBindingExpression(boundProperty) != <span class="kwrd">null</span>)
<span class="kwrd">continue</span>;
var binding = <span class="kwrd">new</span> <span class="type">Binding</span>(property.Name)
{
Mode = property.CanWrite ? <span class="type">BindingMode</span>.TwoWay : <span class="type">BindingMode</span>.OneWay,
};
<span class="type">BindingOperations</span>.SetBinding(foundControl, boundProperty, binding);
}
}</pre>
<p></p>
When a control matching a property is found it will lookup in a dictionary the DependencyProperty that the view model property should be bound to. For example for a TextBox control it will bind to the TextBox.TextProperty. In the complete version of this method (please check the sample app) it handles hookup of bool properties to a Border control's visibility property, automatically configuring a BoolToVisibility converter on the binding. An important part of the method is where it checks if any manual (in the XAML) binding exists, if it already exists it skips the property/control. This allows you to override the conventions with manual bindings in edge cases.
<p>There is a similar method that handles binding of public methods to commands: </p>
<pre class="csharpcode"><span class="kwrd">private</span> <span class="kwrd">static</span> <span class="kwrd">void</span> BindCommands(<span class="kwrd">object</span> viewModel, <span class="type">FrameworkElement</span> view, IEnumerable<<span class="type">MethodInfo</span>> methods, IEnumerable<<span class="type">PropertyInfo</span>> properties)
{
<span class="kwrd">foreach</span>(var method <span class="kwrd">in</span> methods)
{
var foundControl = view.FindName(method.Name);
<span class="kwrd">if</span>(foundControl == <span class="kwrd">null</span>)
<span class="kwrd">continue</span>;
var foundProperty = properties
.FirstOrDefault(x => x.Name == <span class="str">"Can"</span> + method.Name);
var command = <span class="kwrd">new</span> <span class="type">ReflectiveCommand</span>(viewModel, method, foundProperty);
TrySetCommand(foundControl, command);
}
}</pre>
<p></p>
If a method with the same name as control is found it will create a new ReflectiveCommand and define the command binding. For example a method named ExecuteSearch matches the name of a button in the view. It will also look for a property that begins with Can and ends with the method name (for example CanExecuteSearch), if this property is found it will be used to determine if the command can be raised (which will disable and enable the button for example). Raising a property change for this CanExecuteSearch property will result in the ReflectiveCommand raising the CanExecuteChanged (defined on the ICommand WPF interface). This is pretty great, now all that boring command setup will be handled by infrastructure code! I am in the process of trying to incorporate some of these ideas into parts of a system I currently working on. The conventions defined in the Robs sample app will only get you so far, the nice thing is that it is now very easy to add new ones. The scenario I was working on today was how to hookup a DoubleClick event on a grid item to a method on the view model. If the convention based binding could look for a method ending with "_OpenGridItem" it could then check for the first part of the method, try to find a control matching that first part and hookup the DoubleClickEvent and then call the view model method. First we need to refactor the BindCommands method into something more extendible.
<p>Fist we need an interface: </p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">interface</span> <span class="type">IMethodBindingConvetion</span>
{
<span class="kwrd">void</span> Apply(<span class="kwrd">object</span> viewModel, <span class="type">FrameworkElement</span> view, <span class="type">MethodInfo</span> method, IEnumerable<<span class="type">PropertyInfo</span>> properties);
}</pre>
<p>Now we can move the already existing convention into it's own class: </p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">class</span> <span class="type">CommandToMethodBindingConvention</span> : <span class="type">IMethodBindingConvetion</span>
{
<span class="kwrd">public</span> <span class="kwrd">void</span> Apply(<span class="kwrd">object</span> viewModel, <span class="type">FrameworkElement</span> view, <span class="type">MethodInfo</span> method, IEnumerable<<span class="type">PropertyInfo</span>> properties)
{
var foundControl = view.FindName(method.Name);
<span class="kwrd">if</span> (foundControl == <span class="kwrd">null</span>)
<span class="kwrd">return</span>;
var foundProperty = properties
.FirstOrDefault(x => x.Name == <span class="str">"Can"</span> + method.Name);
var command = <span class="kwrd">new</span> <span class="type">ReflectiveCommand</span>(viewModel, method, foundProperty);
TrySetCommand(foundControl, command);
}
<span class="rem">//...</span>
}</pre>
<p></p>
<p>Now lets try to create the convention that captures DoubleClick on a infragistic Grid and calls the corresponding OpenGridItem method on the view model. </p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">class</span> <span class="type">DoubleClickGridToMethodConvention</span> : <span class="type">IMethodBindingConvetion</span>
{
<span class="kwrd">public</span> <span class="kwrd">void</span> Apply(<span class="kwrd">object</span> viewModel, <span class="type">FrameworkElement</span> view, <span class="type">MethodInfo</span> method, IEnumerable<<span class="type">PropertyInfo</span>> properties)
{
<span class="kwrd">if</span> (!method.Name.EndsWith(<span class="str">"_OpenItem"</span>))
<span class="kwrd">return</span>;
var gridName = method.Name.Replace(<span class="str">"_OpenItem"</span>, <span class="str">""</span>);
var gridControl = view.FindName(gridName) <span class="kwrd">as</span> <span class="type">XamDataGrid</span>;
<span class="kwrd">if</span> (gridControl == <span class="kwrd">null</span>)
<span class="kwrd">throw</span> <span class="kwrd">new</span> <span class="type">ConventionBindingException</span>(<span class="str">"Could not find matching control for the method "</span> + method.Name);
gridControl.MouseDoubleClick += (sender, e) =>
{
var item = FindClickedItem(sender, e);
method.Invoke(viewModel, <span class="kwrd">new</span> <span class="kwrd">object</span>[] {item});
};
}
}</pre>
<p>If you want the method to be able to return IEnumerable<IResult>, something I talked about in <a href="http://www.codinginstinct.com/2010/06/sequential-async-using-coroutines.html">yesterdays post</a> (async programming using coroutines), then you need to handle the return value of the method invocation and pipe that through a ResultEnumerator. </p>
<p>Now that we have delegated the method conventions to specific classes the BindCommands method now looks like this: </p>
<pre class="csharpcode"><span class="kwrd">private</span> <span class="kwrd">static</span> <span class="kwrd">readonly</span> IList<<span class="type">IMethodBindingConvetion</span>> _methodBindingConventions =
<span class="kwrd">new</span> List<<span class="type">IMethodBindingConvetion</span>>()
{
<span class="kwrd">new</span> <span class="type">CommandToMethodBindingConvention</span>(),
<span class="kwrd">new</span> <span class="type">DoubleClickGridToMethodConvention</span>()
};
<span class="kwrd">private</span> <span class="kwrd">static</span> <span class="kwrd">void</span> BindCommands(<span class="kwrd">object</span> viewModel, <span class="type">FrameworkElement</span> view, IEnumerable<<span class="type">MethodInfo</span>> methods, IEnumerable<<span class="type">PropertyInfo</span>> properties)
{
<span class="kwrd">foreach</span>(var method <span class="kwrd">in</span> methods)
{
<span class="kwrd">foreach</span> (var methodBindingConvention <span class="kwrd">in</span> _methodBindingConventions)
methodBindingConvention.Apply(viewModel, view, method, properties);
}
}</pre>
<p></p>
<p>This method should perhaps be renamed to BindMethods. Anyway the point of this post was really to show how the convention based binding ideas in Robs <a href="http://devlicio.us/cfs-file.ashx/__key/CommunityServer.Components.PostAttachments/00.00.05.61.16/Build-Your-Own-MVVM-Framework.zip">sample application</a> can be expanded to fit the application you are building. </p> Unknownnoreply@blogger.comtag:blogger.com,1999:blog-3198935374994345981.post-82655396131908065502010-06-22T09:32:00.001+02:002010-06-22T13:56:36.111+02:00Sequential Async using CoRoutines<p>If you work with WPF or Silverlight then you really should check out <a href="http://devlicio.us/blogs/rob_eisenberg">Rob Eisenberg</a> presentation at MIX10 titled <a href="http://live.visitmix.com/MIX10/Sessions/EX15">Build Your Own MVVM Framework</a>. In that presentation he goes through a <a href="http://devlicio.us/cfs-file.ashx/__key/CommunityServer.Components.PostAttachments/00.00.05.61.16/Build-Your-Own-MVVM-Framework.zip">sample application</a> that utilizes no code behind and no data binding or command binding expressions, all is hooked up through conventions and is driven solely from the presentation model. The sample app has about 500 lines of framework or infrastructure code that handles the view look up and convention based binding. I urge you to download it and really dig through it, it contains some awesome code and ideas. </p> <p>But I will focus this blog post on one aspect of that sample app which is how Rob implemented async workflows. It might be a long post with a lot of code :)</p> <p>Sequential async workflow: </p> <pre class="csharpcode"><span class="kwrd">public</span> IEnumerable<<span class="type">IResult</span>> ExecuteSearch()
{
var search = <span class="kwrd">new</span> <span class="type">SearchGames</span>
{
SearchText = SearchText
}.AsResult();
<span class="kwrd">yield</span> <span class="kwrd">return</span> <span class="type">Show</span>.Busy();
<span class="kwrd">yield</span> <span class="kwrd">return</span> search;
var resultCount = search.Response.Count();
<span class="kwrd">if</span> (resultCount == 0)
SearchResults = _noResults.WithTitle(SearchText);
<span class="kwrd">else</span>
SearchResults = _results.With(search.Response);
<span class="kwrd">yield</span> <span class="kwrd">return</span> <span class="type">Show</span>.NotBusy();
}</pre>
<p>Before I dig into what the above code does and how it works I need to explain the problem. Anyone who has worked with WinForms/WPF/Silverlight knows that backend calls and other long running work needs to be done on a background thread. However all UI updates needs to be done on the UI thread. If you use ThreadPool.QueueUserWorkItem and you want to notify the UI that something has updated (issue a NotifyPropertyChanged for example) then you need to marshal the the call via the WPF dispatcher so the NotifyPropertyChanged happens on the UI thread. Another option is to use the BackgroundWorker that automatically executes the event RunWorkerCompleted on the same thread that called RunWorkerAsync. </p>
Example:
<p></p>
<pre class="csharpcode"><span class="kwrd">private</span> <span class="kwrd">void</span> ExecuteSearch()
{
IsBusy = <span class="kwrd">true</span>;
var worker = <span class="kwrd">new</span> <span class="type">BackgroundWorker</span>();
IEnumerable<<span class="type">SearchResult</span>> results;
worker.DoWork += (e, sender) =>
{
results = searchService.SearchGames(SearchText);
};
worker.RunWorkerCompleted += (e, sender) =>
{
<span class="kwrd">if</span> (results.Count == 0)
SearchResults = _noResults.WithTitle(SearchText);
<span class="kwrd">else</span>
SearchResults = _results.With(results);
IsBusy = <span class="kwrd">false</span>;
};
worker.RunWorkerAsync();
}</pre>
<p></p>
<p>This does not look so bad, we still have all the code in one method thanks to the lambdas. But imagine that we need to fetch the game (another backend call) and open the game screen if the returned search result only match exactly one game. In that case we would need to new up another BackgroundWorker inside the RunWorkerCompleted lambda and then hookup DoWork and RunWorkerCompleted. The code would be very messy (nested lambda callbacks) and it would be hard to read the sequential flow of the process. </p>
<p>Coroutines to the rescue. Wikipedia definition reads: </p>
<blockquote>Coroutines are program components that generalize subroutines to allow multiple entry points for suspending and resuming execution at certain locations </blockquote>
But C# does not have that! Well it kind of does. You can get the same effect if you define an enumerator using yield returns. In a method that returns IEnumerable<t> you can use yield return. The C# compiler will turn that method into a state machine (to implement the enumerator). Each time someone calls MoveNext (which happens once each foreach loop) the execution of the method will continue until the next yield return.
<p></p>
<p>Example: </p>
<pre class="csharpcode"><span class="kwrd">public</span> IEnumerable<<span class="kwrd">string</span>> GetStrings()
{
<span class="kwrd">yield</span> <span class="kwrd">return</span> <span class="str">"Hello"</span>;
<span class="type">Console</span>.WriteLine(<span class="str">"execution continued"</span>);
<span class="kwrd">yield</span> <span class="kwrd">return</span> <span class="str">"Good bye"</span>;
<span class="type">Console</span>.WriteLine(<span class="str">"Nothing left"</span>);
}</pre>
<p></p>
<p>This method will be turned into a MoveNext method on a generated class that implements IEnumerator<string>: </p>
<pre class="csharpcode"><span class="kwrd">private</span> <span class="kwrd">bool</span> MoveNext()
{
<span class="kwrd">switch</span> (<span class="kwrd">this</span>.<>1__state)
{
<span class="kwrd">case</span> 0:
<span class="kwrd">this</span>.<>1__state = -1;
<span class="kwrd">this</span>.<>2__current = <span class="str">"Hello"</span>;
<span class="kwrd">this</span>.<>1__state = 1;
<span class="kwrd">return</span> <span class="kwrd">true</span>;
<span class="kwrd">case</span> 1:
<span class="kwrd">this</span>.<>1__state = -1;
Console.WriteLine(<span class="str">"execution continued"</span>);
<span class="kwrd">this</span>.<>2__current = <span class="str">"Good bye"</span>;
<span class="kwrd">this</span>.<>1__state = 2;
<span class="kwrd">return</span> <span class="kwrd">true</span>;
<span class="kwrd">case</span> 2:
<span class="kwrd">this</span>.<>1__state = -1;
Console.WriteLine(<span class="str">"Nothing left"</span>);
<span class="kwrd">break</span>;
}
<span class="kwrd">return</span> <span class="kwrd">false</span>;
}</pre>
<p></p>
<p>Ok, so now that we know how yield works we can use that to get something like Coroutines. </p>
<pre class="csharpcode"><span class="kwrd">public</span> IEnumerable<<span class="type">IResult</span>> ExecuteSearch()
{
<span class="rem">// yield returns...</span>
}
<span class="kwrd">public</span> <span class="kwrd">interface</span> <span class="type">IResult</span>
{
<span class="kwrd">void</span> Execute();
<span class="kwrd">event</span> <span class="type">EventHandler</span> Completed;
} </pre>
<p></p>
<p>Back to Robs sample app. The ExecuteSearch method above returns an IEnumerable<iresult> of IResult, an interface that has an Execute method and a Completed event. The magic happens in how this enumerable is consumed, which is handled by the ResultEnumerator class: </p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">class</span> <span class="type">ResultEnumerator</span>
{
<span class="kwrd">private</span> <span class="kwrd">readonly</span> IEnumerator<<span class="type">IResult</span>> _enumerator;
<span class="kwrd">public</span> ResultEnumerator(IEnumerable<<span class="type">IResult</span>> children)
{
_enumerator = children.GetEnumerator();
}
<span class="kwrd">public</span> <span class="kwrd">void</span> Enumerate()
{
ChildCompleted(<span class="kwrd">null</span>, <span class="type">EventArgs</span>.Empty);
}
<span class="kwrd">private</span> <span class="kwrd">void</span> ChildCompleted(<span class="kwrd">object</span> sender, <span class="type">EventArgs</span> args)
{
var previous = sender <span class="kwrd">as</span> IResult;
<span class="kwrd">if</span>(previous != <span class="kwrd">null</span>)
previous.Completed -= ChildCompleted;
<span class="kwrd">if</span>(!_enumerator.MoveNext())
<span class="kwrd">return</span>;
var next = _enumerator.Current;
next.Completed += ChildCompleted;
next.Execute();
}
}</pre>
<p></p>
<p>This class might take some time to get your head around. What happens is that we take the first IResult by calling MoveNext, we then hook up the Completed event and then call the Execute method. The interesting thing is that the Completed event is hooked up the the same method that we are in. The result is that the first IResult controls when the next IResult is fetched (the next IResult won't be fetched until the one before executes the Completed event). Ok, think about this until you understand it :) </p>
<p>Now lets look at how we can use this. Lets try to create a IResult that executes a lambda in a background thread then executes the Completed event on the UI thread. </p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">class</span> <span class="type">BackgroundResult</span> : <span class="type">IResult</span>
{
<span class="kwrd">private</span> <span class="kwrd">readonly</span> <span class="type">Action</span> action;
<span class="kwrd">public</span> BackgroundResult(<span class="type">Action</span> action)
{
<span class="kwrd">this</span>.action = action;
}
<span class="kwrd">public</span> <span class="kwrd">void</span> Execute()
{
var backgroundWorker = <span class="kwrd">new</span> <span class="type">BackgroundWorker</span>();
backgroundWorker.DoWork += (e, sender) => action();
backgroundWorker.RunWorkerCompleted += (e, sender) => Completed(<span class="kwrd">this</span>, <span class="type">EventArgs</span>.Empty);
backgroundWorker.RunWorkerAsync();
}
<span class="kwrd">public</span> <span class="kwrd">event</span> <span class="type">EventHandler</span> Completed = <span class="kwrd">delegate</span> { };
}</pre>
<p></p>
<p>Lets look at our example that used BackgroundWorker but rewrite it to use our new BackgroundResult: </p>
<pre class="csharpcode"><span class="kwrd">private</span> IEnumerable<<span class="type">IResult</span>> ExecuteSearch()
{
IsBusy = <span class="kwrd">true</span>;
IEnumerable<<span class="type">SearchResult</span>> results;
<span class="kwrd">yield return</span> <span class="kwrd">new</span> <span class="type">BackgroundResult</span>(() =>
{
results = searchService.Search(SearchText);
});
<span class="kwrd">if</span> (results.Count == 0)
SearchResults = _noResults.WithTitle(SearchText);
<span class="kwrd">else</span>
SearchResults = _results.With(results);
IsBusy = <span class="kwrd">false</span>;
}</pre>
<p></p>
<p>Looks better doesn't it? The BackgroundResult will block the execution of the method until the action completes which will fire the Completed event (which happens on the UI thread) which in turn will resume the execution of the ExecuteSearch method. The requirement to show the game screen when there is only one match is now much easier to handle as we can yield another BackgroundResult to fetch the game. The method logic happens in the sequential order that it is written, making it much easier to read, test and debug. </p>
<p>Now to the complete version of the method from Robs example app: </p>
<pre class="csharpcode"><span class="kwrd">public</span> IEnumerable<<span class="type">IResult</span>> ExecuteSearch()
{
var search = <span class="kwrd">new</span> <span class="type">SearchGames</span>
{
SearchText = SearchText
}.AsResult();
<span class="kwrd">yield</span> <span class="kwrd">return</span> <span class="type">Show</span>.Busy();
<span class="kwrd">yield</span> <span class="kwrd">return</span> search;
var resultCount = search.Response.Count();
<span class="kwrd">if</span> (resultCount == 0)
SearchResults = _noResults.WithTitle(SearchText);
<span class="kwrd">else</span> <span class="kwrd">if</span> (resultCount == 1 && search.Response.First().Title == SearchText)
{
var getGame = <span class="kwrd">new</span> <span class="type">GetGame</span>
{
Id = search.Response.First().Id
}.AsResult();
<span class="kwrd">yield</span> <span class="kwrd">return</span> getGame;
<span class="kwrd">yield</span> <span class="kwrd">return</span> <span class="type">Show</span>.Screen<<span class="type">ExploreGameViewModel</span>>()
.Configured(x => x.WithGame(getGame.Response));
}
<span class="kwrd">else</span> SearchResults = _results.With(search.Response);
<span class="kwrd">yield</span> <span class="kwrd">return</span> <span class="type">Show</span>.NotBusy();
}</pre>
<p></p>
<p>In the complete version he handles the case where there is only one match, in that case GetGame query is also issued to the backend. Before I end this post I will just highlight another interesting aspect of this sample and that is how Rob handles backend interaction. Instead of directly calling a IBackend service he returns an IQueryResult or ICommandResult which will handle the execution of the backend call and the thread marshalling. This improves the testability as the method will not require any mocking to test. </p>
<p>It's not trivial stuff, it takes some time to get your head around how the ResultEnumerator works and what it makes possible. But I think it is a pretty brilliant solution to keep complex async workflows in the same place and be able to read them sequentially. I am not sure if it is the same thing but if I remember correctly I think the C# team is looking at making this easier in C# 5 with an async keyword. Does anyone know how this implementation of coroutines compares to the async features in F#? </p>
Check out the full <a href="http://devlicio.us/cfs-file.ashx/__key/CommunityServer.Components.PostAttachments/00.00.05.61.16/Build-Your-Own-MVVM-Framework.zip">sample application</a> Unknownnoreply@blogger.comtag:blogger.com,1999:blog-3198935374994345981.post-35716026648862722772010-06-10T18:19:00.001+02:002010-06-10T18:23:03.532+02:00NHProfiler Integration<p>If you use NHibernate heavily then you have a lot to gain from <a href="http://nhprof.com/">NHProfiler</a>. It is a great tool for identifying problems with how you use NHibernate and how you access and update data. But I think its greatest strength is as a learning tool, as it is makes it easy to understand how NHibernate works and what the consequences of each mapping setup are. </p> <p>Ok, this post is not just going to be free advertising for <a href="http://ayende.com/Blog/">Ayende</a>. A nice feature in NHProfiler is that it will show you the context of the data access. For web apps it will show the URL that triggered the data access, for WCF apps it will show the WCF service and operation name. </p> <p>Example: <br /><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgu6KPe9X9IrhpqpcG2gPOasNEoSmjpA8yRc6TjkN9jzKRljjXa7bLEio5tg5UIcV4eVzbrUWqD8Jdn6Q6xt4HSzbRl6JXtu-GxD1je2AL14Lq_YSRCuF-1ttqE0uv344sFsUug-R9so5Q/s1600-h/image%5B4%5D.png"><img title="image" style="border-top-width: 0px; display: inline; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="134" alt="image" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiklz6DlKixu2AllK4v4hvHyuQ1b7agnQRCtSsaoktf-nUcNDcUdenaU9xrJPgV_KQPGPutBmB2hb6Bo1-cnFt0nLiQy_TpPNfgfF_mCTGWYq4zS9mMTsQF-wkRZrtzhnNEe53wuiKTWmg/?imgmax=800" width="621" border="0" /></a> </p> <p>Here you see that ContractService and operation GetContractStatuses was called and generated one database call. This context is very nice to have when profiling and tuning your application. However in the current project that I am working on we have moved from classic WCF with services and operations to a generic WCF command & query service with just two operations  (SendCommand & SendQuery). This makes the context not so useful anymore.</p> <p><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgC3pI0a23_hLESAfEou5Ai6ue44tO1f14-RYHVu_AlxXBrkPiiewqcA5F3pqkcTq1EVW0Ztpf4ZLhtMgeEIM4Y2UQBEf6Tvk453reOmiOMOZkquUHoaoLA5qyP5HfsBOFxUdd4C472zZU/s1600-h/image%5B9%5D.png"><img title="image" style="border-top-width: 0px; display: inline; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="167" alt="image" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEixB6N4WuiJuflGPk1FujYvZSAdc2dgz0BAZnKA3C0kELwSWoiSchRmYsP2KW8VzFK3N2eUxmFJYZA_GFNpQ8_n5wG9yD1Ba2jYv8ZtiIA4j7hHUwnTHMvplRoLb6v4YsH4Q6bQz741NlA/?imgmax=800" width="389" border="0" /></a> </p> <p>Sorry for the censored image, it hides the project name. Anyway here the WCF service and operation name is not helping much as we do not se what command or query was issued. Fortunately NHProfiler offers a way to programmatically set the context. In order to set the context for this generic command & query service I implemented a ParameterInspector (a WCF extensibility point) in which I set the NHProfiler context. </p> <p>Here is the code: </p> <pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">class</span> NHProfMessageInspector : <span class="type">IParameterInspector</span>
{
<span class="kwrd">public</span> <span class="kwrd">object</span> BeforeCall(<span class="kwrd">string</span> operationName, <span class="kwrd">object</span>[] inputs)
{
var typeName = inputs[0].GetType().Name;
var commandOrQuery = <span class="str">""</span>;
<span class="kwrd">if</span> (typeName.EndsWith(<span class="str">"Query"</span>))
{
commandOrQuery = <span class="str">"Query"</span>;
typeName = typeName.Substring(0, typeName.Length - 5);
}
<span class="kwrd">if</span> (typeName.EndsWith(<span class="str">"Command"</span>))
{
commandOrQuery = <span class="str">"Command"</span>;
typeName = typeName.Substring(0, typeName.Length - 7);
}
var contextString = <span class="kwrd">string</span>.Format(<span class="str">"{0} : {1}"</span>, commandOrQuery, typeName.ToSentenceStyle());
SetContext(contextString);
<span class="kwrd">return</span> <span class="kwrd">null</span>;
}
<span class="kwrd">public</span> <span class="kwrd">void</span> AfterCall(<span class="kwrd">string</span> operationName, <span class="kwrd">object</span>[] outputs, <span class="kwrd">object</span> returnValue, <span class="kwrd">object</span> correlationState)
{
SetContext(<span class="kwrd">null</span>);
}
<span class="kwrd">private</span> <span class="kwrd">void</span> SetContext(<span class="kwrd">string</span> <span class="kwrd">value</span>)
{
<span class="type">Assembly</span> profilerAsm = <span class="kwrd">null</span>;
<span class="kwrd">try</span>
{
profilerAsm = <span class="type">Assembly</span>.Load(<span class="str">"HibernatingRhinos.Profiler.Appender"</span>);
}
<span class="kwrd">catch</span> (<span class="type">Exception</span>) { <span class="kwrd">return</span>; }
<span class="kwrd">if</span> (profilerAsm == <span class="kwrd">null</span>)
<span class="kwrd">return</span>;
var profilerIntegration = profilerAsm.GetType(<span class="str">"HibernatingRhinos.Profiler.Appender.ProfilerIntegration"</span>);
<span class="kwrd">if</span> (profilerIntegration == <span class="kwrd">null</span>)
<span class="kwrd">return</span>;
var currentContext = profilerIntegration.GetProperty(<span class="str">"CurrentSessionContext"</span>);
currentContext.SetValue(<span class="kwrd">null</span>, <span class="kwrd">value</span>, <span class="kwrd">null</span>);
}
}</pre>
<p>The BeforeCall method checks the first input type and creates a nice context string based on the type name. The SetContext method does the integration with NHProfiler. This is done through some reflection (in order to not have a strong reference to HibernatingRhinos.Profiler.Appender.dll and be version independent). </p>
<p>The result:
<br /><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiTmVgl47fSQZPdZwJrbH6KofDwLP0a-J-16rKMNEzrlodTsdjeubDGi3ORnZHlT3DvgKZdt1g4O_W_IjQYViQ2yIhOhssI8jEurfTEwYshX85vcPZJyOSQkzhmUkinjivJ_1mL6Pa2zas/s1600-h/image%5B17%5D.png"><img title="image" style="border-right: 0px; border-top: 0px; display: inline; border-left: 0px; border-bottom: 0px" height="105" alt="image" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjP6d2gpwsN_g2F9Xs6K-XRQUnIWZBPONBa1JtjBeKcoVruaaJVz8JnSgd_6bKid9V1wVMaxKLkeUPekmG0dTM_cTPIJNpIrrujgdc88AcjWHUQk9SwLkBIlPina1p_f_CXpcM5k9WOww4/?imgmax=800" width="392" border="0" /></a> </p>
<p></p>
<p>Now the context is much more useful! The same approach should be interesting for other people who also use a generic WCF interface or for example NServiceBus. Another option is to set the NHProfiler context in an integration test base class. This could be useful for example if you have a suite of repository tests and you want the text fixture name to appear as the context in NHProfiler. </p> Unknownnoreply@blogger.comtag:blogger.com,1999:blog-3198935374994345981.post-9089100936321730752010-06-01T13:57:00.001+02:002010-06-01T14:00:35.818+02:00NHibernate presentation at Developer Summit 2010<p><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiNICnnY3Ho84TCkjAVErHb1KBWG97lufY8K4oF7ykP1pgVEBBwbpuWhQE5uYlYipHQOnIKWA8EXm4XPN1zb0IyGe7oWeEz6gMNr_ebMI04m198XAV6ItzUqn8Pl3H7Nt2lpYEaw-mcLuo/s1600-h/image%5B12%5D.png"><img style="border-bottom: 0px; border-left: 0px; display: inline; margin-left: 0px; border-top: 0px; margin-right: 0px; border-right: 0px" title="image" border="0" alt="image" align="right" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjmXGf2s4EGh_36J5P7FAZxxcFz23MRvN7wjd0CVdoA6BFKNIIQygQPfs6rEhyphenhyphenOIdLP7BY9FkbEgwST85PvF1e3nSiZ1JMC1frRQcm2VYLxw7dXUUghwN5fQtbZX3tiPfWAgmkHPf5dHxM/?imgmax=800" width="458" height="272" /></a>A couple of hours ago I finished a presentation about NHiberante at the <a href="http://www.cornerstone.se/sv/Event/DevSum/">Developer Summit 2010 conference</a> being held here in Stockholm. </p> <p>I have worked with NHibernate in many projects, some greenfield projects but mostly replacing an existing data layer. I have introduced it to many teams. In those teams I have always been the NHibernate guy. The person that people turn to when faced with some NHibernate related problem. So when I started to prepare for this presentation I asked myself what is it that is causing these problems, what is it that people are missing in there understanding? </p> <p>So the focus of the talk centered around these areas:</p> <p><strong>Identity Map (L1 Cache) <br /></strong>Understanding how the identity map is an integral part of NHibernate is very important. If you are not aware that you share instances for entities with the same id you can run into some strange bugs and side effects. The identity map is probably one of the main causes of problems when replacing an old DAL layer (that do not use an identity map) with an ORM. </p> <p><strong>Unit Of Work <br /></strong>Of course it is important to know how the Unit Of Work in NHibernate works, it’s relation to Flush and Transaction (FlushMode Commit).</p> <p><strong>Session Management<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiBFsTAt9kWezLl45HZnQvNVUMK64b05pmlnLllXFPVZzEh-TKun81AQ12ZedMI5vqYO6k2jibZFBAihoi03ADzUOnTF3-2Xnsnq3V93o6GZ4SP_eGTo9pBcLMgG064WBnGRIrxmF7ewqM/s1600-h/image%5B44%5D.png"><img style="border-bottom: 0px; border-left: 0px; display: inline; margin-left: 0px; border-top: 0px; margin-right: 0px; border-right: 0px" title="image" border="0" alt="image" align="right" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjTUom5OAmOSRT176hET-d-OQ_wuPqyVLt2LCaq1WjD0SfIJVdFAEcAk1-a3CC21wScMXplpan7iSCxC3ni0RLMUzakgsTh38RDKA85rMGhym7g6OQdRncPUEVFeU1RQIaYHaGRY7dKtgc/?imgmax=800" width="469" height="291" /></a> <br /></strong>Important to use the session correctly (i.e. do not open and close it in the data layer).    </p> <p><strong>Cascading <br /></strong>Understanding cascading can be tricky, especially how correctly to use cascade=”none” and how that works in relation to transient instances (it doesn’t). It is important to understand that NHibernate persists all changes to modified entities that are associated with an open session, no matter if you set cascade to none.  </p> <p><strong>Attached & Detached</strong> <br />It is very important to understand what it means that an instance is attached/associated with an open session. In the talk I show the result when you try to persist a modified detached instance. I also show how you can solve that issue by associating the detached instance with an open session (before the modification) by calling session.Lock and how you can as your last option use session.Merge to update modified detached instances. </p> <p><strong>Lazy Loading & Proxy Objects <br /></strong>In the talk I show how NHibernate’s lazy loading works via proxy objects and what issues you might run into. For example trying to check the concrete type in an inheritance chain won’t work as the type will always be the proxy object.</p> <p><strong>ID Generation & unsaved-value<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjgSEDbXAScwxMDxbm5GI1w-35Hu3uoarcaaHfCrQanr5qVMEzUs8Y_mBGIHjlVjvGDZutSCmum_pe4CBZiaNG1JriN2unAU3epYlDnWb_jflpLCYO1eD4SleX1c1Q2w3D9P4nWPPYzS_4/s1600-h/image%5B37%5D.png"><img style="border-bottom: 0px; border-left: 0px; display: inline; margin-left: 0px; border-top: 0px; margin-right: 0px; border-right: 0px" title="image" border="0" alt="image" align="right" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg0psWnMdwR7iw1JQzp8v2w9kEDjJn_SYvlL7fVEi8c7kIMY7GM_VunnHS1uXpAG9A9FlgowUVVxa74phCP_N6VoBGTknipoBeRGt232ZXCj-zn2DdA_vrtKYI3kINhARULW2OryQuXjO8/?imgmax=800" width="464" height="286" /></a> <br /></strong>It is important to understand how NHibernate determines if an instance is transient or not and how that plays into id generation. If you need to use assigned id you can still let NHibernate know if an instance is transient or not by using a version column. </p> <p><strong>Concurrency</strong> <br />I ended the talk by showing how to handle concurrency (by using a version column).</p> <p> </p> <p>If all NHiberante users have a good grasp of the above areas I think they would experience a lot less bugs and head aches. So for those that attended the talk I hope they will not be making the same mistakes I have made and have seen others make.  </p> <p>Here is a link to download the <a href="http://tlo.googlecode.com/svn/trunk/presentations/devsum10/docs/devsum10.pptx">powerpoint slides</a></p> Unknownnoreply@blogger.comtag:blogger.com,1999:blog-3198935374994345981.post-67723225008708448782010-05-17T21:45:00.001+02:002010-05-17T21:51:53.739+02:00A visit to Kyrgyzstan parliament<p><img style="display: inline; margin-left: 0px; margin-right: 0px" align="right" src="http://www.reliefweb.int/mapc/cis/reg/cau/caucia.jpg" width="464" height="346" />Those who read the tile of this post should have figured out that this post is not about programming but is an account of an interesting trip I recently came home from. An amazing trip that took me through Kazakhstan, Kyrgyzstan and Uzbekistan. So if you want to know something about Central Asia please continue to read otherwise skip this post. </p> <p>The trip focused on the history of this region and it’s people. The region is famous for it’s huge steps, incredible mountains and vistas and it’s rich history and art. It contains enchanting cities like Samarkand and Bukhara. Cities that has existed for millennia as important centers of commerce along the silk road.    </p> <p>The most interesting part of the trip, and the one I wish to retell in more detail is the event that happened in Bishkek (the capital of Kyrgyzstan). We were invited to the parliament by <a href="http://en.wikipedia.org/wiki/Edil_Baisalov">Edil Baisalov</a>, the current chief of staff of the interim government. For those who haven’t followed the news of this region: There was recently (April 6-15) and <a href="http://en.wikipedia.org/wiki/2010_Kyrgyzstani_riots">uprising in Kyrgyzstan</a> where the then president <a href="http://en.wikipedia.org/wiki/Kurmanbek_Bakiyev">Kurmanbek Bakiyev</a> and his government was removed and replaced by an interim government. One of the many reasons for the uprising was the shutting down of news outlets that were critical of him and his son. </p> <p>Why would a central figure from the new interim government invite a group of Swedish tourists?  <a href="http://en.wikipedia.org/wiki/Edil_Baisalov">Edil Baisalov</a> was recently a political refuge fleeing Kyrgyzstan in late 2007. He feared imprisonment or assassination from president Bakiyev. He ended up in Sweden. He was very moved by the way Sweden accepted him and his family, how they were provided with an apartment, free language education and counsel. Now, when a group of Swedish tourists, in this time of political crisis, dared to enter the partially closed border and go forward with their trip through Kyrgyzstan, I think he felt obliged to say something.  I am not sure exactly what his motives were.  </p> <p>The meeting took place on the 5th of May. The group of forty Swedish tourists was led into a big round table room in the parliament building. After a few minutes Edil Baisalov entered, greeting us in Swedish. He switched to English and continued to talk a little bit about himself, his history with activism for human rights and against corruption. Baisalov was a very open critic of the Bakiyev government, criticism that finally led to him having to flee from Kyrgyzstan. One thing that struck everyone from the beginning of the meeting was how very candid and honest this person sounded - this was no ordinary politician. And reading his profile in Wikipedia shows that this is a longtime activist, who is not used to have power and to be careful about what he says.  </p> <p><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhsWml6XcYVL5AZ8DnITlGMlnH0E81Ikwp2VJjXHdqqIhKqQOyynVCNb86IK8AbiiGXi1s7A1rhcREtnHtrIFmD5hP28R1Yifd2rEW3q8LYoda-r2CuuqKtEVplxpmM5OsBbonImKpfl3s/s1600-h/_DSC0301%5B6%5D.jpg"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; margin-left: 0px; border-left-width: 0px; margin-right: 0px" title="_DSC0301" border="0" alt="_DSC0301" align="right" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjqHNQ2vNHq5nkidFPeFEPKrPgXerTF1S0b7x5PpF6g6n0d9h4qsVUVdkgGXywHC179wRTT3IKZcoDyoi605LAtMW4qTZf_Zx1TryzDNKxM4M6-JmNuIf46NhYdCuMsxCgoyN5am1H8Y_U/?imgmax=800" width="415" height="275" /></a>And what Baisalov said was very interesting. He was asked: "How are you going to fix it?" referring to the current state of political crisis.</p> <p>Baisalov said that the main focus is to organize free and fair elections this fall. They are working on changing the constitution in the direction to become a parliamentary republic, increase freedom of speech and improve the election and voting system.</p> <p>Another focus he mentioned was to improve the situation for women - from education and job opportunity standpoint. He said that Kyrgyzstan has a population of very well educated women, almost more so than men (for example his mother was a doctor and his father a driver). This he said was a legacy from the Soviet times, when the situation between men and women were more equal (compared to today) and where everyone could get an education. He said that the situation for women has deteriorated and is regressing. This trend he wishes to reverse.</p> <p>He was asked about relations to Russia and the States.</p> <p>He answered by saying that Russia quickly accepted the interim government. Mainly (he thought) because Bakiyev had cheated Russia by accepting money from Russia to build a power station, but in return for the money Bakiyev should have barred the States the use of the military airport. He did not comply with this demand. This and other similar situations caused Russia to be offended by Bakiyev. This Baisalov thought was one of the reasons behind Russia’s quick approval of the uprising and ousting of Bakiyev. </p> <p>With regards to the interim government and its relations to The States: He said that they were finding evidence that the States had bribed military and government officials in order to use the airport in Bishkek. "They fight for democracy in Afghanistan while they sacrifice democracy in Kyrgyzstan".  But he said that they (the interim government) will continue to allow the USA to use the airport and it is for the next elected government to decide on this issue.</p> <p>He also mentioned that Bakiyev's son, known as the ‘prince’ and was touted as his almost certain successor, was visiting <a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjeLnL7KzEmFvfDGmVaFk0XVJ4Yu2BD0SkYDaxtS5K8IS0x1SPz5Xew1VUr4XyDbLRiYVA87OJ1DYQsxBYoKDwJ0XgxIMrVhItv4D7EPHgMxCr9ZwMNHGEibdlljyMfmqD7Qm8r93fbu3I/s1600-h/_DSC0308%5B6%5D.jpg"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; margin-left: 0px; border-left-width: 0px; margin-right: 0px" title="_DSC0308" border="0" alt="_DSC0308" align="right" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhgqMoKQGhrKYc0EmM3O26tTNS2_ZuUbJr3_MUsBauyX7Z-C70Ks4WAFrjx6HwfeFOA9tyP0qyIBiLhmvUEBZfU6muF8VHOJ0DUtUMNarZ5TaSSzz7lnjG9RTlYxn-N8FHb9HiR59G8qCU/?imgmax=800" width="413" height="274" /></a>Washington a few months back (maybe to talk the military air base). He was accepted as an official of the government even though he was dismissing the democratic process in Kyrgyzstan. Baisalov mentioned these two stories as possible causes for the apprehension of the attitude of the USA towards the new interim government knowing that they supported and even encouraged the corruption within Bakiyev’s government.</p> <p>He was also asked to talk about what happened during the uprising that led to the ousting of president Bakiyev. He mentioned a former minister of defense who was very popular among the military and critical of Bakiyev. This person was sentenced to prison for 8 years on trivial charges. During the uprising this person was freed and due to his popularity within the military helped secure their support for the demonstrators. Baisalov also mentioned that they recently had discovered 8 million dollar in a bank security box belonging to the previous defense minister (the one who had replaced the one who was sent to prison). </p> <p>When Baisalov continued to describe what happened during the days of the uprising he choked, after multiple tries. It was clear that the pain from losing close friends just weeks earlier was too much and to soon. 88 people were killed and 500 hospitalized during the demonstrations.</p> <p>He added his view on secularism, about the long term goal of reaching something like the social democracy in Scandinavia, about ways to make politics more about ideology and issues than about clans and individuals. Baisalov expressed following important opinion: “Even if we’ll lose the election we’ll win. The purpose is to gain a democratic system”. Much more was said but I cannot remember more specifics. </p> <p>The whole group left the event in a strange mood. What we just had heard was so very unexpected and unique. It is not often you get the possibility to visit a parliament after an uprising and talk to one of the leading opposition leaders and activists in the country, or listen to a politician that felt so honest and human. Everyone walked out from that meeting with a great hope that Kyrgyzstan might be the first real democracy in Central Asia, if the elections and everything pan out. But because of Baisalov’s very personal account everyone also walked away with a personal connection to Kyrgyzstan and its fight for democracy and human rights. Personally I and I think many others in the group will be following the events very closely from now on. </p> <p>In order to thank Baisalov for taking the time to talk to us, I would like to recommend to everyone to visit Kyrgyzstan. It is an amazingly beautiful country with a friendly and fun people. </p> <p>North Kyrgyzstan, near Issyk-kul lake: <br /><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiGWta3hkHtIptJfuvCUWTXvAcHn4CKzBmaBBkIkigtNIoxlptLt85Xa0GNBkMBKiRvIYe_3vQ7O_mk8M599QorOy_P7hRBzoiguFgky56S4Wgp0vfvlr5aPG6SLENdxWHuIGzzpLbZhGI/s1600-h/_DSC0155%5B9%5D.jpg"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; margin-left: 0px; border-left-width: 0px; margin-right: 0px" title="_DSC0155" border="0" alt="_DSC0155" align="left" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiOM6AdEW0JgSs4SVM6l9MBOV3heI0HU6tdgxj1V172z3oRZ4DeAb93yh4y8m4lY2YFFeJLxOij_7b_GllgmVwRzK8OWcLgsIyanV8kASKDYGaiWQt3H3875iDQ8E4OwMpkWek1EfUAozw/?imgmax=800" width="522" height="185" /></a> </p> <div style="clear: both"></div> <p><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgnn-vMQvuTf_Ci4tvhCcGL2v83rWleV8iZZ2M0DwqaMGyRMk0tqLlV53_ZMojfL03A04nUY9cBe1lVBW4caM6cc06DP0muDePL530NDHMbGwBz0FlSR0Vn8_TmyHj3sPVZcERtqoG1Uks/s1600-h/_DSC0136%5B6%5D.jpg"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; margin-left: 0px; border-left-width: 0px; margin-right: 0px" title="_DSC0136" border="0" alt="_DSC0136" align="left" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj4jjc04NgCNEgwvd0eAqabS_KBGE2IEvoGSM0zIFj-THkcBwpJ1w9X5jzbHOmYCPSSdD8NyBfQNNcywFQaMg_kAMWdNo5tu96pV-LTsvoDfwQD8QByaZ9jtJVGM88Nrnk1yOXzhdLSZz4/?imgmax=800" width="523" height="229" /></a> </p> <div style="clear: both"></div> <p>A very young goat herder that came and said hello: <br /><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhem53pBWB7Lejczb-npGY18Jik2LwoNLzOSjbC3r9n2kjRvcjh_HbzazfmCvSFvBs5WEHq9TcByFHYQ7wJ80LQ3JcE9IpiwqjqEznF30AVJJ9N2rDKYlV_xieBv4h4MYNtAHXcTLBxKb8/s1600-h/_DSC0189%5B5%5D.jpg"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="_DSC0189" border="0" alt="_DSC0189" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjD0YFPW5pQ0AA4w_Mqu0TPJnbt0NXlImbB2MZilqHCCpFJCYyVGqG86PK34QkQ8TWsJfs7VM8XjxlozT-N3FWL0vJqgh5_HL3lzSmRfmD1KHfRx1tXGxi9kNkGl0rpwpd9IOkrvxUZ6t0/?imgmax=800" width="534" height="321" /></a></p> <div style="clear: both"></div> <p>View from hotel I stayed at in central Bishkek: <br /><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhtd7B3u69CuCjJ6GwGYWBClD5HqR-xCtIGKgd8Uj05bsxETC0gau0wxjaJPOi2Ugctrdmm33eHKFs70t94p89TAXWGaQPG-VC9-u4qw6sjqZByFrPXSUeagGnAt48f0SxujZ093f-kQyQ/s1600-h/_DSC0255%5B6%5D.jpg"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; margin-left: 0px; border-left-width: 0px; margin-right: 0px" title="_DSC0255" border="0" alt="_DSC0255" align="left" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhhd77ZnX6QH-s71z6c2ZBUr4XlyWPklUkaqr6glzRiDCzvc4M_5ECn9p9H7vJelSfwz72uoSSBKDf86xUFwL5U7G9bGGIM25nhNOOvYbSRXL8E6b9b85e3llKIB9j0U2SBnNQb9Gc42fg/?imgmax=800" width="535" height="241" /></a></p> <div style="clear: both"></div> <p>Registan in Samarkand: <br /><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgmTBJsboBkwG8uUIR4BuaMGXxAIXYFJXzagGYkaN1vfJ7EjtOmIdCliK-L56CFCDNdpB1n0pHs-gu0omfgwytATEkcW7_-SwIEpCRMwPfrPFMvGxB_7fGtKZlDFvgaAq8JitH05XwW7OE/s1600-h/_DSC0382%5B5%5D.jpg"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="_DSC0382" border="0" alt="_DSC0382" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhukeFu6PEI8HbwEALjaC9VzaKo0w27U594RNH-MFHmZeVUuMen-7yt5WrBVJIT6ZYW-pxBvvbO4_MngLRieKvS6slXFpX3S5FKOTCABpRf1cIDrTfUsb-f6RxYrT1S1CWBC89OeJ36jA0/?imgmax=800" width="538" height="386" /></a> </p> <p>The cities were not what I expected, the cities Almaty, Bishkek and Tashkent where much more modern, clean and organized than I expected. But most of all they were green and beautiful, with parks everywhere and trees planted along every street. Still these are very poor countries, with vast differences between rich and poor and low expected living age. For example GDP per capita in Kyrgyzstan is 934$ compared to 52 000$ in Sweden (source <a title="http://www.wolframalpha.com" href="http://www.wolframalpha.com">Wolfram alpha</a>). But I encourage everyone who wants to experience something different to travel to Central Asia. I will definitely be returning, maybe a hiking trip in Kyrgyzstan!  </p> Unknownnoreply@blogger.comtag:blogger.com,1999:blog-3198935374994345981.post-78051470823421582272010-04-21T09:58:00.001+02:002010-04-21T10:03:07.631+02:00Visual studio color styles<p>I have blogged <a href="http://www.codinginstinct.com/2008/11/my-visual-studio-color-scheme.html">before</a> about my visual studio color settings. </p> <p>I just found a new site called <a href="http://studiostyles.info">Studiostyles</a> that allows you to create visual studio color schemes via an intuitive interface (using javascript). You can then submit the scheme and have other people vote on it. I just submitted my theme: <a href="http://studiostyles.info/schemes/coding-instinct-theme">http://studiostyles.info/schemes/coding-instinct-theme</a>  please vote it up!  You cannot select font type in the Studiostyles scheme creator, that is why it is displayed using courier new instead of the better Consolas font.  </p> <p>Screenshots: </p> <p><img alt="image" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhasUsjKcBmsRd11PuJx8Bfw0gnZ7n_eLrPm659OgHB60-1SvTw6-wohQtdtINl09_TbPLnGryI-niifEuJA4DIQTVO97YMacdD8Q6T6hk2hJeM-_yoVbLmVk3PBzDEn_LXs2E1TnSMR6Y/?imgmax=800" /></p> <p><img alt="image" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiBij7EKHhKJxxs_5mjELw0RgFyWBUjtqjo0JqJy4x7VqnIkXzguSXFk3g6DYG3T5Qlm_f-_yadpoA8EpDt9fpi5J6fmwMxL6wZJAswufqI4yvydCm3HysJDk2OI3oMCKGJuiY3GmI4lQQ/?imgmax=800" /></p> Unknownnoreply@blogger.comtag:blogger.com,1999:blog-3198935374994345981.post-49638947799026794712010-03-15T06:40:00.000+01:002010-03-15T07:37:32.833+01:00NHibernate Tip: Use set for many-to-many associations<p>I would not recommend that you use the NHibernate "bag" mapping option for a many-to-many association, for example: </p> <p><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEghX72y2STbeLtjYu5f6aFxHHDszvjRZwCQr5gcgK3P0Ov4mgcGot5qR14TwWLi54pJ5Nh6n4qmKZmyxLhrQMS_bD300WKBz2OhGfmeofGy2qu-XM9gP37MKNwP2jH6a6oV1uh-xzhc77k/s1600-h/image%5B4%5D.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjajtiT3eZwZbeafmYdezYsYcCCy-OOsKzEyLPQkVZD4ma4pjeBbQ8ElTXo_VUsOZyyq9j9hJE46PahRful5bIE0XWcQCxxis2ZWrkuapQfN3y8bxxy0M99m31NXaTcMKT_d4PiiRlfLpA/?imgmax=800" width="654" height="95" /></a> </p> <p>Never mind the strange domain, it is for a upcoming NHibernate presentation and I was too bored with the normal Order > OrderLines example domains.</p> <p>The reason why using a bag for many-to-many is not recommended is because of the poor update behavior you get. If you were to load an entity (RebelEncounter in this case) that has a ShipsLost many-to-many association and just add another StarDestroyer to the ShipsLost collection like this:</p> <p><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhvCviOLCAKvvsIeTzMPdr0J-FOtSeHepfTyV2epfCjsr6h8YbH4oT6la_H-s0LQeykEaAsN9dSmnLO3ZWtRc77otthTOX__i4nA9gQcq4ZgH5zNTVM9V9FODMwttmXjoj10AI_0n1-Gr8/s1600-h/image%5B9%5D.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhjrK8jiF2uVu9l78QlaAoouNEGZ-cSCQUNZXsM6sG-4JkXrma8T8G376sT03kQWQ3ko8CADrnXL43Jqow_WDoPLKb4Gs-ozwsLCG3P7X-3C-SPTPCt2k1pD_fmmy8JyTRAgbQGA1RtNa8/?imgmax=800" width="784" height="205" /></a> </p> <p>This would be issued to the database:</p> <a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiwAMvYKAYxzCrzQsv43e0D9ldFGYZJAVt72XzK8ZQBdrLpkfRWXC5BpXpjJwh1OluQ1R1qC3U1qozszWdJCf4rLfHr9p7oSGMEVw0ZWqoQe9Dr9E6cyOWzz5Q6mSc580zWMy0vlqivLg0/s1600-h/many_to_many_using_bag%5B4%5D.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="many_to_many_using_bag" border="0" alt="many_to_many_using_bag" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiraECma9_ASg-VEX8Cu0XGVWE1hNahK_P6w9gARiFIiyPZA53qGYLvyLFzp9S6L8VdHN_NMDZPTimkM27xs8R9fkLRCvKmio-oqr6w9-GKp35-pWR7GmFxSt5MTZMmzpYNt39OO4Eikc0/?imgmax=800" width="856" height="384" /></a> <p>As you can see all the existing ships where deleted and then reinserted (along with the single new one you added). You can probably guess that this is far from ideal from a performance stand point. However it is easy to fix. First we have to change the mapping from bag to set:</p> <p><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjy6ZVkeDvPY23Nne-776TwQCsj8BSf9sQX7NhljSyb4J39rbFSyHiKPp_7ugfUW4XOESYgXoZkB627vAznVKwBhhQMZ0ELVungNw70SyakMS8vDp4SPWXjkVcj6QI01KFryH65-3viDZc/s1600-h/image%5B14%5D.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj0SnlIh63US7Urj-OGSeuG2pwnA03o0s_-KkRpGxxMvOZaxZK0dT32E0qH_jNDJFLMGInnUg2BALiBpGvBUHgeHldnyzP92qbWwRgYpYcqpMzdMWDWy4alPgkkzeTkIQFZJBB1MkyW70o/?imgmax=800" width="666" height="94" /></a> </p> <p>NHibernate will use the HashedSet type from the Iese.Collection framework as the collection type when using the set mapping, that means that the type for the property can no longer be IList<StarDestroyer> since HashedSet does not implement that interface, however it does implement ICollection<T>. So we can change the code to something like this:</p> <p><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjohJP4kAFvqgx2ZqpsudZ6IiCHTTFnSzIySGpugnHksahkJjuZL7fjPFHQElCRTxlSADGlu9QZH8BV2pteMtv-DsZFZe_caDCfCTs_QHIfNwFEun3ED7V3P1x7NkzvUcoLSUzUm1Hx3i8/s1600-h/image%5B19%5D.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiLty52umcdIt0UF6zdWhXgaIp-IUDzONABb9t26oeev3JKCn5Lx-2qGlQgTioONKTfYBgJjSzw4nrHNGDefDTudwEr7cSJSKgwKSXCiC0gdqh5Rtv2MoA_5b3592ZgRbuSrAag61hXWC8/?imgmax=800" width="773" height="189" /></a></p> <p>With this change NHibernate will now only insert the newly added entity:</p> <p><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiwgB8fISYM6DHo2Ba98zIDzq1VilR730CeBqWRRY-HsSVKrcRuQfQNX038yYZK1cfoEjo4rfIDRs5ffP0u8VavgsPXPCudRUJqF96qA_88bhXjguDjtXxbpuuegoQbHJy6yZrmQblY984/s1600-h/image%5B6%5D.png"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="image" border="0" alt="image" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhgwrrc6SdPUBMiRsRXQHLsCc5gaQe49Sw7SAkkmayC-25Ge7eGowWiC3JgTnniEkhAr2IHatqNpNhCPt4xUPmOp_D7_1fciRm854r6CpFnCT8rZhzqWIwovtUbRwZ5h1y3GsW235ZtrBQ/?imgmax=800" width="640" height="256" /></a></p> Unknownnoreply@blogger.comtag:blogger.com,1999:blog-3198935374994345981.post-79164549523988924302010-03-10T22:58:00.001+01:002010-03-11T07:07:34.847+01:00ASP.NET MVC And Convention Based Forms – Part 1<p>Series Index </p> <ul> <li>Part 1: Reusable controller actions & model inheritance </li> <li>Part 2: Custom meta data provider (coming soon) </li> </ul> <p>One of the great new features in ASP.NET MVC 2 is the template system. It is very similar to the template form helper system introduced in MvcContrib for MVC V1. For more information on the MVC template system read Brad Wilsons excellent <a href="http://bradwilson.typepad.com/blog/2009/10/aspnet-mvc-2-templates-part-1-introduction.html">series</a>.  </p> <p>This template system allows you to create convention based views and forms. The scenario that I have been working with the last couple of days is forms for reports. These forms are all very similar, that is they are all built around a couple of report filters/parameters built using dropdowns, checkboxes and datetime pickers. </p> <p>My idea was that each report would only consist of a new report model and the most of the views, and controller actions could be reused. </p> <p>Example: </p> <pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">class</span> <span class="type">ReportController</span> : <span class="type">Controller</span>
{
<span class="kwrd">public</span> <span class="type">ViewResult</span> ViewRequestForm()
{
<span class="kwrd">return</span> View(<span class="str">"ViewForm"</span>, <span class="kwrd">new</span> <span class="type">RequestReportForm</span>());
}
<span class="kwrd">public</span> <span class="type">ViewResult</span> ViewOrderForm()
{
<span class="kwrd">return</span> View(<span class="str">"ViewForm"</span>, <span class="kwrd">new</span> <span class="type">OrderReportForm</span>());
}
[<span class="type">HttpPost]</span>
<span class="kwrd">public</span> <span class="type">ActionResult</span> ViewReport(<span class="type">ReportForm</span> form)
{
<span class="kwrd">return</span> View(form.GetReportParameters());
}
}</pre>
The idea is to be able to reuse the same root view and the same action for all forms. The root view is only going look something like this:
<pre class="csharpcode"><span class="x_asp"><%</span> Html.BeginForm(<span class="x_str">"ViewReport"</span>, <span class="x_str">"Report"</span>); <span class="x_asp">%></span>
<span class="x_asp"><%</span>=Html.EditorFor(x => x) <span class="x_asp">%></span>
<span class="x_kwrd"><</span><span class="x_html">input</span> <span class="x_attr">type</span><span class="x_attr_v">="submit"</span> <span class="x_attr">value</span><span class="x_attr_v">="submit"</span> <span class="x_kwrd">/></span>
<span class="x_asp"><%</span> Html.EndForm(); <span class="x_asp">%></span></pre>
<p>The EditorFor helper is going to start the MVC template engine. This template engine is first going to try to find a matching editor template for the report form model, since no specific template exists it is going to fallback to the default template for object, this template loops through all properties defined on the model and applies an editor for each property. </p>
<p>This is how the RequestReportForm and OrderReportForm model looks like: </p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">class</span> <span class="type">RequestReportForm</span> : <span class="type">ReportForm</span>
{
[<span class="type">DisplayName</span>(<span class="str">"Include canceled requests"</span>)]
<span class="kwrd">public</span> <span class="kwrd">bool</span> IncludeCanceledRequests { get; set; }
[<span class="type">DisplayName</span>(<span class="str">"Some parameter"</span>)]
<span class="kwrd">public</span> <span class="kwrd">string</span> SomeParameter { get; set; }
<span class="kwrd">public</span> <span class="kwrd">override</span> <span class="kwrd">string</span> GetReportParameters()
{
<span class="kwrd">return</span> <span class="str">"RequestFilter="</span> + IncludeCanceledRequests;
}
}
<span class="kwrd">public</span> <span class="kwrd">class</span> <span class="type">OrderReportForm</span> : <span class="type">ReportForm</span>
{
[<span class="type">DisplayName</span>(<span class="str">"Group by status"</span>)]
<span class="kwrd">public</span> <span class="kwrd">bool</span> GroupByStatus { get; set; }
[<span class="type">DisplayName</span>(<span class="str">"Some other paramater"</span>)]
<span class="kwrd">public</span> <span class="kwrd">string</span> SomeOrderParameter { get; set; }
<span class="kwrd">public</span> <span class="kwrd">override</span> <span class="kwrd">string</span> GetReportParameters()
{
<span class="kwrd">return</span> <span class="str">"something"</span>;
}
} </pre>
<p>With the default templates built into MVC these models will be rendered like this: </p>
<p>RequestReportForm:</p>
<p><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj-R9TOQ_8GJ3TR_y9PNG2X3o3VyRM45XnZI6KmNRABIUXWonmmZX0G32LO14cZ6NY2EH4yb4-gVdwobNVoc29-ewxvPyfjl4bhYALHJJ7wI8wQ7HqZFDTitN2rLOiR9H-E4_NgGUdFucU/s1600-h/image%5B15%5D.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; margin-left: 0px; border-left-width: 0px; margin-right: 0px" title="image" border="0" alt="image" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjDe6I_o0YxBTQkMgbPHeMIqdwDi6uFjiPoyD6vBsx8Gkx-XxPXfURCyldAUpNoHXIB2aYqyHkGUdNSw8ngcxTbA-7r9f_HqJwusHQQRwDmdDo6c_gXvRqHinjSx0F_gD2wBp9RGAva3jI/?imgmax=800" width="232" height="138" /></a></p>
<p>OrderReportForm:</p>
<p></a><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgbiN3jFvCV4KQP3dqDBuxcdEa_dxsm40foA-j9GB7WavQxqm11HEAr4NUwcnpoQq0HO6ZYwvw6iYz47TtIwnAHvYjVh_o0f5Uvqa6EKVe24jL2CzECaAodtj8zmQGNNfxWBZfeEpY9IFM/s1600-h/image%5B14%5D.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; margin-left: 0px; border-left-width: 0px; margin-right: 0px" title="image" border="0" alt="image" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgMeqAdy1OUgdHJmi6sCbLbH4OE3U-n-P3X4mNFgypjo_QGOHyqbA_vU7mhx5Lyt_sJqdjstsTFRt428Y6PbOe6DJMqk1T0ueRwwjVVwfaphamXYFCeNO81zgIiv4a6p-ZjxDbMFvX07HE/?imgmax=800" width="240" height="128" /></a> </p>
<p>If we would like to override these templates all we have to do is create our own partial view and name it string.ascx or bool.ascx and place it in a view folder named EditorTemplates, hopefully more on that in a later part in this blog series. </p>
<p>So sharing the same view for both of these report models seems to be very easy with the template system built into MVC 2 but how do we use the same controller action? We want to use the the controller action ViewReport that takes the base type ReportForm as a parameter. The standard DefaultModelBinder will not know which concrete class to bind to. The solution to this problem should be to create a custom model binder that will figure out which concrete form model to instantiate based on some field coming in the post data from the browser. </p>
Example:
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">class</span> <span class="type">ReportFormModelBinder</span> : <span class="type">DefaultModelBinder</span>
{
<span class="kwrd">public</span> <span class="kwrd">override</span> <span class="kwrd">object</span> BindModel(<span class="type">ControllerContext</span> controllerContext, <span class="type">ModelBindingContext</span> bindingContext)
{
<span class="kwrd">var</span> reportFormTypeName = bindingContext.ValueProvider.GetValue(<span class="str">"ReportFormTypeName"</span>);
<span class="kwrd">var</span> reportFormType = <span class="type">Type</span>.GetType(<span class="str">"MvcApplication1.Models.ReportForms."</span> + reportFormTypeName.AttemptedValue);
<span class="kwrd">var</span> model = bindingContext.ModelMetadata.Model;
bindingContext.ModelMetadata = <span class="kwrd">new</span> ModelMetadata(<span class="type">ModelMetadataProviders</span>.Current,
bindingContext.ModelMetadata.ContainerType,
() => model, reportFormType, bindingContext.ModelMetadata.PropertyName);
<span class="kwrd">return</span> <span class="kwrd">base</span>.BindModel(controllerContext, bindingContext);
}
}</pre>
<p>This custom model binder looks for a form data field "ReportFormTypeName". With this name it is possible to get the .NET Type (based on some namespace convention) and thereby create a new ModelMetadata object, now we can call the base implementation. All we need to do now is to add this ReportFormTypeName field as a hidden field to our form. Lets add it to the base class ReportForm, like this: </p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">abstract</span> <span class="kwrd">class</span> <span class="type">ReportForm</span>
{
[<span class="type">HiddenInput</span>(DisplayValue = <span class="kwrd">false</span>)]
<span class="kwrd">public</span> <span class="kwrd">string</span> ReportFormTypeName
{
<span class="kwrd">get</span> { <span class="kwrd">return</span> <span class="kwrd">this</span>.GetType().Name; }
}
<span class="kwrd">public</span> <span class="kwrd">abstract</span> <span class="kwrd">string</span> GetReportParameters();
}</pre>
<p></p>
<p>This is actually all we have to do to get the MVC template system to generate a hidden field named ReportFormTypeName that will contain the name of the concrete Type. Since both RequestReportForm and OrderReportForm inherit from ReportForm and since the default template for object will loop through all properties (including inherited properties) the hidden field will be included for all report forms. </p>
<p>So what have we accomplished? We can generate different report forms by only creating a new form model, the view rendering is shared and the controller action to generate the report is also shared. The controller action that handles the viewing of the report is in my case only responsible for concatenating all report parameters into a querystring to then pass to the report system, since this is so generic it can be handled in the same controller action for all report forms. I hope some of you understand what I am trying to show here, and I also hope to expand on the ideas in this post in later posts. Specifically how to make the report parameters more rich and how to control and override the layout using custom editor templates and custom metadata. </p>
<a href="http://www.dotnetkicks.com/kick/?url=http%3a%2f%2fwww.codinginstinct.com%2f2010%2f03%2faspnet-mvc-and-convention-based-forms.html"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fwww.codinginstinct.com%2f2010%2f03%2faspnet-mvc-and-convention-based-forms.html&bgcolor=0033CC&cfgcolor=FFFFFF&cbgcolor=009900" border="0" alt="kick it on DotNetKicks.com" /></a> Unknownnoreply@blogger.comtag:blogger.com,1999:blog-3198935374994345981.post-39886059606133907322009-11-01T20:37:00.001+01:002009-11-02T08:05:45.252+01:00NHibernate feature: SaveOrUpdateCopy & Merge<p>One of NHiberantes features that I haven’t seen mentioned in the documentation or in blogs concerns the the two methods on <em><strong>ISession</strong> SaveOrUpdateCopy </em>and <em>Merge. </em></p> <p>Lets say we have an backend (i.e. application server) that has an operation called UpdateOrder. </p> <p><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhtbuJxYyvVuA66VKXDXtIie4nrJODYj2zEHh3s7RFn218JU0y4fOsOiwGlXmaMSgjgj_a3Ht2fQr0HIzn19G6ndTj9eQkOVkgzyCHOhLYPfABJVQfawMMKjcruj-OZ7HwZvzY7NQp-YZA/s1600-h/image%5B8%5D.png"><img title="image" style="border-top-width: 0px; display: inline; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="355" alt="image" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi83XoFEPtbk23OGK8-R_zXnPD-o_cKHfd_1cQvLhSEiWtxnobvDHHdp6BXoPOGxMKOKBTeXfsisNcwAmnbIm8WP8zag5YXHoHebHzyM-CisQ07FAjis91UFBynknikwjxeWumm1l9itew/?imgmax=800" width="460" border="0" /></a> </p> <p>The UpdateOrder message contains a complete order. The normal scenario here is that the backend translate the order contained in the message to a domain model that is then persisted to the database via NHibernate. The problem with an update scenario like this is that the order that is coming in from the client could have missing order lines. If you use the normal ISession SaveOrUpdate method the order line that was removed on the client and therefore missing in the UpdateOrder message will not be deleted in the database. </p> <p>Why won’t the missing order line be deleted from the db? Well consider this normal update scenario:</p> <p><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhEL8eRs824TaL6JnTu9NgBw7EKjNV28s_ClcSF5pGUSvNBVHp7tqWsYR-IAI67slF7m6IEmY1H3onfFT9CwqPxxD_rcpXuoKgnVSEPU_cAQjJwDH6YQhx4A1Rve8U_YnN6eJfxWlyVclc/s1600-h/image%5B15%5D.png"><img title="image" style="border-top-width: 0px; display: inline; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="201" alt="image" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjlo6ztzreovcITLYB4pznvnCC-C0HrlTvLaKN46CWH5fIoMAZRKXF-tsCaLhFl313BL2Rv4g3dqKa_kvBU467ybE4fGGdczn6-vfI1RsPZ_TrhP0Jll6JkI8Bc0KaEjp8j4WTtjwsL9hM/?imgmax=800" width="384" border="0" /></a> </p> <p>Here the order line is removed on the instance that is already attached to an open NHiberante session. In this case <em>SaveOrUpdate </em>will work perfectly because NHiberante can track the removal of the order line. </p> <p>Consider this case (that represents the client –> backend scenario I mentioned above)</p> <p><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjUfKRk-67kcPbf96irCNdbHKZJfyZsgUx8QaPwdbZIUKQeDjfYciFyqqB826UOntYsHKVHjXLGPbnzV_TBTvkEhDDuLfYzM4dZYxPFgDpkTfvELh-4BMO55wR_WmrwsDO-npdeQ-B72Fc/s1600-h/image%5B25%5D.png"><img title="image" style="border-top-width: 0px; display: inline; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="174" alt="image" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiVINpZKwCAdjB8y2Xx3Vh8lQgnjptHRAuMgEFXnEWVP4R3RtKQQHkaBWDFPbEIRVygHttbIgQFfFbW09SecrIerbj7ZH-6ejX1gAeVIl61Q0ulKyJ6JZXy8Yhq1zT03YN-qlMOBFqzKWk/?imgmax=800" width="413" border="0" /></a> </p> <p></p> <p>Here we try to save a detached instance which means that NHibernate’s dirty tracking and tracking of collection removals will not work. </p> <p>How do you solve this problem? One approach is to fetch the order from the db and do a manual merge of the changes.  The current system that I am working on has a data access layer that is using LinqToSql and there are many, many update scenarios as described above. The amount of code to manually merge and figure out what has happened with all relations (added / removed order lines for example) is quite substantial. </p> <p>For the last month we have been bit by bit migrating the data access layer to NHibernate. First I thought that this issue of updating detached objects would be a problem that we still needed to solve manually but then I discovered <em>SaveOrUpdateCopy</em> and <em>Merge</em>. These two functions does exactly what the old DAL did manually, that is before the update it fetches the persisted object from the db and then merges all changes from the detached instance into the persisted instance automatically, including orphaned child deletions!</p> <p>Ex:</p> <p><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiDiqsx2Er7X4G0iwP7tsjg0GoVbQCqDWnwTM7iWxU4NGYa_WDQwDNxbWXj439lW4zlEAaLocqNPPA0sYniRsCFNC-Ix592eoZd2yYadBygpsAxJj3bJhwcWnslVk8fCBpMiTgkNalpRP4/s1600-h/image%5B35%5D.png"><img title="image" style="border-top-width: 0px; display: inline; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="196" alt="image" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjkGWaFRrCUF6rytY3fbmyW-VGSqifT453LgECMSXJQfG0MdbwKiyKYvZEqPw5qcTNiww4BWGLJpNcXiVUJjL_HrLYaRW7jzzyIjKu7RI8-azDOsGhDB8t_MdsDmaYRDuGlZTR7JXUH6pU/?imgmax=800" width="363" border="0" /></a> </p> <p>In the above code I modify an order line and remove another. Both operations are on a detached object. Then using SaveOrUpdateCopy we get this:</p> <p><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgZZVXg9GToyTTroURX3Gd6YxDfCNmiCxM4UdSo7gmas3FRjJ98feF5P3df_HG8Bqq7p7XF9FwtEci9MQfutK5__Tku4tr63Wh6LO9dEurshvH1DDgn7KPGRLQZ9Wq5bz6dVDO_RPIAP-M/s1600-h/image%5B30%5D.png"><img title="image" style="border-top-width: 0px; display: inline; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="171" alt="image" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh9o-QpbktvyIQPu2LdIV_gn9Cd0QUOKmKhJ7me84o66yFdvI58cMekeHxphNQINTaZp3zt6IwjP8HDb-WxejS02jgSog6vGSdm5YQhpG6YOs5PmZJA8Uyh9Qmdbztvu2YHq6GncqSZr-Q/?imgmax=800" width="616" border="0" /></a> </p> <p>NHibernate fetches the order (in one statement by joining in the order lines), then performs the merge, figures out that one order line is updated and one is removed and issues the correct database calls. Is it just me but isn’t this great??? This will literally save thousands of lines of code!  </p> <p>The <em>ISession.Merge</em> function basically does the same (from what I can tell). I am not sure really what separates them, except that there is cascade option named “merge” that you can set on relations to control how cascades should be propagated during merge operations. </p> <p>Here is the API doc for Merge:</p> <blockquote> <p><em>Copy the state of the given object onto the persistent object with the same <br />identifier. If there is no persistent instance currently associated with <br />the session, it will be loaded. Return the persistent instance. If the <br />given instance is unsaved, save a copy of and return it as a newly persistent <br />instance. The given instance does not become associated with the session. <br />This operation cascades to associated instances if the association is mapped <br />with cascade="merge". The semantics of this method are defined by JSR-220.</em> </p> </blockquote> <p>I think SaveOrUpdateCopy is something that has exited in NHiberante for all time and Merge is something added in 2.1 (clearly something ported from the hibernate). Anyway I am very glad that NHibernate has this ability because writing and handling the merge operation manually is very boring code to write!  </p> Unknownnoreply@blogger.comtag:blogger.com,1999:blog-3198935374994345981.post-39170839883479753222009-10-28T20:53:00.001+01:002009-10-28T20:53:22.375+01:00WPF and databinding to dynamic properties<p>One useful feature in WPF 4.0 is the ability to databind to dynamic (runtime generated) properties using the <strong><em>DynamicObject</em></strong> as a base class or implementing the <strong><em>IDynamicMetaObjectProvider </em></strong>interface. I am currently working on a WPF application and this ability to bind to runtime generated properties would have been very useful in a previous story we implemented two weeks ago. </p> <p>The story concerned merging two object graphs and then visualizing what properties that were changed/conflicted in the UI (for example with a different color). </p> <p>In order to not add “XXX_HasMergeChange” for every property in the presentation model we solved this by using a value converter and some WPF binding magic that some might call a HACK. The solution was only partial as it only worked in the Grid and not on everything else. </p> <p>If we had WPF 4.0 we could have solved this like this:</p> <p><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiicb84ytZ56gv7jf81q77lzcfgA1CELbII63biVzp1An9zwgDqSKPWw1ZU15Nois1y8RTf7LO8XpXWP2J2deMg8pSH9NQ3b60f3FMBTUDnhCKssof94_6jGPRqaEBpp-dY2mRHKBwGqAI/s1600-h/image%5B9%5D.png"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="image" border="0" alt="image" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi9seHGAlkOEOiCzwBkxfEeJqdbX6qRxwAHF3K3OeMOWVi1tlaxAYs9wCmw_QCPcEZNI6QS5G_vwAykKev-G7rMsbiMF-dniJ7nyrefnkOlVbbOjqGrIGUhjg-4c_PiS5rEHXhKu03fqxQ/?imgmax=800" width="633" height="203" /></a> </p> <p>In the above style trigger the data trigger is binding to a property that doesn’t exist on the presentation model. How does WPF then get the value for this property? By calling the TryGetMember method:</p> <p></p> <p></p> <p><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiOQCsG7ImeVcnk-8VHi2BLyzRTT3BalY3dhzbMYlD4B3690yAJ58mzdzMo5ONkUXi7eYQDewNSz2A02WIXKxV8sS2gne_kyfFnWJ4mD4haInaQKgwhd9dDy34_sUogqQgLl9WORyMa8JA/s1600-h/image%5B14%5D.png"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="image" border="0" alt="image" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjdZ3X-Qp5YtTVPQcpjJoUfyE-JwcFjpBC5YXKkQvmu8nGfQdeicGs39x_MyV_AK1w4boQ2CWl_781N5BeG0Zvm1oFbRShv0kG8nKPlGcMPsJhOhLvoya9xD2Aip5CRofkRvkjXmQZg07o/?imgmax=800" width="693" height="337" /></a> </p> <p>WPF will call the TryGetMember and that will check if the property ends with “_HasMergeChange”, if that is the case it will try to look up the property in the MergeChanges dictionary. </p> <p>The above is just a simple proof of concept, if I would go forward with this I would have to figure out a more generic way to define the style and data trigger to be able to reuse the xaml style markup for example, but that shouldn’t be a big problem. I also tested property change notifications using the <strong><em>INotifyPropertyChanged</em></strong> interface and they work for dynamic properties as well. </p> <p>To learn more about the new features in WPF 4.0 read ScottGu’s <a href="http://weblogs.asp.net/scottgu/archive/2009/10/26/wpf-4-vs-2010-and-net-4-0-series.aspx">recent post</a>.</p> Unknownnoreply@blogger.comtag:blogger.com,1999:blog-3198935374994345981.post-28747701087516525132009-09-24T22:08:00.001+02:002009-09-24T22:11:00.920+02:00A Bug in Except?<p>Among the Linq extensions methods that came with .NET 3.5 is one called <em>Except. </em>This method takes two lists (first and second)</p> <p>The MSDN docs say:</p> <blockquote> <p><em>This method returns those elements in first that do not appear in second. It does not also return those elements in second that do not appear in first.</em></p> </blockquote> <p>This appears to be a lie. Review the code below and guess the output:</p> <p><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjGn1L1K0NQsrhJgKIvvp0p0sch_N0iVmgyb2ACvitIeOmRE9AGiCVphOqD4IWVieQeC1czg6vxd18YDbZ-2ZHLBqFnyOJtt7ZNzA23u_afHx9-Zlc8kK_VD1aHToTbmj-jgUBrVufAfV4/s1600-h/image%5B8%5D.png"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="image" border="0" alt="image" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiY0aKCjy0YQpooHWTr4KEQF70VA6TnkQGpCrb-Ots0gL6aW7o_s43akqtDU4ufl5pU1VF1CRc85skWsiVaOYMZuevQxZWE5Tt29UP0r47VvRJ3NFZgLP0VGyFI1tvBaBcJL6PgjpUSn6Q/?imgmax=800" width="384" height="650" /></a> </p> <p> <p>The <em>User</em> object has overridden the <em>Equals</em> and <em>GetHashCode</em> methods which the <em>Except</em> method use to determine equality. Since there is only one object in list2 that is also “equal” to an object in list1 I would expect (granted the MSDN docs are correct) that list3 would contain three users with the id zero. </p> <p>The actual result? list3 will only contain ONE user object (with id zero). When I debug I see that Equals is called to compare objects in list1 with each other. </p> <p>Using reflector I can see why, <em>Except</em> is implemented using the internal class <em>System.Linq.Set:</em></p> <p><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiIO9Ixz7ASvRh1LzWG9XFzmXIxNkKHbhJrT_Zp366HspIOXu6OZcIKhMzxY1P5yjVATjDe-KOpY-XfBrBzW2dLBcYMj6TLZC4V1usWecB0uuPj5bNrQZB0yVlHLz7SZtD0WzTQCGCpmVI/s1600-h/image%5B17%5D.png"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="image" border="0" alt="image" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgkDY7elRePjaw-HhYnDmW2dFj7NPuhF-QI1uiO8dPgMRhygm_U9DCMfx1blJQqDLgDi3Ica71SCV_zRbllNrJmKnU2OWaVT4PxWOymiqhrBPqCgeT4M_JtKZaHIbsRlQrPB4oY8AF96ps/?imgmax=800" width="470" height="254" /></a> </p> <p>It starts by adding all items from list2 into the set class then for each item from list1 that <u><strong>can</strong></u> be added to the set it yield returns. This filters all items from list1 that are equal to an item in list2 BUT it <u><strong>also</strong></u> filters all items in list1 that are equal any other item in list1! </p> <p>Maybe not such a common usage scenario, and I don’t recommend overriding <em>Equals</em> and <em>GetHashCode</em> in this manner. Anyway frustrated by this because I burnt an hour on debugging before figured out it that what was to blame.  </p></p> Unknownnoreply@blogger.comtag:blogger.com,1999:blog-3198935374994345981.post-62733693860653505842009-08-26T12:55:00.001+02:002009-08-26T13:01:05.787+02:00Profiling NHibernate Batching<p>NHibernate has pretty good support for batching, something that can significantly increase performance when inserting or updating large number of objects. </p> <p>Example: </p> <p><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjNIF5h2XG3lt5vBOidwhWfR1YJpDXyLmkbQ_NvDBHYmPrbI3hdYLSVV8Yr75WndHtTTE57d8oTcA8nlJ5EqfN2wI3Q5DGPHha-RQCeg8MjIcq1p7PgwdthYJe2nRTSrDEhwTqwLnIIhB4/s1600-h/nh_batching%5B5%5D.jpg"><img style="border-right-width: 0px; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="nh_batching" border="0" alt="nh_batching" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhAvTviQCcsuZt1HpA5HmSVlcFK_62bXl0ysJ4eLC_nVSasmUqh8ibZ7SMj6uR9LMvVvLrGvRJleH7fA6Lz61UsvyL_kl1xNXdtm2iXZMhP6Sbl572KYHEibtDS8Oxv1Hu4tzZsWkI2ZCg/?imgmax=800" width="400" height="300" /></a></p> <p>In the above example you can see that the order lines are created in one statement. In a recent mail conversation with <a href="http://blog.lowendahl.net/">Patrik Löwendahl</a> he asked for assistance in getting batching to work. The first thing to check is what id generator you are using, you cannot use native (sql identity) id generator and expect batching to work for inserts. The reason for this that for identity inserts NHibernate issues a "select SCOPE_IDENTITY()" statement after each insert statement to fetch the generated ID. If you want to use batching for inserts you need to use the guid or hilo id generator. </p> <p>Another issue i came across was that batching does not work as you would hope for associations. For example if you want to save a thousands orders and each order has five order lines, this would result in six thousands calls if batching was disabled and two thousands calls with batching enabled. As you see in the screenshot above, batching is only done on the order lines and not for everything. </p> <p>You can optimize further by using the stateless session. However inserting entities using nhibernate’s stateless session ignores associations. But by looping through all orders and calling session.Insert(order), and then doing a nested loop to do the same for all order lines you can insert all orders and order lines in just two calls to the database. </p> <p>The problem Patrik had was very weird and confusing. To verify that batching was actually happening he used SQL Profiler, while I used NHProfiler. The weird thing is that they show a very different picture. NHProfiler shows order lines as being issued in one command while SQL Profiler shows them as separate RPC calls.</p> + <p><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEirM786zUGPye7jr7hybGK2qBzgw8CX1iJzrxmZ8j0Z6-vqBhC0OWdKHDclRsDUpXwAeXv2iNvGek4Uv8SFNHpn21H3RwhCjlddHzSQltabIeI2Ga3DBt_biPjXpoQiFJsktjelDmsYKxI/s1600-h/image%5B5%5D.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi36IhxepKw6nxgPdbuzeLyTyXDxgQxk_Ld_ah7qgUg2u9UkxrcLgTga87hFJmET-BhBCVWWpVQLcVEbPrPXtTDg-8G1ZNUaQRN8uWkvXTUGUnYobVjoFxivbtCkOPDCD1rLH_gPzDnnYU/?imgmax=800" width="535" height="159" /></a> </p> <p>This result left me very confused. The NHProfiler result clearly indicates that batching is being used but SQL Profiler shows the same results as when batching is off. However when batching is enabled the performance is significantly better, what is going on here?? After some Googling on SQL Profiler and batching I found this comment on <a href="http://stackoverflow.com/questions/970473/batch-sql-inserts-in-net">stackoverflow</a>:</p> <blockquote>On MS SQL Server, SQL Profiler shows each insert statement seems to be on it's own. After reviewing your comment, I viewed a TCP Dump of the conversation and do see that it is batching multiple commands together. SQL Profiler shows each insert as a "RPC Completed" event which was confusing me. Thanks for your help. </blockquote> <p>I appears that batching <em>IS</em> being done but not like I thought it would be (for example a Batch Starting command in SQL Profiler). The difference, when batching is turned on, is that all the statements are sent to the database in one go without waiting to listen for a response. That explains the SQL Profiler result, however I still find the NHProfiler result puzzling as it indicates that the order lines are created using a single call to sp_executesql.</p> <p><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh7o97gBnH0urUZqxIzcfQBIOwOsCia1pj0YBhxF2CalMx1aKNuanMrJCR6rslVVADkcHPpx3qnAyg-ya7TTJpghLXYWsuk8AHj6-mb3g9UhV6v1gunNYsJ-vp9_upz4ZcXnVJPnhIYE0M/s1600-h/image%5B9%5D.png"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="image" border="0" alt="image" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh7jLr77LMj9lgBD6EXWJ1ob7yE28ccRUyPTtNHHs57UqDRalWW96XR5iioM8tTN-fexm8YV7QphPsoeVCZ8TfiQLbwgSxibzY7PYrDq3SuxcNL-xrHXf5W3tlEFpkER89rbXxDO_3rTBQ/?imgmax=800" width="240" height="158" /></a> </p> <p>Ayende care to explain? :) </p> <p>Some links on NHibernate batching:</p> <ul> <li><a href="http://davybrion.com/blog/2008/10/bulk-data-operations-with-nhibernates-stateless-sessions/">Bulk Data Operations With NHibernate’s Stateless Sessions</a></li> <li><a href="http://ayende.com/Blog/archive/2009/08/22/nhibernate-perf-tricks.aspx">NHibernate Perf Tricks</a></li> </ul> Unknownnoreply@blogger.comtag:blogger.com,1999:blog-3198935374994345981.post-20048207296188302712009-07-21T09:02:00.001+02:002009-07-21T09:02:23.581+02:00NHibernate 2.1 Released<p><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi8u29-f-zWRy67oFn_jyEhRuMTCoWAue1l954O_OZscoZjYHtE64EM-4PYViI7oACA6dIzA9lqR2kUKzEUpzIrWgz6t7z4zCw0F1l3PA7LBeyAAJbt3GNMW8rLwOLA2w6bGufvNZDIIdw/s1600-h/image%5B10%5D.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; margin-left: 0px; border-left-width: 0px; margin-right: 0px" title="image" border="0" alt="image" align="right" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiGTD7v1Bz9WT_t55OAUwdLjRwYuHl3fQx4onjKiDqENveX_ToYGt4z9m2R5Y_CbY_1nr0AOv350tIO8GaPzeIyCH6a7vsySXMI7XYoyhN__SzsL-q6n3Wq31Ag4W1FHp3arFly3Dg9b9M/?imgmax=800" width="300" height="112" /></a> There is a new release of NHibernate available, <a href="http://sourceforge.net/projects/nhibernate/files/">download it now</a>. It contains a host of great new features, like support for Dependency Injection for entities using an inversion of control container of your choosing. There is also a new ANTLR based HQL parser that has allowed for some HQL improvements, like the <a href="http://nhforge.org/blogs/nhibernate/archive/2009/05/17/nhibernate-2-1-0-hql-with-clause.aspx">with clause</a>.  The new ANTLR based HQL parser is also central to the forthcoming LINQ support and is the result of some great work by  <a href="http://blogs.imeta.co.uk/sstrong/Default.aspx">Steve Strong</a> and <a href="http://fabiomaulo.blogspot.com/">Fabio</a>. </p> <p>This release also includes the long sought after support for <a href="http://ayende.com/Blog/archive/2009/05/28/nhibernate-ndash-executable-dml.aspx">executable bulk queries</a>. This is a feature that the java (Hibernate) version has had for some time and is now fully ported to NHibernate. </p> <p>For a complete list of new features: <a href="http://zvolkov.com/blog/post/2009/07/20/Whats-new-in-NHibernate-21.aspx">link</a></p> Unknownnoreply@blogger.comtag:blogger.com,1999:blog-3198935374994345981.post-39890509778100471812009-05-14T11:54:00.001+02:002009-05-14T11:54:56.076+02:00Presentation & Code Demo Tips<p><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgI6w7EVpksF6Qhfan_7ZsPKGudaWQilkhs_S5_LmwMxNiVdl-PLLvYfVWewgiYtB7MtZ4rOIvPlvi_YAqtzEhT1kEAFW_WQfPtfcZjDg6L72IgGYfn_Ekk0dEdBU3hwNyxmeMNJJtArZc/s1600-h/image%5B5%5D.png"><img title="image" style="border-right: 0px; padding-right: 5px; border-top: 0px; display: inline; padding-left: 5px; padding-bottom: 5px; margin-left: 0px; border-left: 0px; margin-right: 0px; padding-top: 5px; border-bottom: 0px" height="206" alt="image" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjqLcziZg0lo0Tvf8p1O092AzUxcE34AKyiJKfA0Cy6ROpGrBURcQfOorpyazI0H50Wp8GtdbNdGlHFQgfrqF2DICxB6lOT6on5cR2BdSOOwUolyuQjcuJi2UKY_5LzMfA67_TT-VuTXe8/?imgmax=800" width="300" align="right" border="0" /></a> I have been doing more and more talks lately. I am not a natural speaker I usually need to practice a few times before in order to talk more fluently. But practice has made me more comfortable with it and I feel that I am getting better at it. Two days ago I held a long (3.5 hour) talk on ASP.NET MVC which was both my longest talk and my most successful, at least considering the positive response a got, which was very encouraging. </p> <p>The talk was mostly a long code demo. One thing that can often kill code demos are that they can slow down the tempo of a presentation when there is too much typing of unimportant text/code. Like creating a new class, constructor, etc and then later getting to the really important part of a particular function. </p> <p>In this MVC code demo I tried to have as much prepared as possible. I started with a standard MVC template project, but had hidden (excluded from the project) controllers and views which I included as the code demo progressed. These controllers/views included some existing functionality which I then expanded upon. That way I did not need to type class definitions defining simple controller actions and views before getting to the interesting bits. </p> <p>I did the same with many other parts of the presentation, for example when explaining how to unit test controller actions I already had an almost empty test method already written, and only needed to show how to unit test the controller actions and how to assert on the result.</p> <p>I also had code snippets in the toolbox for some of the tricky parts of the code demo that I could use if something did not work or I felt that it took to long to write. Never let a problem in the code demo completely halt the presentation, have a backup plan or just move a long if you cannot fix the problem on the first 2 tries. </p> <p>I feel that I still have much to work on when it comes to presentation technique. I often talk a little to fast, need to focus on keeping calm and talking in a slow and articulate manner.  It doesn’t matter how nice your powerpoint or code demo is if the audience can’t hear what you are saying! </p> <p>Next up is trying keynote, nice to see how it compares to powerpoint. </p> Unknownnoreply@blogger.comtag:blogger.com,1999:blog-3198935374994345981.post-13279137989408429062009-05-13T19:20:00.001+02:002009-05-14T11:59:04.709+02:00The never ending stored procedure debate<p><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhpvmQ4cBfKitwj83s1hMchI9zzGp7CIAtH92O_Plp1HyWdelgn9P_0XDXoXtGrgdZdLYmqA2Xlyp5UdNe4OBVOnuyTQUOGIdI3cbUVSKPRgShdLCxhRmNL2sAheJ16uujfnkuXSLtYPeM/s1600-h/image%5B4%5D.png"><img title="image" style="border-top-width: 0px; padding-right: 5px; display: inline; padding-left: 5px; border-left-width: 0px; border-bottom-width: 0px; padding-bottom: 5px; margin-left: 0px; margin-right: 0px; padding-top: 5px; border-right-width: 0px" height="222" alt="image" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiEP3OYu7KPqmUKlsA68J_wUy4W83x5U72FHnSOM6oEC0DH_d2gUOox6MLK7fNrP5oyQc2IS3QfFlL6m7iOSm754AGTyXplHXK-yMdGCP4dhkdxdLOFic6jEELCmIo5Z92npoYnIR-DPww/?imgmax=800" width="240" align="right" border="0" /></a> I listened to the panel discussion on the <a href="http://www.msteched.com/online/view.aspx?tid=1fd917e2-e451-44c2-b515-c778325846fe">pros and cons of stored procedures</a> from the currently ongoing TechEd09 today. It was not what I hoped for, the panel consisted almost exclusively of pro stored procedure people with the exception of Jeffrey Palermo who for an NHibernate guy appeared very pro stored procedure. </p> <p>I was hoping for a more balanced debate. The arguments were to much focused on the real vs. perceived benefits of stored procedures in terms of performance, database coupling, vendor coupling, security etc. </p> <p>The really big issues I have personally with stored procedures (sprocs from now on) were never fully brought up. Especially when you compare sprocs and a manually coded DAL (which I find is the most common) with NHibernate.</p> <p><strong>Code duplication</strong> <br />In my experience systems which rely heavily on sprocs also show a large amount of code duplication, for example duplication of SQL queries in the same sprocs in the case of dynamic queries that filter on different columns based on input. I have seen sprocs that feature the same basic query duplicated 12 times with small variation in the where/order clause. Also duplication between different sprocs can usually be very high. And the final point is the sad fact that sprocs usually contain some business logic, logic that sometimes also exist in the application itself. </p> <p><strong>Productivity & Lines of code</strong> <br />This topic was also not really touched upon. Data access layers which use sprocs often feature massively more amount of code to deal with calling the sprocs and mapping them to entities. The amount of TSQL you need to write for the basic CRUD sprocs is also a huge time waster and possible maintenance nightmare. </p> <p>Some of these issues could be argued that it is just incompetent programmers/DBAs and sprocs are not to blame. Maybe it is not fair to compare sprocs with an ORM like NHibernate. But I think you can compare having to write and maintain sprocs compared to letting NHibernate generate adhoc SQL. Sure I think sprocs still have their usage in specific and relatively rare scenarios but the panel discussion too often concluded on the wishy washy "it depends". Of course it depends, context is everything (as Scott Bellware always says), but that does not mean that one method shouldn't be the preferred "best practice" choice. </p> <p>Sorry for the rant. Kind of frustrated with a current legacy system (which uses sprocs) :) </p> Unknownnoreply@blogger.com