tag:blogger.com,1999:blog-75774216121208253122024-03-13T17:57:42.266+00:00Functional FunSamuel Jack's light-hearted take on software developmentAnonymoushttp://www.blogger.com/profile/01345100698738870730noreply@blogger.comBlogger214125tag:blogger.com,1999:blog-7577421612120825312.post-16299107801312592672014-09-17T17:39:00.001+01:002014-09-17T17:43:37.347+01:00Text templating with … (gasp) … Excel!<p>Excel has many unlikely uses (did you know that <a href="http://eeggs.com/items/718.html" target="_blank">Excel 97 contained a hidden Flight Simulator</a>?). I’ve just reminded myself of another one: fast text templating.</p> <p>I needed to convert a data structure that looked like this</p> <p><a href="http://lh3.ggpht.com/-dJXQuuZvC-E/VBm5JrW_atI/AAAAAAAABUY/g3_9qt3X9xU/s1600-h/image5.png"><img title="image" style="display: inline" alt="image" src="http://lh3.ggpht.com/-bDxhk4gQNWc/VBm5KLpN8PI/AAAAAAAABUg/pvYdRAGEfa8/image_thumb3.png?imgmax=800" width="499" height="107" /></a></p> <p>into one that looked like this</p> <p><a href="http://lh3.ggpht.com/-xpg8AzJttOk/VBm5KjI3-7I/AAAAAAAABUk/v4amLocNR6A/s1600-h/image32.png"><img title="image" style="display: inline" alt="image" src="http://lh6.ggpht.com/-ypHWkBRFugg/VBm5LImo3TI/AAAAAAAABUw/GANaxGud9NM/image_thumb18.png?imgmax=800" width="348" height="222" /></a></p> <p>In other words, I needed to convert from a delimited text string into XML elements.</p> <p>It took me about 60 seconds in Excel. Here’s how:</p> <ol> <li>I copied the text containing all the keywords and pasted it into a single cell of an Excel spreadsheet </li> <li>I selected the cell, and clicked on the Text to Columns tool (you find this in the Data tab)<a href="http://lh5.ggpht.com/-DocVjMfc4_s/VBm5L_tUjYI/AAAAAAAABU4/GT4xwAtEnq0/s1600-h/image15.png"><img title="image" style="float: none; margin: 5px auto; display: block" alt="image" src="http://lh6.ggpht.com/-r3UU1krzl3c/VBm5MvsOABI/AAAAAAAABU8/uaSrGkkALhA/image_thumb9.png?imgmax=800" width="455" height="204" /></a> </li> <li>In the Text to Columns Wizard, I indicated that the data was Delimited, and then entered the appropriate delimiter – the pipe (‘|’) character in this case. When I clicked Finish, Excel split each keyword into its own cell, going across the sheet.<a href="http://lh5.ggpht.com/-lgZFcf_ERak/VBm5NKNDaSI/AAAAAAAABVI/l5ch_RGod0Q/s1600-h/image21.png"><img title="image" style="float: none; margin: 5px auto; display: block" alt="image" src="http://lh3.ggpht.com/--bOlzUOag_w/VBm5NxoaFpI/AAAAAAAABVM/pUFtX45rPAU/image_thumb13.png?imgmax=800" width="460" height="377" /></a> </li> <li>Next, I needed the keywords arranged vertically instead of horizontally – in rows instead of columns. So I selected all the columns by clicking the first cell, then pressing Ctrl+Shift+[Right Arrow] to select all the way to the last keyword. Ctrl-C copied all the keywords. After clicking in an empty cell, I selected the Paste Special option. In the Paste Special dialog, right at the bottom, you’ll find the Transpose option, which will convert columns of data into rows, and vice versa.<a href="http://lh4.ggpht.com/--79D31aB7SU/VBm5OJHWLAI/AAAAAAAABVU/vTAZ5CLdlHs/s1600-h/image22%25255B3%25255D.png"><img title="image" style="float: none; margin: 5px auto; display: block" alt="image" src="http://lh3.ggpht.com/-00ZUrkKuiCQ/VBm5OpsHmpI/AAAAAAAABVc/drZqNItrNzU/image22_thumb%25255B2%25255D.png?imgmax=800" width="423" height="358" /></a> </li> <li>In the cell next to the first keyword, I typed a formula that would wrap the keyword in the XML boilerplate. To concatenate strings use ‘&’, and to include quotes in a string use a double quote. So the formula I needed was <pre>="<Keyword Name=""" & A3 & """ />"</pre>
<a href="http://lh6.ggpht.com/-zHxo3KO94lM/VBm5PYYvGRI/AAAAAAAABVk/TJ6qGRT8Dx8/s1600-h/image25%25255B3%25255D.png"><img title="image" style="float: none; margin: 5px auto; display: block" alt="image" src="http://lh5.ggpht.com/-Q5Tw1tixDJA/VBm5P3tY6GI/AAAAAAAABVs/AwVIQ4AbJqE/image25_thumb%25255B2%25255D.png?imgmax=800" width="330" height="193" /></a> </li>
<li>I selected that first cell again, and double-clicked the solid square at the bottom right of the cell’s selection border. This replicated the formula all the way down the page to the last row with something in it.</li>
<li>Did the Ctrl-C/Ctrl-V dance to copy and paste the generated XML into my code file.</li>
<li>Job’s a good ‘un!</li>
</ol> Anonymoushttp://www.blogger.com/profile/01345100698738870730noreply@blogger.com1tag:blogger.com,1999:blog-7577421612120825312.post-53955983784282261202014-02-10T17:33:00.001+00:002014-02-10T17:39:37.527+00:00Getting Started with SignalR - and not a Chat room in sight!<blockquote> <p>You might have heard of <a href="http://www.asp.net/signalr">SignalR</a>, a real-time communications library for the web from Microsoft. It’s open source, it’s hip (it supports <a href="http://en.wikipedia.org/wiki/WebSocket">WebSockets</a>!) – and just about all the Getting Started tutorials are about Chat applications. How many times have you had to write a Chat application in your career? I’d bet a two-toed sloth could keep count for you on one foot and still have digits to spare.</p> <p>I want to show you how SignalR can solve elegantly a problem you will almost certainly have faced at some point: reporting progress of long-running operations on web pages. I say you’ve probably faced the problem – and if you’re anything like me, you’ve probably ducked out of solving it too, leaving your web site visitors in the tender care of a wait cursor while your web application does its thing in its own sweet time. Getting a server to report back to a web page has always been a fiddle, and many of the techniques in common use feel like hacks. SignalR changes all of that.</p> </blockquote> <p>Read my three-part guest series on the <a href="http://blog.safaribooksonline.com/" target="_blank">Safari Books Online blog</a>:</p> <ul> <li><a href="http://blog.safaribooksonline.com/2014/02/04/getting-started-signalr/" target="_blank">Getting Started with SignalR</a></li> <li><a href="http://blog.safaribooksonline.com/2014/02/06/server-side-signalr/" target="_blank">Reporting Server-Side Progress to Web Pages with SignalR</a></li> <li><a href="http://blog.safaribooksonline.com/2014/02/10/signalr-rx-framework/" target="_blank">Better Together - SignalR and the Rx Framework</a></li> </ul> Anonymoushttp://www.blogger.com/profile/01345100698738870730noreply@blogger.com1tag:blogger.com,1999:blog-7577421612120825312.post-24624882123029383022013-07-05T19:53:00.001+01:002013-07-09T19:33:28.668+01:00The Easy way to Record and Share Sermons - Introducing TruthVine Studio<p>One of my goals for <a href="http://www.truthvine.com">TruthVine</a>, my new sermon-sharing service, is to make recording and uploading sermons as easy as sending an email. All churches, great and small, should have the capability to share the Gospel online, not just those blessed enough to have an IT guru in the congregation.</p> <p>To that end, I’m pleased to announce TruthVine Studio, free to all subscribers of the TruthVine service.</p> <p><a href="http://lh6.ggpht.com/-lUewijgJOrQ/UdxXP73-rhI/AAAAAAAABL4/3UAHaPdGx8w/s1600-h/image%25255B6%25255D.png"><img title="TruthVine Studio" style="display: inline" alt="A screenshot of TruthVine Studio" src="http://lh4.ggpht.com/-KP9KGNJMcBk/UdxXQqBZ27I/AAAAAAAABMA/qUeHhSh-fkc/image_thumb%25255B4%25255D.png?imgmax=800" width="704" height="581" /></a></p> <p>Using this is simplicity itself:</p> <ol> <li>Press the big Record button when the preacher mounts the pulpit steps </li> <li>As he introduces his sermon, fill out the details in the relevant boxes </li> <li>Press the Stop button after the final “Amen” </li> <li>Hit Upload – and you’re done! The sermon will magically appear on your <a href="http://www.truthvine.com">TruthVine</a> powered website. </li> </ol> <p>Should there be a period of paper shuffling before the preacher begins, you can easily trim the sermon before you upload it. Simply click and drag over the part of the recording you don’t want, then press the Trim (scissors) button.</p> <p>Just think of the effort that saves you:</p> <ul> <li>You don’t have to spend hours learning how to use complicated recording software. </li> <li>You don’t have remember the sermon details to tag the files with later – type them straight into app. </li> <li>You don’t have to spend ages waiting for your tool of choice to encode multiple versions of the file – TruthVine Studio exports a High Quality Mp4, a smaller Mp4 file, and an WMA file (for burning to CD) – and it takes advantage of your multi-core laptop to do all three at once. </li> <li>You don’t have to go to a separate website, enter the sermon details all over again, then wait – again – whilst it uploads. </li> </ul> <p>TruthVine Studio handles all of that in just a couple of clicks. We’ve been using TruthVine Studio at our church for the last couple of weeks at our church, and sermons have typically been on our church website within a minute of the service finishing.</p> <p>If you fancy giving it a go, head over to the <a href="http://www.truthvine.com/">TruthVine</a> site and <a href="http://www.truthvine.com/signup.html">sign up</a> – it’s completely free during our preview period.</p> <h4>Shoutouts</h4> <p>I just wanted to say a few quick thank-yous to several folks for tools, resources and code that have been a huge help in building TruthVine Studio. In no particular order:</p> <ul> <li><a href="http://mark-dot-net.blogspot.co.uk/">Mark Heath</a> is the wizard behind the <a href="http://naudio.codeplex.com/">NAudio library</a> which shielded me from the gory details of the Windows Audio APIs </li> <li><a href="https://twitter.com/kozw">Koen Zwikstra</a> created the <a href="http://mui.codeplex.com/">Modern UI framework</a> that helps TruthVine Studio look so smart </li> <li><a href="https://twitter.com/keyamoon">Keyamoon</a> is the designer of the <a href="http://icomoon.io/">beautifully crisp, and oh-so-clickable icons</a> </li> <li><a href="https://twitter.com/mixedinkey">Yakov Voyborev</a> very generously allowed me to reuse some of the code that I wrote for him as part of <a href="http://www.mixedinkey.com/">Mixed In Key</a> projects. </li> <li>The <a href="http://blogs.msdn.com/b/bclteam/">BCL Team</a> wrote the new <a href="http://blogs.msdn.com/b/bclteam/archive/2012/12/18/preview-of-immutable-collections-released-on-nuget.aspx">Immutable Collections</a> library which was great fun to use as part of my audio editor code. </li> </ul> Anonymoushttp://www.blogger.com/profile/01345100698738870730noreply@blogger.com7tag:blogger.com,1999:blog-7577421612120825312.post-8747158184435688922013-05-30T12:00:00.001+01:002013-05-30T12:02:47.000+01:00How to debug silent crashes in .Net<p>Here’s a quick note to my future self, and any other interested parties in the present on how to diagnose a particularly tricky kind of unhandled exception. I’m talking about those ninja exceptions which manage to evade any kind of unhandled exception logging you’ve rigged up around your .Net applications.</p> <p>I was debugging just such a problem today. A customer would double click the application, and nothing would happen. Our application is configured to log any unhandled exceptions to a log file. But no log file was being created. There was, however, an entry written to the application event log: it told me that a <em>TypeInitializationException</em> had been thrown, and even gave me a stack trace. But it told me nothing about why the type had failed to initialize.</p> <p>To complicate matters, this was one of those <a href="http://en.wikipedia.org/wiki/Heisenbug">heisenbugs</a> where, though I could replicate it under normal circumstances, it would go away if I attached a debugger to the process. What I needed was a crash dump – a snapshot of the entire state of the application at the moment the exception happened. </p> <p><a href="http://www.microsoft.com/en-gb/download/details.aspx?id=26798">DebugDiag</a> was my first port of call. That’s a nifty tool from Microsoft which can be configured to create dumps from your application under particular circumstances,  including when it crashes. Handily, it will also analyse the dump file, and help you work out why the application crashed. Inexplicably, DebugDiag failed to capture any dumps for my application.</p> <p>So I turned to Windows Error Reporting. From Windows Vista SP1 onwards you can tweak some <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/bb513638(v=vs.85).aspx">flags in the registry</a>, and have windows automatically capture dumps for you – assuming you’re using .Net 4.0.</p> <h4></h4> <h4>Capturing dump files with Windows Error Reporting</h4> <p>All you need to do is set create a key at HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\Windows Error Reporting\LocalDumps\[Your Application Exe Name]. In that key, create a string value called <em>DumpFolder, </em>and set it to the folder where you want dumps to be written. Then create a DWORD value called <em>DumpType</em> with a value of 2.</p> <p><a href="http://lh4.ggpht.com/-dbz2rYf5iLo/UacxXf6nTBI/AAAAAAAABEo/rGuV0LR4Vfc/s1600-h/image%25255B4%25255D.png"><img title="image" style="float: none; margin-left: auto; display: block; margin-right: auto" alt="image" src="http://lh6.ggpht.com/-7TzzE4xw8RE/UacxYJpaZPI/AAAAAAAABEw/Ls4zuwUPMlU/image_thumb%25255B2%25255D.png?imgmax=800" width="626" height="326" /></a></p> <p>Now get those ninjas to crash your app.</p> <p>You should see a *.dmp file appearing in the folder you chose. Double click it – and you’ll see some Visual Studio magic, introduced in VS 2010. You can debug a dump file almost as if it were a live application. When you see the Minidump File Summary screen, you just need to click Debug with Mixed.</p> <p><a href="http://lh4.ggpht.com/-KaRpNkjhycs/UacxYvQmbkI/AAAAAAAABE4/1gzs1WxjYiU/s1600-h/image%25255B22%25255D.png"><img title="image" style="float: none; margin-left: auto; display: block; margin-right: auto" alt="image" src="http://lh6.ggpht.com/-73Sv0MBWUuk/UacxZfcFyXI/AAAAAAAABFA/cz4kqdq1OhE/image_thumb%25255B16%25255D.png?imgmax=800" width="647" height="510" /></a></p> <h4>Unmasking the ninja</h4> <p>So what was this ninja exception that was evading my logging routines? It was an exception being thrown by my exception handling code! </p> <p>The original exception was a <em>ConfigurationErrorsException</em>, thrown by the configuration API when loading my application’s user settings from a corrupt user.config file. My exception handling code looked like this:</p> <pre class="brush: csharp;">private void ReportUnhandledException(Exception exception)
{
try
{
Tracing.TraceUnhandledError(exception);
ReportExceptionToUser(exception);
}
catch (Exception fatalException)
{
Tracing.TraceUnhandledError(fatalException);
}
}</pre>
<p>The problem was caused by a static constructor in the Tracing class. We’re using the System.Diagnostics TraceSource api to log our exceptions, and the constructor was setting all of that up. The TraceSource API, it turns out, also tries to load the application configuration, so that was throwing an exception.</p>
<p>The solution? Use <em><a href="http://msdn.microsoft.com/en-us/library/ms131100.aspx">Environment.FailFast</a></em> instead of trying to log the secondary exception. That simply writes a message to the event log then bails out, with no chance of causing mayhem by raising further exceptions.</p>
<pre class="brush: csharp; highlight: [11];">private void ReportUnhandledException(Exception exception)
{
try
{
Tracing.TraceUnhandledError(exception);
ReportExceptionToUser(exception);
}
catch (Exception fatalException)
{
Environment.FailFast("An error occured whilst reporting an error.", exception);
}
}</pre> Anonymoushttp://www.blogger.com/profile/01345100698738870730noreply@blogger.com3tag:blogger.com,1999:blog-7577421612120825312.post-79763412676411301682013-03-20T11:35:00.001+00:002013-03-20T11:43:32.085+00:00A Logo for TruthVine<p>I’m delighted to announce that <a href="http://www.truthvine.com/">TruthVine</a> now has a logo:</p> <p><a href="http://www.truthvine.com/"><img title="TruthVine Logo" style="border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; float: none; padding-top: 0px; padding-left: 0px; margin-left: auto; display: block; padding-right: 0px; border-top-width: 0px; margin-right: auto" border="0" alt="TruthVine - Share Sermons Online" src="http://lh5.ggpht.com/-z79BllyoaWw/UUmfF6WEOTI/AAAAAAAABDg/g1SkJurlHVQ/Truthvine-Colour-Medium%252520-%252520No%252520R%25255B5%25255D.jpg?imgmax=800" width="503" height="352" /></a></p> <p>We also have an icon form that we can use in social media handles (our <a href="http://twitter.com/truthvine">twitter account</a>, for example), and for application icons:</p> <p><a href="http://lh4.ggpht.com/-zZVmrT_R4LY/UUmfGddRFtI/AAAAAAAABDo/mCF5LB9mN1Q/s1600-h/Truthvine%252520Icon%252520-%252520Medium%25255B4%25255D.jpg"><img title="Truthvine - Concepts 2 - Mini Icon" style="border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; float: none; padding-top: 0px; padding-left: 0px; margin-left: auto; display: block; padding-right: 0px; border-top-width: 0px; margin-right: auto" border="0" alt="Truthvine - Concepts 2 - Mini Icon" src="http://lh5.ggpht.com/-7ovkg4mBfZo/UUmfHC6rDXI/AAAAAAAABDw/BvMzOhfarHY/Truthvine%252520Icon%252520-%252520Medium_thumb%25255B1%25255D.jpg?imgmax=800" width="240" height="240" /></a></p> <p>Graphic design work was done by the talented <a href="http://www.chrishesketh.co.uk/">Chris Hesketh</a>, who is now beavering away to make our <a href="http://www.truthvine.com/">landing page</a> look presentable.</p> Anonymoushttp://www.blogger.com/profile/01345100698738870730noreply@blogger.com1tag:blogger.com,1999:blog-7577421612120825312.post-71102672581304119202013-03-09T22:23:00.001+00:002013-03-09T22:25:07.703+00:00A crash course on the importance of cross-browser testing<p>Having <a href="http://blog.functionalfun.net/2013/03/build-startup-in-weekmission.html">trumpeted</a> the successful launch of my startup’s <a href="http://blog.functionalfun.net/search/label/Startup%20Challenge">minimal-viable-product</a> on our first customers website yesterday, I went to bed feeling pretty satisfied with the week’s work.</p> <p>I woke up this morning to find a tweet and a comment on my blog alerting me to an issue with the site. Dave <a href="https://twitter.com/VerifyVeracity/status/310146176274026496">kindly tweeted</a> to say he was getting Http 404 errors when clicking links to view sermons. I checked the site again, and it “worked for me”<sup>TM </sup>so I concluded it was just a one off issue, and hoped it would go away. Then Mark <a href="http://blog.functionalfun.net/2013/03/build-startup-in-weekmission.html#comment-823954396">commented</a> that he was getting problems when viewing the site in Firefox. Ah!</p> <p>Rob and I developed the site using Google Chrome. I also tested it on Safari on my iPad. Both worked fine, so I optimistically assumed it worked everywhere.</p> <p>Prompted by Mark’s comment I downloaded Firefox, and tried the site for myself. Instead of this:</p> <p><a href="http://lh3.ggpht.com/-XrZOScpG6PA/UTu2U9E8eZI/AAAAAAAABC0/5WOLxjMRn1c/s1600-h/image%25255B8%25255D.png"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: block; float: none; border-top-width: 0px; border-bottom-width: 0px; margin-left: auto; border-left-width: 0px; margin-right: auto; padding-top: 0px" title="image" border="0" alt="image" src="http://lh3.ggpht.com/-Kofb5xjWLtU/UTu2VZ5mCnI/AAAAAAAABC8/cIKydY9XUAc/image_thumb%25255B7%25255D.png?imgmax=800" width="615" height="443" /></a></p> <p>I saw this:</p> <p><a href="http://lh5.ggpht.com/-s7k0U62SZyI/UTu2WN5FHOI/AAAAAAAABDE/ZJYYubuTtj8/s1600-h/image%25255B11%25255D.png"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: block; float: none; border-top-width: 0px; border-bottom-width: 0px; margin-left: auto; border-left-width: 0px; margin-right: auto; padding-top: 0px" title="image" border="0" alt="image" src="http://lh4.ggpht.com/-gsB_VT1U6nk/UTu2W5sFAsI/AAAAAAAABDM/uwvVGzAZ8gY/image_thumb%25255B10%25255D.png?imgmax=800" width="631" height="456" /></a></p> <p>I quickly diagnosed the problem: Firefox wasn't loading the css file that styles the content our script injects into the site. Our script was loading the style sheet dynamically by injecting a <link/> element into the page immediately before our content. This was working fine in Chrome and Safari – both <a href="http://www.webkit.org/">Webkit</a> based browsers. In Firefox, and IE, that technique didn’t work. It seems that IE requires style sheets to be added using the createStyleSheet method, and Firefox is picky, and requires the stylesheets be injected into the <head/> element. Fortunately, a google search turned up a StackOverflow post giving a <a href="http://stackoverflow.com/a/524798">cross-browser technique for injecting style sheets</a>.</p> <p>That was the first problem solved. The bigger problem was the links not working. In Firefox, clicking the links showed 404 errors in the page. In IE, they just didn’t work at all.</p> <p>The cause of this problem lay in the code that takes the html returned by our server and injects it into our customers page. That code has to rewrite all links to make them use hash bangs, so that we can intercept the clicks and post back to our server rather than the customers. In the process of rewriting we were using the <em>document.location.origin</em> property. Turns out, that’s only supported by Webkit browsers. Once again, StackOverflow <a href="http://stackoverflow.com/a/6167979">had the solution</a>.</p> <p>The problems should all hopefully now be fixed, and <a href="http://welcomehallchurch.org/sermons">welcomehallchurch.org/sermons</a> powered by <a href="http://www.truthvine.com/">TruthVine</a> should be working across all three major browsers.</p> <p>Next time I’ll remember to test on all three browsers first before launching!</p> Anonymoushttp://www.blogger.com/profile/01345100698738870730noreply@blogger.com0tag:blogger.com,1999:blog-7577421612120825312.post-45681001295967395202013-03-08T19:39:00.001+00:002013-03-08T19:39:34.493+00:00Build a Startup in a Week–Mission Accomplished!<p>This week <a href="http://codeofrob.com/">Rob Ashton</a> and I have been battling against the clock to get a minimum viable product for my startup <a href="http://www.truthvine.com/">TruthVine</a> out of the IDE and into the hands of customers in five days.</p> <p>At 3:42 PM this afternoon, we declared victory:</p> <blockquote class="twitter-tweet"> <p>Mission accomplished! @<a href="https://twitter.com/robashton">robashton</a> and I have built our TruthVine MVP in 1 week, and it's now live on <a title="http://www.welcomehallchurch.org/Sermons" href="http://t.co/VkyCpxNTA1">welcomehallchurch.org/Sermons</a></p> — Samuel Jack (@samuel_d_jack) <a href="https://twitter.com/samuel_d_jack/status/310052913198280704">March 8, 2013</a></blockquote> <script async src="//platform.twitter.com/widgets.js" charset="utf-8"></script> <p>There were some course adjustments along the way, as you would expect in a project like this. By the end of yesterday, I concluded that I wasn’t going to get my streamlined audio recording tool completed, so to make sure we had something to ship by the end of the week, I decided to put that on hold.</p> <p>Today we focused all our efforts on getting the TruthVine Admin website and the embedding experience ready for use. And I believe we succeeded. Rob wrote a migration tool to take all the existing sermon data from my own church website (which I manage) and put it into the new TruthVine database. Having deployed the final builds of the software to our EC2 server, I then replaced the sermon display code in the website with TruthVine’s magic script. Two minutes later it was live. You can visit <a href="http://welcomehallchurch.org/sermons">welcomehallchurch.org/sermons</a> to see for yourself. Of course, there’s still a lot left to be done, styling being the most obvious thing – but that’s the point of a minimal viable product. It’s now out there in the wild, and I can start gathering feedback to determine where to focus my efforts next.</p> <p>This week has been great fun, though hard work. I’d like to thank Rob again for all outstanding efforts. He has given me a great head start. But now the real work begins: marketing TruthVine, and building it into a self-sustaining business.</p> <p>Oh – and by the way - if you know a church who might be interested in trying this out, send them <a href="http://blog.functionalfun.net/p/contact-me.html">to me</a>, and I’ll hook them up with a free trial.</p> Anonymoushttp://www.blogger.com/profile/01345100698738870730noreply@blogger.com6tag:blogger.com,1999:blog-7577421612120825312.post-77427105954300892082013-03-08T10:39:00.001+00:002013-03-08T10:47:48.980+00:00Why I chose RavenDb for my startup<p>In my post the other day about my <a href="http://blog.functionalfun.net/2013/03/bootstrap-startup-in-week-day-1.html">choices of technological underpinnings</a> for my startup, <a href="http://blog.functionalfun.net/2013/03/introducing-truthvine.html">TruthVine</a>, there was one choice I omitted to mention. I didn’t say which database I had decided upon. </p> <p>In fact it was a decision which took no consideration at all: having worked with <a href="http://ravendb.net/">RavenDb</a> on the inside and from the outside, it was my immediate choice. Here’s why.</p> <h4>RavenDb stays out of the way</h4> <p>RavenDb is like a waiter at the best kind of restaurant. It serves your data with the minimum of fuss and gets out of the way. Unlike certain persistence technologies I could mention, there is barely any configuration involved, and not a mapping in sight. You just hand RavenDb an object or any shape or size, and RavenDb stores it. You murmur an object’s id, and RavenDb has it on your plate in an instant, child collections and all.</p> <p>RavenDb is a document database. That means that you don’t need to declare a schema upfront. Whenever you hand RavenDb an object it simply serializes it to JSON format, and stores it as a blob in its persistence engine. The benefit I see from this is greatly reduced pain when deploying updates to my code, as I won’t need to worry about sql migration scripts. I can add things to my objects with impunity, and for other situations, RavenDb has very nice <a href="http://ravendb.net/docs/2.0/studio/patch">document patching support</a>.</p> <p>As as you’d expect, given <a href="http://ayende.com/blog">RavenDb’s provenance</a>, the RavenDb .Net client is awesome. It has full support for the <a href="http://ravendb.net/docs/client-api/basic-operations/understanding-session-object">unit-of-work pattern and transactions</a>. Thus any entities you load within a session are tracked, and any that have changed when you save the session are sent to the database in a single transaction. Naturally, the RavenDb client has LINQ support too, with paging in queries being especially trivial to implement.</p> <p>Here’s a complete snippet showing everything you need to store and retrieve objects from RavenDb.</p> <pre class="brush:csharp">class RavenDbDemo
{
public void Demonstrate()
{
// DocumentStore is a heavy-weight object usually created once per application
var documentStore = new DocumentStore() {Url = "http://myravendbserver.com"};
documentStore.Initialize();
// session objects are light-weight and are created per transaction
using (var session = documentStore.OpenSession())
{
var person = new Person()
{
Name = "Samuel Jack",
FavouriteDatabase = "Sql Server"
};
session.Store(person);
session.SaveChanges();
}
using (var session = documentStore.OpenSession())
{
var person = session.Query<Person>()
.First(p => p.Name == "Samuel Jack");
person.FavouriteDatabase = "RavenDb";
session.SaveChanges();
}
}
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public string FavouriteDatabase { get; set; }
}
}</pre>
<h4>Indexing is largely automatic</h4>
<p>One thing this snippet highlights is RavenDb’s awesome indexing support. Whenever you make a new kind of query, RavenDb will automatically create an index for you to query against. In the most recent versions of RavenDb, it will automatically tune the indexes over time, depending on the patterns of queries you make against the database. Of course, you can define more sophisticated indexes explicitly, but often you never need to.</p>
<p>One situation where you will need to create indexes is when you want to take advantage of <a href="http://ayende.com/blog/4435/map-reduce-a-visual-explanation">RavenDb’s Map/Reduce support</a>. This is how RavenDb supports queries which involve aggregating multiple documents, since it doesn’t implement grouping clauses in LINQ queries from the client. The nice thing about the way it does this is that Map/Reduce indexes are persisted just like other indexes, which makes aggregate queries very fast.</p>
<h4>And There’s More</h4>
<p>There is so much more to like about RavenDb, but I’ll just highlight a few other things which I think will be important to me as a startup.</p>
<p>The first is RavenDb’s replication support. This is important if you want to make sure your application has high availability. Configuring replication is as easy as entering the connection string for the database you want RavenDb to replicate too. Replication also helps enormously with scalability, as you can configure your clients to read from any of the replicas, thus spreading the load, but write to the master database, thus ensuring consistency without generating conflicts.</p>
<p>Next is backup support. RavenDb comes with built in support for doing backups to Amazon S3, or Amazon Glacier. You just have to tell it the bucket you want to write to, and your API keys, and off it goes.</p>
<p>The level of support available is always an important consideration when choosing to adopt a product, and RavenDb has great support, both from the RavenDb community who hang out on the <a href="https://groups.google.com/forum/?fromgroups#!forum/ravendb">RavenDb group</a>, and from Ayende and the rest of the Hibernating Rhinos team. RavenDb is an open source project (using the AGPL license, so you must buy a license if you’re not willing to open-source your own code) and the community are very active in contributing to the project. </p>
<p>I should mention that, if RavenDb has one failing, the documentation is not as good as it might be. The situation has improved a lot recently, and I understand a couple of books are in progress. Most of the time RavenDb just works, but if you stray too far from the beaten path, you might find yourself relying on the community to help you understand what’s going on. Having the code available certainly helps, and, as I said, the community are very responsive.</p>
<p>Finally, I can’t resist a plug for the Management UI (in which, if you press me, I might admit to <a href="http://blog.functionalfun.net/2012/08/data-virtualization-in-silverlight.html">having played a part</a>!). </p>
<a href="http://lh3.ggpht.com/-Xv9d16qfTp8/UTm_8rHbMkI/AAAAAAAABCc/-n8xFYQ6nH8/s1600-h/image%25255B7%25255D.png"><img title="image" style="float: none; margin-left: auto; display: block; margin-right: auto" alt="image" src="http://lh3.ggpht.com/-LRDZv8Y6ifU/UTm_9R6om4I/AAAAAAAABCk/fN9NnpFXDtU/image_thumb%25255B5%25255D.png?imgmax=800" width="801" height="524" /></a>
<p>I love the fact that you scan scroll through your entire documents collection, or through all the results of a query, with the client paging in the data as necessary.</p>
<p><em>Full disclosure: Whilst these opinions are entirely my own, and I do not believe them to be prejudiced by any other factors, I have been offered a RavenDb license by Hibernating Rhinos in exchange for setting them out in this blog post. I am also a freelance contributor to the RavenDb project.</em></p> Anonymoushttp://www.blogger.com/profile/01345100698738870730noreply@blogger.com0tag:blogger.com,1999:blog-7577421612120825312.post-40390505150457535842013-03-07T07:33:00.001+00:002013-03-07T10:24:27.920+00:00Bootstrap a Startup in a Week–Days 2 and 3: A Walking Skeleton<p><a href="http://codeofrob.com/"><em>Rob Ashton</em></a><em> and I are engaged in a </em><a href="http://blog.functionalfun.net/2013/02/my-one-week-start-up-challenge.html"><em>challenge</em></a><em> to build a minimal viable product for my start-up </em><a href="http://www.truthvine.com/"><em>TruthVine</em></a><em> in a week. We kicked off on </em><a href="http://blog.functionalfun.net/2013/03/bootstrap-startup-in-week-day-1.html"><em>Monday</em></a><em>. This is how Tuesday and Wednesday panned out.</em></p> <p>I’m surfacing briefly from the code-face this morning to announce that our efforts have met in the middle. My desktop sermon-recording client is now encoding and uploading sermons to Rob’s web application.</p> <p>Having spent Monday working on the Administrator user interface, where churches will upload and manage sermons, Rob turned his attention on Tuesday and Wednesday to the public facing website which will supply the smarts to allow churches to easily embed a rich sermon browsing experience in their existing websites.</p> <h4>Single Page Application without client side templating</h4> <p>The brief I set Rob had three parts:</p> <ol> <li>A church must be able to add the sermon display to their website just by pasting a snippet of html/javascript code onto a page of their website </li> <li>Individual areas of the sermon browsing experience should have unique urls to make them easy to share </li> <li>If possible, the whole thing should be SEO friendly </li> </ol> <p>We can now tick off points 1 and 2, and we’re running some experiments with Google to see if we have accomplished 3.</p> <p>Rob has come up with an elegant solution whereby our small snippet of code loads a small <em>truthvine.js</em> file which brings the whole experience to the page. The javascript inspects the url of the page where it is embedded, and reads the part after the hash bang (ie ‘#!’). It interprets that as a url and requests it from the TruthVine server, which returns a JSONP result containing some html. For example, in the url <a href="#"><em>http://mychurch.com/sermons/#!/sermons/view/33</em></a><em>, </em>the part after the hash bang is <a href="http://mychurch.com/sermons/#!/sermons/view/33">/sermons/view/33</a> , and that url is requested from the server. The javascript on the page appends the html fragment from the JSONP request to a <div/> which is part of the snippet. </p> <p>The best part of this is that there’s no client side templating involved. We can render everything using <a href="http://en.wikipedia.org/wiki/Microsoft_ASP.NET_Razor_view_engine">Razor</a> views on the server side, including all the links between different parts of the experience. </p> <h4>Immutable collections and audio editing</h4> <p>Meanwhile, on my side of the tunnel, work on the desktop recording client has been going forward steadily. It can now play back the audio that it has recorded, and encode it to AAC format. More importantly, it can post sermons to the website.</p> <p>I spent a large part of yesterday laying the groundwork for being able to trim a recording. This has been very interesting work, not least because I’ve been able to try out the new <a href="http://blogs.msdn.com/b/bclteam/archive/2012/12/18/preview-of-immutable-collections-released-on-nuget.aspx">Immutable collections</a> that the BCL team have created.</p> <p>The approach I’m taking is to write all the raw audio samples to a memory-mapped file which I’m treating as append-only. I then keep a list of segments – pointers to the start and end of sections in the original recording which will be included in the output. The idea is that it is this list of segments which will change during the editing process rather than manipulating the raw audio. By using immutable data structures it becomes much easier to do work on different threads. It should also make it almost trivial to implement undo-redo, because undoing an operation just requires us to reinstate the previous version of the segments list. Remind me to share the code with you sometime!</p> <h4>Deployment</h4> <p>Yesterday evening we deployed our code to the web for the first time – “the moment of truth<em>vine</em>”, as Rob called it. I was impressed by how painless deployments are using <a href="http://www.iis.net/downloads/microsoft/web-deploy">Microsoft’s Web Deploy</a>. Having installed Web Deploy on the server, you can simply create a new website in IIS, then choose the “Deploy –> Configure Web Deploy Publishing…” from the context menu. This creates a publishing profile that you then import into Visual Studio. Then every time you have fresh bits for the server you just select “Build –> Publish Selection” in Visual Studio and – hey presto! – there it is for all the world to see.</p> <p>There was one point in the deployment where I thought I was going mad. Having successfully deployed the admin website, I tried deploying the public facing website, only to discover IIS wouldn’t serve <em>.js</em> files from the root of the application – it was returning Http 404 errors instead. I checked folder permissions, checked that the Static Content module was installed – nothing doing. I was saved by the old trick: I deleted the site and started again, and everything was fine!</p> <p>With our skeleton now on his feet, we have two days left on the clock to put some flesh on his bones and make sure he doesn’t wobble over. Stay tuned!</p> Anonymoushttp://www.blogger.com/profile/01345100698738870730noreply@blogger.com1tag:blogger.com,1999:blog-7577421612120825312.post-85071753383417853412013-03-04T21:06:00.001+00:002013-03-04T21:06:35.847+00:00Bootstrap a Startup in a Week: Day 1<p><a href="https://twitter.com/robashton">Hurricane Rob</a> (aka <a href="http://codeofrob.com/">Rob Ashton</a>) is the mildest-mannered whirlwind one could ever hope to meet, and he passed through my office today leaving in his wake a wonderful trail of <em>con</em>struction. It was Day 1 of my <a href="http://blog.functionalfun.net/search/label/Startup%20Challenge">“Build a Startup in a Week” challenge</a>, and Rob arrived at my house (we’re working from my garden office) bright and early, eager to re-caffinate. Whilst he patched up his scarcely-used Windows laptop with Asp.Net MVC 4 (am I the only Windows developer still actually using a PC and not a Macbook Air?) we talked tactics. </p> <p>There are three major components for my <a href="http://www.truthvine.com">sermon sharing service</a> that I want to get built this week. One is the administration website, where churches will upload and manage sermons. Second is the public-facing website which will embed sermon listings in churches websites. And third is “The Studio” – a super-easy-to-use desktop application for recording, editing and uploading sermons.</p> <p>Since Rob’s strength lies in web development and my expertise is centred on desktop applications, a natural division of labour emerged. So whilst Rob got started on the web stuff, I cracked open Visual Studio and created a fresh WPF project.</p> <p>Some of the ground work for our weeks work, I laid last week.</p> <h4>Ground Work</h4> <p>After much toing and froing I’ve settled on Amazon to host the services, and in particular, <a href="http://aws.amazon.com/ec2/">Amazon EC2</a> for the servers. I considered <a href="https://appharbor.com/">AppHarbour</a>, and <a href="http://www.windowsazure.com/en-us/home/scenarios/web-sites/">Azure Websites</a>, with their promises of painless deployments, but in the end I decided I’d trade off a little extra work on deployment in return for complete control of the stack. </p> <p>Wherever you turn, Amazon seem to have you covered. The <a href="http://www.truthvine.com/">TruthVine landing page</a> is currently hosted as a static website on <a href="http://aws.amazon.com/s3/">Amazon S3</a>, and we’ll be using S3 for sermon storage too. The truthvine.com domain is pointed at <a href="http://aws.amazon.com/route53/">Amazon’s Route 53 DNS service</a>. We’ll be using <a href="http://aws.amazon.com/ses/">SES</a> for sending notification emails. If only <a href="http://aws.amazon.com/fps/">Amazon Flexible Payments service</a> worked in the UK, I’d be use that in a shot.</p> <p>For hosting our source code and managing issues, I’ve settled on <a href="https://bitbucket.org/">BitBucket</a>, with a Git repo. Whilst I prefer Mercurial from an ease-of-use perspective, and would have loved to use <a href="http://www.fogcreek.com/kiln/">Fogcreek’s Kiln</a>, it seems Git has become the <em>lingua</em> <em>franca</em> for DVCS, particularly after <a href="http://www.hanselman.com/blog/GitSupportForVisualStudioGitTFSAndVSPutIntoContext.aspx">Microsoft announced they were adopting it for TFS</a>. Why BitBucket rather than GitHub? Because I think their pricing model makes more sense. GitHub charges per repository, whereas BitBucket charge per user. I can see our repository count growing over time, whereas the number of developers I’m likely to involve in my projects is going to remain small.</p> <p>The last thing to get sorted before Rob’s arrival was a UI theme for Admin pages. We’re going to be using <a href="http://twitter.github.com/bootstrap/">Twitter Bootstrap</a> to make the UI a little easier to develop. I found a wonderful site called <a href="https://wrapbootstrap.com/">WrapBootstrap</a> which sells themes built on Twitter Bootstrap, all for very reasonable prices. From that, I’ve picked the <a href="http://wrapbootstrap.com/preview/WB0016FX5">Optimus Dashboard theme</a>, which not only looks the part, but is responsive, so it resizes to accommodate tablets and smartphones.</p> <h4></h4> <h4>Progress Report</h4> <p>So how did we get on today?</p> <p>Rob made a sterling effort. Starting with some code I’d written for <a href="http://welcomehallchurch.org/sermons">our church website</a> (which he <a href="https://twitter.com/RobAshton/status/308526703674814464">seemed to like</a>) he got a good chunk of the admin website done today – login, sermon management, and series management.</p> <p>My efforts were a bit more lacklustre. They amounted to this:</p> <p><a href="http://lh6.ggpht.com/-mD1rB7jP31Y/UTUM1h7CX5I/AAAAAAAABCE/v-uuUGjjkWo/s1600-h/image%25255B4%25255D.png"><img title="TruthVine Studio" style="border-top: 0px; border-right: 0px; background-image: none; border-bottom: 0px; float: none; padding-top: 0px; padding-left: 0px; margin-left: auto; border-left: 0px; display: block; padding-right: 0px; margin-right: auto" border="0" alt="TruthVine Studio" src="http://lh3.ggpht.com/-PY9Jh3n_3l8/UTUM2dFsp_I/AAAAAAAABCM/R0o6A-bPy74/image_thumb%25255B2%25255D.png?imgmax=800" width="549" height="276" /></a></p> <p>I did make a few useful discoveries though. A while back, I found the <a href="http://naudio.codeplex.com/">NAudio library</a>, which does a lot of the grunt work when working with Audio in .Net. Today I discovered that they’ve added code to handle AAC encoding using the <a href="http://msdn.microsoft.com/en-gb/library/windows/desktop/dd742785(v=vs.85).aspx">encoder built into Windows</a> as of Windows 7. I was thinking I’d need to spend a day or translating C++ samples into C# interop to get that working.</p> <p>All in all, a profitable day. Hopefully a sign of a good week to come.</p> Anonymoushttp://www.blogger.com/profile/01345100698738870730noreply@blogger.com5tag:blogger.com,1999:blog-7577421612120825312.post-76873212229470769672013-03-02T21:07:00.001+00:002013-03-02T21:07:48.944+00:00Introducing TruthVine<p>This Monday morning, the metaphorical starting gun will fire, and <a href="http://codeofrob.com/">Rob</a> and I will be off on our <a href="http://blog.functionalfun.net/2013/02/my-one-week-start-up-challenge.html">one-week startup challenge</a>. We aim to have a minimum viable product up and hosting at least one customer in 5 days. So what is it we’re building?</p> <p>Allow me to introduce <a href="http://www.truthvine.com">TruthVine</a> – “the easiest way to share sermons online”. The theory I’m testing with the launch of this product is that there are many churches who would love to put their sermons online, but simply don’t know where to start. There are already sites like <a href="http://www.sermonaudio.com">SermonAudio.com</a> or <a href="http://www.sermoncloud.com/">SermonCloud.com</a>, but my research suggests that there is room in the market for a service which makes the whole process so simple that no IT know-how is required.</p> <p>With TruthVine I aim to streamline the whole process of recording, publishing, and <em>engaging with</em> sermons. Engagement is a major part of my vision for the future. As a wise man once said, “a sermon is not over until it is lived”, and God-willing, I want to build TruthVine into a tool which helps Christians keep the preached Word of God at the front of their minds so they can live it.</p> <p>That’s the lofty goal. But every journey begins with a first step, and on Monday we take ours. </p> <p>Check out the <a href="http://www.truthvine.com">landing page</a>, sign up for the newsletter, and follow along with our hackathon next week. </p> Anonymoushttp://www.blogger.com/profile/01345100698738870730noreply@blogger.com2tag:blogger.com,1999:blog-7577421612120825312.post-91112163380269249372013-02-23T20:40:00.001+00:002013-02-23T20:41:02.773+00:00My one week Start-up challenge<p>Regular readers of this blog know that I relish a challenge. Two years back the task was to conjure up <a href="http://blog.functionalfun.net/p/simon-squared.html">a mobile app in 3 days</a>. This time, I’m aiming to launch a start-up in 1 week.</p> <p>At the beginning of December <a href="http://codeofrob.com">Rob Ashton</a> posted a startling entry to his blog. “<a href="http://codeofrob.com/entries/i-am-not-looking-for-a-job.html">I’m not looking for a job</a>” was the title, and 1-2 weeks of his expertise in exchange for just expenses and a roof over his head was his offer. It was exactly the catalyst I needed.</p> <p>I suspect many software developers suffer from the affliction I’ve experienced ever since going freelance: the urge to launch some new product. We developers love making things, and seeing people get value out of them. And we freelancers would love to be free of the tyranny of the clock – earning exactly in accordance with the time we can bill for. </p> <p>About the middle of last year I settled on the niche I wanted to target, and the product I wanted to build. Ever since then I’ve been waiting for everything to fall into place so that I could get started. Of course, things never happen like that. There’s always just one more paying project that crops up first, one more thing to get out of the way before you get going.</p> <p>So when Rob’s offer came along, I seized it. I knew that if I committed myself, things would start moving. I emailed Rob the day after he posted his offer, and arranged to host him for a week. With a deadline settled, and other parties involved, things <em>have</em> started to fall into place. My product now has a name, it has a graphic designer working on a logo, and it has a landing page which illustrates why I should not be left in charge of graphic design (or copywriting too, come to that).</p> <p>And by the end of the first week of March, with Rob’s help, I aim to have a minimum-viable-product coded and in the hands of beta testers. </p> <p>Follow along here, and on <a href="http://codeofrob.com">Rob’s blog</a>, and we’ll let you know how it goes.</p> <p>Next up: what is we’re building?</p> Anonymoushttp://www.blogger.com/profile/01345100698738870730noreply@blogger.com0tag:blogger.com,1999:blog-7577421612120825312.post-86539577513287115002012-09-28T12:26:00.001+01:002012-09-28T14:10:31.229+01:00A quick guide to Registration-Free COM in .Net–and how to Unit Test it<p>A couple of times recently I’ve needed to set up a .Net application to use Registration-Free COM, and each time I’ve had to hunt around to recall the details. Further, just this week I needed to write some unit tests that involve instantiating these un-registered COM objects, and that wasn’t straight forward. So, as much for the benefit of my future self as for you, my loyal reader, I’m going to summarise my know-how in quick blog post before it becomes used-to-know-how.</p> <h4>What is Registration-Free COM? </h4> <p>If you’re still reading, I’ll assume you know all about COM, Microsoft’s ancient technology for enabling components written in different languages to talk to each other (I wrote a little about it <a href="http://blog.functionalfun.net/2010/05/primer-on-exposing-net-to-com.html">here</a>, with some links to introductory articles). You are probably also aware of DLL Hell. That isn’t a place where bad executables are sent when they are terminated. Rather, it was a pain inflicted on developers by the necessity of registering COM components (and other DLLs) in a central place in the OS. Since all components were dumped into the same pool, one application could cause all kinds of hell for others by registering different versions of shared DLLs. The OS doesn’t police this pool, and it certainly doesn’t enforce compatibility, so much unexpected weird and wonderful behaviour was the result.</p> <p>Starting with Windows XP, it has been possible to more-or-less escape this hell by not registering components in a central location, and instead using Registration-Free COM. This makes it much easier to deploy applications, because you can just copy a bunch of files – RegSvr32 is not involved, and there are no Registry keys to be written. You can be confident that your application will have no impact on others once installed.</p> <p>It is all done using manifests.</p> <h4>Individual Manifest Files</h4> <p>For each dll, or ocx file (or ax files in my case – I’m working with DirectShow filters) containing COM components you need to create a manifest. </p> <p>Suppose your dll is called MyCOMComponent.dll. Your manifest file should be called MyCOMComponent.sxs.manifest, and it should contain the following:</p> <pre class="brush: xml;gutter: false;"><?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
<assemblyIdentity
type="win32"
name="MyCOMComponent.sxs"
version="1.0.0.0" />
<file name="MyCOMComponent.dll">
<comClass
description="MyCOMComponent"
clsid="{AB12C3D4-567D-4156-802B-40A1387ADE61}"
threadingModel="Both" />
</file>
</assembly></pre>
<p>Obviously you need to make sure that the clsid inside comClass is correct for your component. If you have more than one COM object in your dll you can add multiple comClass elements. For those not wanting to generate these manifests by hand, a StackOverflow answer <a href="http://stackoverflow.com/a/476986/1727">lists some tools</a> that might help.</p>
<h4>About Deployment</h4>
<p>When you deploy your application you should deploy both the dll/ocx/ax file and its manifest into the same directory as your .Net exe/dlls. When developing in Visual Studio, I customise the build process to make sure all these dlls get copied into the correct place for running and debugging the application. I stole the technique for doing this from the way ASP.Net MVC applications manage their dlls. </p>
<p>Put all the dlls and manifests into a folder called _bin_deployableAssemblies alongside the rest of your source code. Then modify your csproj file and add the following Target at the end of it:</p>
<pre class="brush: xml;gutter: false;"><!--
============================================================
CopyBinDeployableAssemblies
This target copies the contents of ProjectDir\_bin_deployableAssemblies to the bin
folder, preserving the relative paths
============================================================
-->
<Target Name="CopyBinDeployableAssemblies" Condition="Exists('$(MSBuildProjectDirectory)\_bin_deployableAssemblies')">
<CreateItem Include="$(MSBuildProjectDirectory)\_bin_deployableAssemblies\**\*.*" Condition="Exists('$(MSBuildProjectDirectory)\_bin_deployableAssemblies')">
<Output ItemName="_binDeployableAssemblies" TaskParameter="Include" />
</CreateItem>
<Copy SourceFiles="@(_binDeployableAssemblies)" DestinationFolder="$(OutDir)\%(RecursiveDir)" SkipUnchangedFiles="true" Retries="$(CopyRetryCount)" RetryDelayMilliseconds="$(CopyRetryDelayMilliseconds)" />
</Target></pre>
<p>To make sure that target is called when you build, update the AfterBuild target (uncomment it first if you’re not currently using it): </p>
<pre class="brush: xml;"> <Target Name="AfterBuild" DependsOnTargets="MyOtherTarget;CopyBinDeployableAssemblies" /></pre>
<h4>The Application Manifest</h4>
<p>Now you need to make sure your application declares its dependencies.</p>
<p>First add an app.manifest file to your project, if you haven’t already got one. To do this in Visual Studio, right click the project, select <em>Add –> New Item … </em>and then choose <em>Application Manifest File</em>. Having added the manifest, you need to ensure it is compiled into your executable. You do this by right-clicking the project, choosing <em>Properties</em>, then going to the Application tab. In the resources section you’ll see a <em>Manifest</em> textbox: make sure your <em>app.manifest</em> file is selected.</p>
<p><a href="http://lh5.ggpht.com/-GreOnFori20/UGWJL1XEJ6I/AAAAAAAABAY/CdzqO_kbleM/s1600-h/image%25255B4%25255D.png"><img style="display: block; float: none; margin-left: auto; margin-right: auto" title="image" alt="image" src="http://lh4.ggpht.com/-Sk14E1Z6GOQ/UGWJNNZOftI/AAAAAAAABAg/YBlgX6KUMWI/image_thumb%25255B2%25255D.png?imgmax=800" width="613" height="412" /></a></p>
<p>Now you need to add a section to the app.manifest file for each dependency.</p>
<p>By default your app.manifest file will probably already have a dependency for the Windows Common Controls. After that (so, nested directly inside the root element) you should add the following for each of the manifest files you created earlier:</p>
<pre class="brush: xml;"><dependency>
<dependentAssembly>
<assemblyIdentity
type="win32"
name="MyCOMComponent.sxs"
version="1.0.0.0" />
</dependentAssembly>
</dependency></pre>
<p>Notice that we drop the “.manifest” off the end of the manifest file name when we refer to it here. The other important thing is that the version number here and the one in the manifest file should exactly match, though I don’t think there’s any reason to change it from <em>1.0.0.0</em>.</p>
<h5></h5>
<h4>Disabling the Visual Studio Hosting Process</h4>
<p>There’s just one more thing to do before you try running your application, and that is to turn off the Visual Studio hosting process. The <a href="http://msdn.microsoft.com/en-us/library/ms185331.aspx">hosting process</a> apparently helps improve debugging performance, amongst other things (though I’ve not noticed greatly decreased performance with it disabled). The problem is that, when enabled, application executables are not loaded directly- rather, they are loaded by an intermediary executable with a name ending .vshost.exe. The upshot is that the manifest embedded in your exe is ignored, and COM components are not loaded.</p>
<p>Disabling the hosting process is simple:  go to the <em>Debug</em> tab of your project’s Properties and uncheck “<em>Enable the Visual Studio hosting process</em>”</p>
<p><a href="http://lh3.ggpht.com/-dWz-JFWhzC8/UGWJOP-JyZI/AAAAAAAABAo/XKjAMisFXqU/s1600-h/image%25255B9%25255D.png"><img style="display: block; float: none; margin-left: auto; margin-right: auto" title="image" alt="image" src="http://lh4.ggpht.com/-iIwRPtQcx50/UGWJPokcF_I/AAAAAAAABAw/85u-J8uGsUg/image_thumb%25255B5%25255D.png?imgmax=800" width="648" height="458" /></a></p>
<p>With everything set up, you’ll want to try running your application. If you got everything right first time, everything will go smoothly. If not you might see an error like this:</p>
<p><a href="http://lh4.ggpht.com/-5uA35zrwDFk/UGWJQ3b72hI/AAAAAAAABA4/-hHEmBxuG8A/s1600-h/image%25255B17%25255D.png"><img style="display: block; float: none; margin-left: auto; margin-right: auto" title="image" alt="image" src="http://lh6.ggpht.com/-bopexg3HEWs/UGWJRzyRkDI/AAAAAAAABBA/FzUGDPHa3Zo/image_thumb%25255B9%25255D.png?imgmax=800" width="563" height="207" /></a></p>
<p>If you do, check Windows’ Application event log for errors coming from SideBySide. These are usually pretty helpful in telling you which part of your configuration has a problem.</p>
<h5></h5>
<h5></h5>
<h4>Summary</h4>
<p>To re-cap briefly, here are the steps to enabling Registration-Free COM for you application:</p>
<ol>
<li>Create a manifest file for each COM dll </li>
<li>Make sure both COM dlls and manifest files are deployed alongside your main executable </li>
<li>Add a manifest file to your executable which references each individual manifest file </li>
<li>Make sure you turn off the Visual Studio hosting process before debugging </li>
</ol>
<h5></h5>
<h4>Unit Testing and Registration-Free COM</h4>
<p>And now, as promised, a word about running Unit Tests when Registration-Free COM is involved. </p>
<p>If you have a Unit Test which tries to create a Registration-Free COM object you’ll probably get an exception like</p>
<blockquote>
<p>Retrieving the COM class factory for component with CLSID {1C123B56-3774-4EE4-A482-512B3AB7CABB} failed due to the following error: 80040154 Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG)).</p>
</blockquote>
<p>If you don’t get this error, it’s probably because the component is still registered centrally on your machine. Running <em>regsvr32 /u [Path_to_your_dll]</em> will unregister it.</p>
<p>Why do Unit Tests fail, when the application works? It is for the same reason that the Visual Studio hosting process breaks Registration-Free COM: your unit tests are actually being run in a different process (for example, the Resharper.TaskRunner), and the manifest file which you so carefully crafted for your exe is being ignored. Only the manifest on the entry executable is taken into account, and since that’s a generic unit test runner it says nothing about your COM dependencies.</p>
<p>But there’s a workaround. Win32 has some APIs –the Activation Context APIs- which allow you to manually load up a manifest for each thread which needs to create COM components. <a href="http://www.atalasoft.com/blogs/spikemclarty">Spike McLarty</a> has <a href="http://www.atalasoft.com/blogs/spikemclarty/february-2012/dynamically-testing-an-activex-control-from-c-and">written some code</a> to make these easy to use from .Net, and I’ll show you a technique to incorporate this into your code so that it works correctly whether called from unit tests or not.</p>
<p>Here’s Spike’s code, with a few minor modifications of my own:</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:cc9bd910-4e43-4e31-bbfd-949ed273caf5" class="wlWriterEditableSmartContent"><pre class="brush: csharp; gutter: false; first-line: 1; tab-size: 4; toolbar: true; ">/// <remarks>
/// Code from http://www.atalasoft.com/blogs/spikemclarty/february-2012/dynamically-testing-an-activex-control-from-c-and
/// </remarks>
class ActivationContext
{
static public void UsingManifestDo(string manifest, Action action)
{
UnsafeNativeMethods.ACTCTX context = new UnsafeNativeMethods.ACTCTX();
context.cbSize = Marshal.SizeOf(typeof(UnsafeNativeMethods.ACTCTX));
if (context.cbSize != 0x20)
{
throw new Exception("ACTCTX.cbSize is wrong");
}
context.lpSource = manifest;
IntPtr hActCtx = UnsafeNativeMethods.CreateActCtx(ref context);
if (hActCtx == (IntPtr)(-1))
{
throw new Win32Exception(Marshal.GetLastWin32Error());
}
try // with valid hActCtx
{
IntPtr cookie = IntPtr.Zero;
if (!UnsafeNativeMethods.ActivateActCtx(hActCtx, out cookie))
{
throw new Win32Exception(Marshal.GetLastWin32Error());
}
try // with activated context
{
action();
}
finally
{
UnsafeNativeMethods.DeactivateActCtx(0, cookie);
}
}
finally
{
UnsafeNativeMethods.ReleaseActCtx(hActCtx);
}
}
[SuppressUnmanagedCodeSecurity]
internal static class UnsafeNativeMethods
{
// Activation Context API Functions
[DllImport("Kernel32.dll", SetLastError = true, EntryPoint = "CreateActCtxW")]
internal extern static IntPtr CreateActCtx(ref ACTCTX actctx);
[DllImport("Kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool ActivateActCtx(IntPtr hActCtx, out IntPtr lpCookie);
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool DeactivateActCtx(int dwFlags, IntPtr lpCookie);
[DllImport("Kernel32.dll", SetLastError = true)]
internal static extern void ReleaseActCtx(IntPtr hActCtx);
// Activation context structure
[StructLayout(LayoutKind.Sequential, Pack = 4, CharSet = CharSet.Unicode)]
internal struct ACTCTX
{
public Int32 cbSize;
public UInt32 dwFlags;
public string lpSource;
public UInt16 wProcessorArchitecture;
public UInt16 wLangId;
public string lpAssemblyDirectory;
public string lpResourceName;
public string lpApplicationName;
public IntPtr hModule;
}
}
}</pre><!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin. http://dunnhq.com --></div>
<p>The method <em>UsingManifestDo </em>allows you to run any code of your choosing with an Activation Context loaded from a manifest file. Clearly we only need to invoke this when our code is being called from a Unit Test. But how do we structure code elegantly so that it uses the activation context when necessary, but not otherwise? Here’s my solution:</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:7dc84edb-cd7e-4987-bb3d-e0972cd5b1f0" class="wlWriterEditableSmartContent"><pre class="brush: csharp; gutter: false; first-line: 1; tab-size: 4; toolbar: true; ">public static class COMFactory
{
private static Func<Func<object>, object> _creationWrapper = function => function();
public static T CreateComObject<T>() where T:new()
{
var instance = (T)_creationWrapper(() => new T());
return instance;
}
public static object CreateComObject(Guid guid)
{
Type type = Type.GetTypeFromCLSID(guid);
var instance = _creationWrapper(() => Activator.CreateInstance(type));
return instance;
}
public static void UseManifestForCreation(string manifest)
{
_creationWrapper = function =>
{
object result = null;
ActivationContext.UsingManifestDo(manifest, () => result = function());
return result;
};
}
}</pre><!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin. http://dunnhq.com --></div>
<p>Whenever I need to create a COM Object in my production code, I do it by calling <em>COMFactory.CreateCOMObject</em>. By default this will create the COM objects directly, relying on the manifest which is embedded in the executable. </p>
<p>But in my Test project, before running any tests I call <em>COMFactory.UseManifestForCreation</em> and pass in the path to the manifest file. This ensures that the manifest gets loaded up before we try to create any COM objects in the tests. </p>
<p>To avoid duplicating the manifest file, I share the same file between my Test project and main executable project. You can do this right clicking your test project, choosing <em>Add->Existing Item… </em>then <em>app.manifest</em> in your main project. Finally, click the down arrow on the Add split button, and choose <em>Add as Link</em>. </p>
<p>If you’ve got any tips to share on using Registration-Free COM, whether in Unit Tests or just in applications, please do leave a comment.</p> Anonymoushttp://www.blogger.com/profile/01345100698738870730noreply@blogger.com3tag:blogger.com,1999:blog-7577421612120825312.post-7100200647741584442012-08-14T18:00:00.001+01:002012-08-14T20:03:34.282+01:00Data virtualization in Silverlight<p>When I <a href="http://blog.functionalfun.net/2011/05/say-hello-to-hatchling-seaturtle.html">first went freelance</a> (15 months ago – how time has rocketed by!) I promised myself that, with the reigns of my schedule tightly held in my own fist, I would dedicate more time to blogging. Well! You can all see from my <a href="http://blog.functionalfun.net/">blog archives</a> how that turned out. I have discovered that when you have clients willing to pay for as much time as you can give them, there’s a strange temptation to give them as much time as you’ve got!</p> <p>However. </p> <p>Just before I went on vacation last week, I <strike>found</strike> made the time to write a mini-blizzard of blog posts, though not for Functional Fun. <a href="http://ayende.com/blog">Ayende</a>, my client for the last few months, has published them on his <a href="http://blog.hibernatingrhinos.com/">company’s blog</a>. In the first batch, I wrote about some <a href="http://blog.hibernatingrhinos.com/12481/new-in-ravendb-studio-1-2-scrollable-document-lists-and-a-details-view">exciting</a> <a href="http://blog.hibernatingrhinos.com/12483/new-in-ravendb-studio-1-2-better-document-editing">new</a> <a href="http://blog.hibernatingrhinos.com/12482/new-in-ravendb-studio-1-2-enhancements-to-querying">features</a> I’ve coded up for the user interface of <a href="http://ravendb.net/">RavenDb</a>, Hibernating Rhino’s <a href="http://en.wikipedia.org/wiki/Document-oriented_database">Document Database</a> server. </p> <p>But I think you’ll most enjoy a couple of posts I wrote about data virtualization in Silverlight. The problem is a common one. How do you display huge lists of data items in a client application without pulling data unnecessarily from the server? Often applications fall back on paging – show one page of data, and make the user click a Next button when they want to see more. But in terms of usability, this technique feels pretty neolithic. So I figured out a way of using ListBoxes and DataGrids without needing to load all the data up front, but with properly proportioned scrollbars, slurping data from the server just in time as the user scrolls. </p> <p>Over on Hibernating Rhino’s blog you’ll find the two posts I wrote about this:</p> <ul> <li><a href="http://blog.hibernatingrhinos.com/12513/data-virtualization-lazy-loading-stealth-pagingndash-whatever-you-want-to-call-it-herersquo-s-how-to-do-it-in-silverlight">Data Virtualization, Lazy Loading, Stealth Paging–whatever you want to call it: Here’s how to do it in Silverlight</a> </li> <li><a href="http://blog.hibernatingrhinos.com/12514/data-virtualization-in-silverlight-digging-into-virtualcollection">Data Virtualization in Silverlight: Digging into VirtualCollection</a> </li> </ul> <p>There’s also a bonus post on how I created a <a href="http://blog.hibernatingrhinos.com/12515/implementing-a-virtualizingwrappanel">VirtualizingWrapPanel for Silverlight</a> – built so that we could display data in a card view rather than a list view.</p> <p>And best of all, I published a <a href="https://github.com/samueldjack/VirtualCollection">sample application</a> on GitHub with all the code you need to use this technique in your own applications. For those WPF-aficionados amongst you, you should find that the code translates without much difficulty. </p> Anonymoushttp://www.blogger.com/profile/01345100698738870730noreply@blogger.com10tag:blogger.com,1999:blog-7577421612120825312.post-28429809336448864442012-03-19T07:00:00.000+00:002012-03-19T09:18:19.332+00:00Weak Events in .Net, the easy way<p>I’ve <a href="http://blog.functionalfun.net/2009/06/managed-memory-leaks-and-their.html">written before</a> about one kind of memory leak the .Net Garbage Collector cannot protect against: those caused by event handlers keeping objects alive beyond their best-before date. <a href="http://www.danielgrunwald.de">Daniel Grunwald</a> has a <a href="http://www.codeproject.com/Articles/29922/Weak-Events-in-C">very comprehensive article</a> on CodeProject explaining the problem in depth, and giving a number of solutions, some of which I’ve used in the past.</p> <p>Nowadays, my preferred solution is one made possible by the fabulous <a href="http://msdn.microsoft.com/en-us/data/gg577609">Reactive Extensions (Rx) framework</a>. </p> <p>Suppose, as one example, you want to subscribe to a CollectionChanged event, but don’t want your object to be kept alive by that subscription. You can just do:</p> <pre class="brush: csharp;">collection.ObserveCollectionChanged()
.SubscribeWeakly(this, (target, eventArgs) => target.HandleEvent(eventArgs));
private void HandleEvent(NotifyCollectionChangedEventArgs item)
{
Console.WriteLine("Event received by Weak subscription");
}</pre>
<h4></h4>
<h4>How it works</h4>
<p>Like all remedies for un-dying object problems, the active ingredient in this one is the <a href="http://msdn.microsoft.com/en-us/library/system.weakreference.aspx">WeakReference</a> class. It works like this</p>
<pre class="brush: csharp;">public static class IObservableExtensions
{
public static IDisposable SubscribeWeakly<T, TTarget>(this IObservable<T> observable, TTarget target, Action<TTarget, T> onNext) where TTarget : class
{
var reference = new WeakReference(target);
if (onNext.Target != null)
{
throw new ArgumentException("onNext must refer to a static method, or else the subscription will still hold a strong reference to target");
}
IDisposable subscription = null;
subscription = observable.Subscribe(item =>
{
var currentTarget = reference.Target as TTarget;
if (currentTarget != null)
{
onNext(currentTarget, item);
}
else
{
subscription.Dispose();
}
});
return subscription;
}
}</pre>
<p>You can see that we hold the intended recipient of the notifications, <em>target</em>, as a <em>WeakReference</em>, so that if the Garbage Collector wants to sweep it up, this subscription won’t stand in its way. Then we subscribe a lambda function of our own to the observable. When we receive a notification from the observable, we check that <em>target</em> is still alive, and then pass along the message. If we discover that <em>target</em> has died, we mourn briefly, then cancel the subscription.</p>
<p>Notice though, that all our clever use of <em>WeakReference</em>s could be subverted if the <em>onNext</em> delegate refers to an instance method on the target. That delegate would then be smuggling in the implicit <em>this</em> pointer as a strong reference to the target. <em>onNext</em> is itself held strongly by the closure that is created for the lambda function, so the net effect would be that the target is kept alive by the subscription. </p>
<p>All of which explains why we do a check to ensure that <em>onNext.Target</em> is null, hence, that <em>onNext</em> is referring to a static method.</p>
<p>To be clear, this doesn’t mean that you can only handle events using static methods. It just means that when you call <em>SubscribeWeakly, </em>the lambda function you supply as <em>onNext</em> must call instance methods via the reference to the target it is given as a parameter (like I showed in the example above) rather than capturing an implicit <em>this</em> reference.</p>
<h4></h4>
<h4>Observing .Net events using Rx</h4>
<p>If you’re going to start using this, you’ll need to know how to turn .Net events into <em>IObservables</em>. Fortunately, the Rx framework includes a magic wand in the shape of <em><a href="http://msdn.microsoft.com/en-us/library/system.reactive.linq.observable.fromeventpattern(v=vs.103).aspx">Observable.FromEventPattern</a>.</em> </p>
<p>Working with events that have been coded-up post-generics, and thus use EventHandler<TEventArgs> delegates, is easiest. Here’s how you would observe the <em>TaskScheduler.UnobservedTaskException</em> event, for example:</p>
<pre class="brush: csharp;">Observable.FromEventPattern<UnobservedTaskExceptionEventArgs>(
handler => TaskScheduler.UnobservedTaskException += handler,
handler => TaskScheduler.UnobservedTaskException -= handler);</pre>
<p>You simply instruct Rx how to attach and detach the event handler it supplies.</p>
<p>Events defined pre-generics all had to roll their own delegate types, and that makes observing them 1-line-of-code more difficult. Here’s the definition of <em>ObserveCollectionChanged</em> which I used earlier:</p>
<pre class="brush: csharp;">public static IObservable<EventPattern<NotifyCollectionChangedEventArgs>> ObserveCollectionChanged(this INotifyCollectionChanged collection)
{
return Observable.FromEventPattern<NotifyCollectionChangedEventHandler, NotifyCollectionChangedEventArgs>(
handler => (sender, e) => handler(sender, e),
handler => collection.CollectionChanged += handler,
handler => collection.CollectionChanged -= handler);
}</pre>
<p>What’s happening here, in the first parameter to <em>FromEventPattern</em>, is that we are adapting an event handler delegate in standard form (i.e EventHandler<NotifyCollectionChangedEventArgs>) given to us by <em>Rx</em> into one appropriate for this specific event. In fact, the compiler is doing all the work, inferring the necessary types of the delegates for us. Then, as before, we show Rx how to hook the adapted handler up to the appropriate event, and how to detach when the subscription is cancelled.</p>
<h4>Prove It</h4>
<p>To prove this all works as it should, I’ve created a little test:</p>
<pre class="brush: csharp;">class Program
{
static void Main(string[] args)
{
var collection = new ObservableCollection<object>();
var strongSubscriber = new StrongSubscriber();
strongSubscriber.Subscribe(collection);
var weakSubscriber = new WeakSubscriber();
weakSubscriber.Subscribe(collection);
collection.Add(new object());
strongSubscriber = null;
weakSubscriber = null;
GC.Collect();
Console.WriteLine("Full collection completed");
collection.Add(new object());
Console.Read();
}
private class StrongSubscriber
{
public void Subscribe(ObservableCollection<object> collection)
{
collection.CollectionChanged += delegate { Console.WriteLine("Event Received By Strong Subscription"); };
}
}
private class WeakSubscriber
{
public void Subscribe(ObservableCollection<object> collection)
{
collection.ObserveCollectionChanged().SubscribeWeakly(this, (target, item) => target.HandleEvent(item));
}
private void HandleEvent(EventPattern<NotifyCollectionChangedEventArgs> item)
{
Console.WriteLine("Event received by Weak subscription");
}
}
}</pre>
<p>In the blue corner we have <em>StrongSubscriber</em> who subscribes to an event on a collection the standard way. And in the red corner we have <em>WeakSubscriber</em> who listens to events using <em>SubscribeWeakly.</em> We trigger an event to show that both are paying attention, then we attempt to nuke them, setting their references to null and doing a full garbage collection. Finally, we trigger another event, to see who survived the apocalypse. Here’s the result:</p>
<p><a href="http://lh6.ggpht.com/-7rmR1g8tjrg/T2MsUsNQ9OI/AAAAAAAAA9U/FShZE4Ch-1E/s1600-h/image%25255B4%25255D.png"><img style="display: block; float: none; margin-left: auto; margin-right: auto" title="image" alt="image" src="http://lh5.ggpht.com/-0r817BzK9Wc/T2MsVg0vh9I/AAAAAAAAA9c/jaiVH8hZnsc/image_thumb%25255B2%25255D.png?imgmax=800" width="439" height="181" /></a></p>
<p>As expected, the StrongSubscription clung on to life, whilst the WeakSubscription dutifully died.</p>
<h4>Here – take it!</h4>
<p>As with all the code on my blog, feel free to take this and use it in your own projects. I’d love to hear how you get on with it.</p> Anonymoushttp://www.blogger.com/profile/01345100698738870730noreply@blogger.com5tag:blogger.com,1999:blog-7577421612120825312.post-68849914051687482372012-03-14T14:08:00.001+00:002012-03-14T14:14:26.943+00:00Solved: Http Error returned for some route urls but not others in Asp.Net MVC or Web API<p><em>Here GoogleBing: remember this one for me so I don’t have to waste another two hours re-solving it.</em></p> <p>I’m working on a project using the new <a href="http://www.asp.net/web-api">Asp.Net Web API</a> and hit a really strange problem yesterday. Every time I called the <em>/search</em> endpoint, I’d get back a <em>Http Error 404.20 – Not Found</em>. All the other controllers were working fine. There were no exceptions being thrown and, even stranger, if I set a break point in the <em>SearchController</em> it was never hit.</p> <p>I spent two hours trying every which-way to get to the bottom of it.</p> <p>The light-bulb lit up when my eye latched on to this:</p> <div style="text-align: center; width: 250px; display: block; float: none; margin-left: auto; font-size: 80%; margin-right: auto"><a href="http://lh3.ggpht.com/-EVQpDh7UrMQ/T2Cma6nrgTI/AAAAAAAAA9E/HJN8rADcbNY/s1600-h/image%25255B6%25255D.png"><img style="display: block; float: none; margin-left: auto; margin-right: auto" title="image" alt="image" src="http://lh4.ggpht.com/--Ga74BhV7Bs/T2CmbQb-Z0I/AAAAAAAAA9I/-2mnQRRS7Ok/image_thumb%25255B2%25255D.png?imgmax=800" width="215" height="232" /></a><em>(No, that’s not <a href="http://www.infoq.com/news/2012/02/vs11goesgrey">Visual Studio 11</a>. I just faded all the rest to grey so you could see what I saw).</em></div> <p>There in the solution was a folder with the same name as the Web API Controller. A quick test confirmed that any route with the same url as a folder in my solution would give the same error. </p> <h4>The Solution</h4> <p>There’s the obvious solution: rename either your folder or your controller, so that there’s no conflict.</p> <p>But if you’re rather attached to your Controller name, and you’re loath to change your folder structure, there is another solution. When you register your Routes, set</p> <pre class="brush: csharp;">RouteTable.Routes.RouteExistingFiles = true;</pre>
<p>This makes Asp.Net Routing try the routes in your RouteTable first, even if there are files and directories that match them. </p>
<p>This by itself was enough for us, because we don’t have any files on disk that we want to serve up directly. But if you do, add</p>
<pre class="brush: csharp;">routes.IgnoreRoute("folder/{*path}");</pre>
<p>for each folder that you want to serve up, and everything should by hunky-dory.</p> Anonymoushttp://www.blogger.com/profile/01345100698738870730noreply@blogger.com1tag:blogger.com,1999:blog-7577421612120825312.post-12035659975951154892012-03-12T10:02:00.000+00:002012-03-12T10:02:00.583+00:00Fade-Trimming TextBlocks in Silverlight and WPF<p><a href="http://ayende.com/blog">Ayende</a> just published a <a href="http://blog.hibernatingrhinos.com/12385/fade-trimming-textblocks-in-silverlight-and-wpf">guest-post</a> I wrote on his company blog:</p> <blockquote> <p>Using ellipsis is <em>so</em> last year. When did you last see the cool HTML 5 kids writing … when they couldn’t fit all their text in a column? They’ve got this fancy new feature, powered by CSS3, where text that doesn’t quite fit simply fades out as it reaches the edge of the text block. Like this (with thanks to the <a href="http://quickui.org/catalog/Fader/">QuickUI Catalog</a>)</p> <p><a href="http://lh4.ggpht.com/-UlAbHJElxNg/T13CMZVBZcI/AAAAAAAAA80/-onTAAvb3-w/s1600-h/image3.png"><img style="display: inline" title="image" alt="image" src="http://lh3.ggpht.com/-XBP4ketHuo4/T13CM_ViMeI/AAAAAAAAA88/EUIr4MFZPCM/image_thumb1.png?imgmax=800" width="240" height="52" /></a></p> <p>Subtle! It looks much prettier, and it means you can fit in an extra three characters of real text instead of the …s.</p> <p>Silverlight’s future might be uncertain, but I want to show you that it isn’t ready to roll over and die just yet. We can have those fancy fade-trimming effects too!</p> <p>As part of the work I’m doing on the UI for <a href="http://ayende.com/blog/4828/designing-ravenfs">RavenFS</a>, I implemented Fade-trimming to make our DataGrids look smarter, and I thought it would be nice to share. So I’ve packaged up all you need into an easy-to-use class called <a href="https://github.com/samueldjack/FadeTrimming/blob/master/FadeTrimmingDemo.Silverlight/FadeTrimming.cs">FadeTrimming.cs</a> which works in Silverlight and WPF, and given you <a href="https://github.com/samueldjack/FadeTrimming">two demo projects</a> to show you how to get started.</p> </blockquote> <p>Read the whole article <a href="http://blog.hibernatingrhinos.com/12385/fade-trimming-textblocks-in-silverlight-and-wpf">here</a></p> Anonymoushttp://www.blogger.com/profile/01345100698738870730noreply@blogger.com1tag:blogger.com,1999:blog-7577421612120825312.post-34389820908655329582012-01-28T16:25:00.001+00:002012-01-30T09:37:21.180+00:00Crunch, the RESTful Accountants (And Introducing the Crunch API Explorer)<p>One of the things that scared me a little when I thought about starting my own business was the thought of the bookkeeping. I know, I know – I have a Maths degree, so I ought to be able to cope with adding up a few numbers then working out the 20% I owe to the tax man. And the 20% I owe to the VAT lady. And how to take just the right amount of salary to avoid giving anything to the PAYE person. But my arithmetic has always been terrible, and the mathematicians who lectured me, strange to say, rarely used actual numbers. It was all <em>x</em>s and <em>y</em>s and <em>β</em>s and <em>π</em>s. So that didn’t help.</p> <p><a href="http://crunch.co.uk"><img style="margin: 0px 7px 0px 0px; display: inline; float: left" title="Crunch" alt="Crunch" align="left" src="http://lh3.ggpht.com/-zCRvvaO-Y6s/TyQhWshMZEI/AAAAAAAAA8Y/afFHtGlrFNM/crunch-logo%25255B3%25255D.png?imgmax=800" width="199" height="39" /></a>A big factor in persuading me to make the leap into running a company was finding an excellent online accounting service to handle all those troublesome numbers for me. <a href="https://www.crunch.co.uk/">Crunch</a> are a smart bunch of accountants based down in Brighton who have teamed up with an equally smart bunch of developers to create bookkeeping software that is actually quite fun to use (I know – I couldn’t quite believe that when I read it on another freelancer’s blog, but it’s true!). You <a href="https://www.youtube.com/watch?v=II4hdMmXhrc&feature=player_embedded">enter all the numbers</a> in the website as you rake in the profits, or fork out to your suppliers, and at the end of the year, Crunch will put together your accounts and send them off to H.M.R.C. They’ll even submit your VAT returns for you. And handle your payroll, if you should happen to have any <strike>minions</strike> employees. All for £59.50 a month. It’s great. <a href="http://getcrun.ch/seatusj2qy">Sign up here</a> and we’ll both get a £25 Amazon voucher!</p> <p>And as if all that wasn’t awesome enough, earlier this month they <a href="https://www.crunch.co.uk/crunch-api-now-live/">launched an API</a>. It its RESTful, speaking XML, with OAuth authentication. That’s right – a REST API from an accountancy company! I should caution that the first release is limited to dealing with expenses and suppliers, but the dev team plan to add areas according to the priorities indicated by us users.</p> <h4>The Crunch API Explorer</h4> <p>Well, you know me. I couldn’t leave a shiny new toy like that lying on the shelf. So I had a play, and knocked together something that I think you’ll like.</p> <p>Allow me to introduce the Crunch API Explorer:</p> <p><a href="http://lh4.ggpht.com/-lEJWnPQsk2E/TyQhXIkzDtI/AAAAAAAAA8c/n6ycv8Sk3J0/s1600-h/image%25255B4%25255D.png"><img style="display: block; float: none; margin-left: auto; margin-right: auto" title="image" alt="image" src="http://lh6.ggpht.com/-EK32wXy0eX4/TyQhXo5vxgI/AAAAAAAAA8o/rneAa84vSdE/image_thumb%25255B2%25255D.png?imgmax=800" width="754" height="575" /></a></p> <p>It’s a little tool to help you poke and prod the Crunch API. You enter a URL, set the appropriate Http Method, hit Go!, and it will show you the XML that Crunch returns.</p> <p>You can download it <a href="http://clickonce.seaturtlesoftware.s3-website-eu-west-1.amazonaws.com/CrunchApiExplorer/CrunchApiExplorer.application">here</a> (it installs using ClickOnce, so it will auto-update when I add new features. If you don’t already have .Net 4.0 on your machine, you should be prompted to install it). To connect to Crunch using the Crunch API Explorer, you’ll need your own API key which you can get by contacting the nice folks at <a href="mailto:api-dev@crunch.co.uk">api-dev@crunch.co.uk</a>. Then you can make REST calls to your hearts delight. All the documentation you need about the resource URLs and the structure of the XML for submitting updates can be found <a href="http://support.crunch.co.uk/entries/20718898-introduction-to-the-api">here on the Crunch website</a>.</p> <p>Here are a few of my favourite features:</p> <ul> <li>XML Syntax colouring when you’re editing requests (this courtesy of <a href="http://avalonedit.net">AvalonEdit</a>, the open source WPF text editor component that is part of SharpDevelop) </li> <li>Makes you confirm any update/delete requests made to the live server (but not to the test server) </li> <li>All the source is available on <a href="https://github.com/samueldjack/CrunchAPIExplorer">GitHub</a>, so if ever you wanted an example of how to connect to an OAuth API with <a href="http://www.dotnetopenauth.net/">DotNetOAuth</a>, well – now you have one (see <a href="https://github.com/samueldjack/CrunchAPIExplorer/blob/master/CrunchApiExplorer/Crunch/CrunchFacade.cs">CrunchFacade.cs</a>). It’s all in C#, with some WPF, and of course a topping of MVVM. </li> </ul> <p>There are a couple of things I wanted to add, but didn’t get time for – maybe next week:</p> <ul> <li>Remembering frequently used resource URIs, and maybe saving template Xml request documents </li> <li>Ability to choose a file and insert it into the XML request documents in Base64 format for the APIs that support file upload </li> <li>Saving Base64 encoded data in the responses to files </li> </ul> <p>Anything else? </p> <p>I’d love to hear from anyone who finds this useful. Feature requests are welcome (<a href="http://help.github.com/send-pull-requests/">pull requests</a> even more so). And if you fancy forking this and adapting it to explore other APIs, be my guest.</p> Anonymoushttp://www.blogger.com/profile/01345100698738870730noreply@blogger.com2tag:blogger.com,1999:blog-7577421612120825312.post-72098567181881532822011-12-26T21:18:00.001+00:002011-12-26T21:18:06.492+00:00Happy Christmas to all<p>I hope you have all enjoyed a Happy Christmas. Nothing technical today. I just wanted to share with you something my six-year old daughter made for me:</p> <p><a href="http://lh4.ggpht.com/-ZJPocVrNJPA/TvjkiFXn7jI/AAAAAAAAA8E/nv5f0AX90bE/s1600-h/EPSON007%25255B5%25255D.jpg"><img style="display: block; float: none; margin-left: auto; margin-right: auto" title="EPSON007" alt="EPSON007" src="http://lh6.ggpht.com/-2TQb_iD9ZOY/TvjkjMlBpKI/AAAAAAAAA8M/XOExMcWH_fM/EPSON007_thumb%25255B3%25255D.jpg?imgmax=800" width="394" height="566" /></a></p> Anonymoushttp://www.blogger.com/profile/01345100698738870730noreply@blogger.com2tag:blogger.com,1999:blog-7577421612120825312.post-45457733809884231252011-11-29T22:29:00.001+00:002011-11-29T22:29:54.049+00:00Mini Review: NHibernate 3 Beginner’s Guide<p>I’ve recently re-discovered the pleasure of reading in bed, thanks to my new iPad, which, with its backlit screen, allows me to snuggle under the covers with a good book without disturbing my wife. <a href="http://www.packtpub.com/">Packt Publishing</a> kindly provided my bedtime reading for the last few nights - <strong><a href="http://www.amazon.co.uk/gp/product/1849516022/ref=as_li_ss_tl?ie=UTF8&tag=funcfun-21&linkCode=as2&camp=1634&creative=19450&creativeASIN=1849516022">NHibernate 3 Beginner's Guide</a></strong> by Dr. Gabriel Nicolas Schenker and Aaron Cure.</p> <p><a href="http://lh3.ggpht.com/-vISB27QLq5U/TtVc0WXUzzI/AAAAAAAAA7w/7COaP-wGOag/s1600-h/nhibernate%25255B1%25255D.png"><img style="background-image: none; border-right-width: 0px; margin: 0px 15px 0px 0px; padding-left: 0px; padding-right: 0px; display: inline; float: left; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="nhibernate" border="0" alt="nhibernate" align="left" src="http://lh5.ggpht.com/-YLnS3SibYic/TtVc32g843I/AAAAAAAAA74/DaS5fB87Qy4/nhibernate_thumb%25255B1%25255D.png?imgmax=800" width="252" height="316" /></a>This is a book I wish I’d had three years ago. Back then I was sketching designs for a database-heavy application, and I evaluated Nhibernate, but was put off by its steep learning curve, and skimpy documentation. The documentation has improved immensely in the years since, and NHibernate itself has got easier to use, but it can still appear daunting for someone just getting started. </p> <p>This book makes Nhibernate approachable for the absolute beginner, even one who is relatively new to database technologies. The author explains key concepts carefully, and drives lessons home with plenty of comprehensive step-by-step tutorials.</p> <p>What I particularly liked was the inclusion of the Nhibernate ecosystem: <a href="http://fluentnhibernate.org/">FluentNhibernate</a> (in my opinion the best mechanism for configuring NHibernate) is given good treatment, as is <a href="http://nhprof.com/">NHProf</a>, a commercial Nhibernate profiling tool. It was also nice to see an introduction to unit testing NHibernate data access layers.</p> <p>One area that I did feel was a little weak was the section on setting up mappings. The author gives examples of three different ways in which mappings can be configured, but doesn't cover important aspects like cascading updates in much detail at all – something I’ve been caught out by several times, and an area on which I would have appreciated some friendly guidance when I was starting out. Have a look at <a href="http://www.amazon.co.uk/gp/product/1932394923/ref=as_li_ss_tl?ie=UTF8&tag=funcfun-21&linkCode=as2&camp=1634&creative=19450&creativeASIN=1932394923">NHibernate in Action</a> if you want to dig in more deeply here.</p> <p>This book definitely goes on my list to recommend to anybody starting out with NHibernate development. </p> Anonymoushttp://www.blogger.com/profile/01345100698738870730noreply@blogger.com0tag:blogger.com,1999:blog-7577421612120825312.post-87770285688311659952011-10-24T11:00:00.000+01:002011-10-24T11:05:24.048+01:00XAML Magic: Turning an Ugly Silverlight Duckling into a Beautiful Photoshopped Swan<p>Over the last few weeks I’ve had the privilege of working with <a href="http://ayende.com/blog/">Ayende</a> and the <a href="http://hibernatingrhinos.com">Hibernating Rhinos</a> team on the new management UI for <a href="http://ravendb.net/">RavenDB</a>. Never one to follow the herd (unless perhaps it <a href="http://ayende.com/blog/58369/all-the-rhinos-in-the-world-unite">consisted of Rhinos</a>), Ayende’s bucking the trend and building it in Silverlight.</p> <p>My part was to beautify the application by mimicking Photoshop designs that a designer had created for a new version of the RavenDB website. I was quite pleased with the way it turned out, and the <a href="http://ayende.com/blog/125953/peeking-behind-the-curtains-the-new-ravendb-management-studio">screenshots Ayende posted on his blog</a> got some favourable feedback.</p> <p>Ayende asked me to write a blog post on the transmogrification process, and he has just published it on <a href="http://blog.hibernatingrhinos.com/10241/xaml-magic-turning-an-ugly-silverlight-duckling-into-a-beautiful-photoshopped-swan">the company blog</a>. Go read it, to find out how I turned this </p> <p><a href="http://lh4.ggpht.com/-oFNySPeXo1g/TqG7embgNUI/AAAAAAAAA6k/5rI-LEN5o18/s1600-h/image_thumb30%25255B3%25255D.png"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="image_thumb30" border="0" alt="image_thumb30" src="http://lh3.ggpht.com/-kXeCt9z52-4/TqG7hgMnrCI/AAAAAAAAA6s/-G3r9cMckbA/image_thumb30_thumb.png?imgmax=800" width="600" height="440" /></a></p> <p>into this</p> <p><img alt="image" src="http://ayende.com/blog/Images/Windows-Live-Writer/Peeking-behind-the-curtains-The-new-Rave_404C/image_thumb.png" width="600" height="332" /></p> Anonymoushttp://www.blogger.com/profile/01345100698738870730noreply@blogger.com1tag:blogger.com,1999:blog-7577421612120825312.post-11273441785353183082011-10-03T12:17:00.001+01:002011-10-03T12:50:04.181+01:00Announcing the launch of Mixed In Key 5<p>I’m very pleased to announce that <a href="http://www.mixedinkey.com/">Mixed In Key LLC</a>, one of my clients, have just launched the product I’ve been working on for the last eight months. <a href="http://www.mixedinkey.com/Screenshots.aspx">Mixed In Key 5.0</a> is for DJs who put together their DJ sets using <a href="http://www.harmonic-mixing.com/">harmonic mixing</a>, a technique for ensuring a musically pleasing transition from one track to the next by eliminating key clashes. <a href="http://lh4.ggpht.com/-QfefFpyVDUg/TomZwIXSFjI/AAAAAAAAA6U/whFUMFCjkXU/s1600-h/image%25255B7%25255D.png"><img style="margin: 10px auto; display: block; float: none" title="Mixed In Key 5.0" alt="Mixed In Key 5.0" src="http://lh3.ggpht.com/-SbHdpQWsDOo/TomZw4B6v5I/AAAAAAAAA6Y/PJSC0AU_pFc/image_thumb%25255B5%25255D.png?imgmax=800" width="682" height="480" /></a></p> <h4></h4> <h4>How it works</h4> <p><a href="http://lh4.ggpht.com/-aQdfaIgXYa0/TomZxbEp3rI/AAAAAAAAA6c/A48mLH9fTJ8/s1600-h/camelotSmall%25255B5%25255D.jpg"><img style="margin: 0px 0px 0px 10px; display: inline; float: right" title="The Camelot Wheel" alt="The Camelot Wheel" align="right" src="http://lh5.ggpht.com/-8H7jtxkW3e0/TomZx0-0XmI/AAAAAAAAA6g/exHCDa0MxMw/camelotSmall_thumb%25255B3%25255D.jpg?imgmax=800" width="231" height="231" /></a>Mixed In Key supplies the key ingredient to successful harmonic mixing. It analyses every song in a DJ’s collection and determines which key it is written in (by key, I mean <a href="http://en.wikipedia.org/wiki/Key_(music)">musical key</a>, like C#, F#, A Minor, etc.). Every song is then added to a searchable database. </p> <p>The other ingredient comes from music theory, and has been cleverly codified by Mark Davis into the <a href="http://www.mixedinkey.com/HowTo.aspx">Camelot Wheel</a>. This shows the relationship between each key in a diagram arranged like a clock. To build a harmonic mix, a DJ finds the key of his first song on the wheel (so E Major is at the twelve o’clock position). For his next song he should pick one in a key which is an “hour” to the left or right, or stay at the same hour but switch between major or minor keys. Mixed In Key 5.0 includes a clickable Camelot Wheel to instantly search the database for songs in a particular key.</p> <h4></h4> <h4>Under the bonnet</h4> <p>The User Interface is all built in WPF. As I hinted in an <a href="http://blog.functionalfun.net/2011/07/how-to-create-inner-shadow-effects-in.html">earlier blog post</a>, I had a great time taking the designs beautifully drawn up for us in Photoshop by our designers and mapping them into XAML. Though I have to say, it is a painstaking process, poking all those pixels into precisely the prescribed positions – I guess it took something like 5 or 6 days to polish the 4 screens in the applications.</p> <p>But more important than looking gorgeous, Mixed In Key 5.0 had to be fast and responsive (we started the project many months before Windows 8 was announced, otherwise that would have been “fast and fluid”). I have to thank the <a href="http://msdn.microsoft.com/en-us/library/dd460717.aspx">Task Parallel Library</a> in .Net 4.0 for making this really easy to achieve (though not as easy as it will be in <a href="http://blog.functionalfun.net/2011/09/whats-new-in-c-50-and-vbnet.html">C# 5.0</a>, when we get our hands on the <a href="http://blog.functionalfun.net/2010/10/c-50-asynchronous-revolution.html">await keyword</a>). </p> <p>At the heart of the application is song analysis, which is a process with several steps. First, we read the song data using some custom DirectShow filters (DirectShow is actually rather fun to use once you’ve got the hang of it). Then we send extracts of the data off to our analysis server in the cloud for processing. Finally we have to add it to the database. Each of the steps takes a while to complete, so are ideal candidates for Tasks.</p> <p>.Net 4.5 has a rather nice <a href="http://blogs.msdn.com/b/pfxteam/archive/2011/09/27/10217461.aspx">Dataflow library</a> that is ideal for setting up a pipeline of tasks that need to be processed asynchronously. But that’s not out yet, so I used some <a href="http://blogs.msdn.com/b/pfxteam/archive/2010/11/21/10094564.aspx">extensions that Stephen Toub wrote</a> to the current TPL library for chaining Tasks together. Here’s what our analysis pipeline looks like:</p> <pre class="brush: csharp; toolbar: false;">AnalyzeSongAudio(progressReporter, file)
.Then(audioAnalysis => file.AudioAnalysis = audioAnalysis)
.Then(_ => ReadFileTags(file))
.Then(tags => file.Tags = tags)
.Then(() => SetItemStatus(file, QueuedFileStatus.DetectingKey))
.Then(_ => DetectKey(file))
.Then(result => file.SongAnalysisResult = result)
.Then(_ => RewriteTags(file))
.Then(result => AddSongToCollection(file))
.Then(song => UpdateQueuedFileWithSong(file, song))
.Then(() => SetItemStatus(file, QueuedFileStatus.UpdatingFile))
.Then(() => UpdateFile(file))
.Then(() => SetItemStatus(file, QueuedFileStatus.Completed))
.OnError(task => UpdateItemWithError(file, task.Exception.InnerException), Schedulers.UIThread)
.ContinueWith(t => DecrementQueuedFileCount(), TaskContinuationOptions.ExecuteSynchronously);</pre>
<p>As an aside, do you know the best thing about using Tasks in your application? You get your <a href="http://www.gotw.ca/publications/concurrency-ddj.htm">free lunches</a> back again! As PCs get more and more cores, your application will automatically scale to take advantage of them.</p>
<h4></h4>
<h4>What a launch!</h4>
<p>Yakov, the founder of Mixed In Key LLC, tells me that the launch has been very successful already.The <a href="http://twitter.com/mixedinkey">Mixed In Key Twitter stream</a> has been flooded with happy comments. Here are a few of my favourites:</p>
<blockquote>
<p>Woke up without a hangover, got called off jury duty & <a href="https://twitter.com/#!/MixedInKey"><s><strong>@</strong></s><strong><b>MixedInKey</b></strong></a>just came out with version 5.0 that analyzes video!!! Start of a good day</p>
</blockquote>
<blockquote>
<p><a href="https://twitter.com/#!/MixedInKey"><s><strong>@</strong></s><strong><b>MixedInKey</b></strong></a> You guys did it! <a href="https://twitter.com/#!/search?q=%23MIK5"><s>#</s><b>MIK5</b></a> is working like a charm. Gorgeous interface, unrivaled speed, heaps new features and still easy to use!!</p>
<p>My new <a href="https://twitter.com/#!/MixedInKey"><s><strong>@</strong></s><strong><b>MixedInKey</b></strong></a> purchase rocks! Firing on all 4 cores at the moment at 100% CPU, this thing is <a href="https://twitter.com/#!/search?q=%23fast"><s>#</s><b>fast</b></a>! Currently scanning 3000 songs :)</p>
<p><a href="https://twitter.com/#!/MixedInKey"><s>@</s><b>MixedInKey</b></a> is very very fast! Like a thunder! The multicore processing is the best feature</p>
</blockquote>
<p>So Congratulations to Yakov and the rest of <a href="http://www.mixedinkey.com/Credits.aspx">the Mixed In Key team</a>, and thanks for letting me help out on such an exciting project.</p> Anonymoushttp://www.blogger.com/profile/01345100698738870730noreply@blogger.com7tag:blogger.com,1999:blog-7577421612120825312.post-63788945873968446232011-09-16T19:12:00.001+01:002011-09-26T13:48:35.963+01:00What’s new in C# 5.0 and VB.Net?<p>As always, <a href="http://channel9.msdn.com/Events/BUILD/BUILD2011/TOOL-816T">Anders Hejlberg’s session</a> at <a href="http://channel9.msdn.com/Events/BUILD/BUILD2011">Microsoft’s Build conference</a> was a must-see. He’s a great presenter, and he had some great things to show off.</p> <p>Anders started off by laying out what’s new in C# 5.0 and VB.Net. Bear in mind that Microsoft now have a <a href="http://blog.functionalfun.net/2009/11/future-directions-for-c-and-visual.html">policy of language parity for C# and VB.Net</a>. So both languages get Windows Runtime support, Asynchronous programming and a brand new feature, Caller info attributes. VB.Net plays catch-up, and finally gets support for Iterators.</p> <h4>Asynchronous Methods</h4> <p>The first demo in Anders talk was about asynchronous programming. He introduced it by reminding us how vital responsiveness is in touch applications. This was something Jensen Harris mentioned <a href="http://channel9.msdn.com/Events/BUILD/BUILD2011/BPS-1004">in his talk</a>. Touch User Interfaces are visceral. If an application doesn’t respond immediately when you touch it, it feels dead, whereas using a mouse or keyboard introduces a kind of disconnect between you and the computer which makes delays feel more acceptable.</p> <p>In the Windows Runtime, the designers took the decision that if an operation was going to take more than 50 milliseconds to complete, it must be implemented asynchronously. There will be no synchronous equivalent – it would make it too easy for developers to do the lazy thing. So, all of a sudden it becomes really important to be able to do asynchronous programming easily.</p> <p>This is where C# shines in comparison to C++ or Javascript for writing Metro style apps. In those languages, doing asynchronous programming means callbacks, and that means turning your programming inside out. The Asynchronous Methods feature in C# allows you to do async programming in the usual, straightforward, do-this-then-that fashion. </p> <p>I won’t say any more on that here. Go watch <a href="http://channel9.msdn.com/Events/BUILD/BUILD2011/TOOL-816T">Anders demo</a> if you haven’t groked async yet. Your future as a Windows developer depends on it!</p> <h4>Windows Runtime integration</h4> <p>In the next section of his talk (starting at 26:00), Anders demonstrated more of the deep integration that C# and .Net now has with the Windows Runtime. He showed how it is possible to take a C# “compute engine” and expose it to a HTML/Javascript meto-style app (it works just as well with C++). You can take a C# project, compile to a WinMD file, then reference it from your HTML/Javascript project. This gives you intellisense for your C# objects when you access them from your Javascript code. As Anders said, “In Javascript, you sometimes get lucky. [Beat]. Of course, in C# you get lucky always! … I’m Just saying!”</p> <h4>Caller Info Attributes</h4> <p>The aforementioned Caller info attributes came up next (see video at 32:00). Not a big feature, just a palate cleanser between demos, according to Anders.</p> <p>Apparently the C# team often get asked when they’re going to introduce support for <a href="http://msdn.microsoft.com/en-us/library/b0084kay(v=vs.71).aspx">__FILE__ and __LINE__ macros</a>, which, C++ developers will know, expand when compiled to produce a string containing the name of the current source file, and the current line, respectively. Of course, C# will only introduce support for macros over Ander’s dead body, so the team had to find another way.</p> <p>Anders related that back in the days of C# 1.0 they had a design that implemented this feature using attributes, but it involved optional parameters on methods which weren’t supported at the time. Well, now C# 4.0 supports optional parameters on methods, so the team revisited the design, and, lo and behold, C# 5.0 now has the CallerFilePath, CallerLineNumber and CallerMemberName attributes.</p> <p>You can write a Trace.WriteLine method like this:</p> <pre class="brush: csharp;">public static class Trace
{
public static void WriteLine(string message,
[CallerFilePath] string file = "",
[CallerLineNumber] in line = 0,
[CallerMemberName] string member = "")
{
var s = string.Format("{0}:{1} - {2}: {3}", file, line, member, message);
Console.WriteLine(s);
}
}</pre>
<p>Then, if you were to call Trace.WriteLine(“Something just happened”) the compiler would automatically fill out the optional parameters in the WriteLine method with details of where you made the call from.</p>
<p>This isn’t in the current developer preview, but will be in the final release. As Anders said, not a big feature, but no doubt somebody will put it to good use.</p>
<h4></h4>
<h4>The Roslyn (Compiler APIs) Project</h4>
<p>The last half of the talk (starting at 35:26) dealt with what comes after C# 5.0, which is what project “Roslyn” in all about (named apparently after a cute little mining town, an hours drive from Seattle). Roslyn is “the compiler re-imagined”. Anders introduced Roslyn by noting that we are increasingly addicted to IDE productivity tools which provide features like “Find Reference”, “Go to Symbol”, “Rename”,  and “Extract Method”. All these need knowledge about code that is traditionally locked inside the compiler. </p>
<p>Roslyn is all about building compiler APIs that expose what the compiler knows about code to the IDE and to developers. It will include Syntax Tree APIs, Symbol APIs, Binding and Flow Analysis APIs and Emit APIs. The APIs are designed using modern principles. So, for example, the SyntaxTree objects are completely immutable (though you can create new ones by combing bits from old ones) and this means that they are concurrency safe. All the language services in the IDE (syntax colouring, intellisense, etc.) are going to be using Roslyn.</p>
<p>All this is going to be available to us starting mid October, when a CTP of Visual Studio Roslyn will be released. APIs will be available for both C# and VB.</p>
<p>The demos Anders gave of Roslyn are pretty impressive (starting 43:00). First up was the ScriptEngine API that allows you to parse and execute code from a string, or even get a delegate back for executing it at some later point. This led in to the demo of the C# interactive window, which will be part of Visual Studio in the future. You can select code in the editor, press Alt-Enter and have it immediately executed in the interactive window. If you then go and edit it there, you get intellisense, even for methods that you have just interactively defined.</p>
<p>Another demo,roundly applauded, was “Paste as VB” and “Paste as C#” which uses the Roslyn APIs to parse and translate code from the Clipboard buffer. The source code for this will be made available in the CTP.</p>
<p>None of this was big news, of course, because Anders first started talking about it when <a href="http://blog.functionalfun.net/2008/10/dynamic-future-of-c-40.html">I was at PDC in 2008</a>. But it’s nice to know that it’s moving on steadily, and that we’ll soon be able to have a play with it.</p> Anonymoushttp://www.blogger.com/profile/01345100698738870730noreply@blogger.com6tag:blogger.com,1999:blog-7577421612120825312.post-46736103580721775932011-09-16T10:53:00.001+01:002011-09-16T15:18:52.050+01:00Windows Runtime – Dial in the right expectations before reading up<p>Three days on from <a href="http://channel9.msdn.com/events/BUILD/BUILD2011/KEY-0001">the announcement</a> of the Windows Runtime at Microsoft’s <a href="http://www.buildwindows.com/">Build conference</a> the marketing dust is settling and the full picture emerging. As you begin to read up what the Windows Runtime actually is you’ll need to set your expectations to the right level or you run the risk of being disappointed. But set them appropriately and I think you’ll see that an exciting developer journey lies ahead.</p> <p>Leading up to the conference <a href="http://blog.functionalfun.net/2011/09/microsofts-build-windows-conference-is.html">I was hoping</a> for a new lean-and-mean User Interface platform for writing any kind of Windows application. But that isn’t what Windows Runtime is about. As things stand this week, Windows Runtime is about producing Metro-style applications (think Windows Phone 7) optimised for running on Tablet devices. Windows Runtime is aimed squarely at the solar plexus of iOS and Android 3.0. </p> <p><a href="http://tirania.org/blog/archive/2011/Sep-15.html">Miguel de Icaza</a> and <a href="http://www.itwriting.com/blog/4866-a-few-facts-about-microsofts-new-windows-runtime.html">Tim Anderson</a> have already done a good job of writing up what has been announced so far about Windows Runtime (or WinRT). But here are the two key points to notice:</p> <ul> <li><strong>Metro-style apps run in a sandboxed environment</strong>. As with Windows Phone 7, apps have to declare upfront, <a href="http://msdn.microsoft.com/en-us/library/windows/apps/hh464929(v=VS.85).aspx#capabilities">through a manifest built in at compilation time</a>, which capabilities of your PC they intend to use. Access to APIs is monitored at runtime by the Runtime Broker, which prevents your app from doing anything naughty. Only certain parts of the <a href="http://msdn.microsoft.com/en-us/library/windows/apps/br230302(v=VS.85).aspx">.Net Base Class Libraries can be used</a>, and even native developers are limited as to <a href="http://msdn.microsoft.com/en-us/library/windows/apps/br205757(v=VS.85).aspx">which Win32 or COM objects</a> they call. Apps can only talk to each other through the WinRT-endorsed Contracts, which allow for Sharing, File-picking etc. <p>To a developer all this sounds like a horrible restriction. But it is wonderful for users, who can have much more confidence that applications they install from the new App Store will not get up to mischief.</p> </li> <li><strong>Metro-style apps are always full screen and immersive</strong>. Windows Runtime does not provide a general-purpose windowing system. Several presenters at the conference mentioned that support for overlapping windows have been intentionally left out. And for one simple reason: they don’t work well in a touch-centric environment. </li> </ul> <p>Windows Runtime is not (at the moment) a general purpose runtime. It may get there eventually, but for the time being it is focused on building the kinds of apps and games that today you might run on the iPad, the Xoom, or (once the lawyers have finished their fisticuffs) the Galaxy Tab. Think of it as Silverlight-on-Steroids-With-Native-Extensions for Tablets and you won’t go far wrong.</p> <p>As speakers at Build conceded, there are many kinds of application that would not fit the Metro-style. Visual Studio is one. Photoshop is another. Microsoft Office is (possibly) a third. For these kinds of apps, keyboard, mouse, menus, toolbars, ribbons and dialog boxes still works best. </p> <p>This means Win32 and WPF are still very much alive. Though there are no sessions about it at the conference, <a href="http://msdn.microsoft.com/en-us/library/bb613588(v=VS.110).aspx">WPF 4.5 has been announced</a> with a number of not-insignificant new features, including the <a href="http://blog.functionalfun.net/2010/11/wpf-to-support-hosting-of-silverlight.html">promised fix</a> for the Win32 airspace restrictions (though nothing has been said about hosting Silverlight controls in WPF apps).</p> <p>I’m no prophet, but I don’t believe this is the last we’ll hear about WPF.</p> Anonymoushttp://www.blogger.com/profile/01345100698738870730noreply@blogger.com1tag:blogger.com,1999:blog-7577421612120825312.post-71980229052551901192011-09-14T10:18:00.001+01:002011-09-15T09:09:38.379+01:00Build Windows Day 1–and a peek a what’s to come<p>If you haven’t caught the news already, yesterday at Microsoft’s <a href="http://www.buildwindows.com/">Build Windows</a> conference Steven Sinofsky announced a preview of Windows 8 and a bunch of developer tools, including Visual Studio 11. You can download it <a href="http://msdn.microsoft.com/en-us/windows/apps/br229516">here</a>. </p> <p><a href="http://blog.functionalfun.net/2011/09/microsofts-build-windows-conference-is.html">As predicted</a>, Windows 8 comes with an all new development framework, the Windows Runtime (WinRT). I’ve not read enough myself to begin explaining. But here’s a picture, snapped during Steven Sinofsky’s keynote:</p> <p><a href="http://lh6.ggpht.com/-vbcHI2hLwEA/TnBxafQgygI/AAAAAAAAA6M/ZJ4IFDuQVps/s1600-h/image%25255B4%25255D.png"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: block; float: none; border-top-width: 0px; border-bottom-width: 0px; margin-left: auto; border-left-width: 0px; margin-right: auto; padding-top: 0px" title="Windows 8 Platform and Tools - How WinRT relates to Win32 and .Net" border="0" alt="Windows 8 Platform and Tools - How WinRT relates to Win32 and .Net" src="http://lh5.ggpht.com/-rya8adHhQ14/TnBxc9_hXaI/AAAAAAAAA6Q/ZQFXffaPsTc/image_thumb%25255B2%25255D.png?imgmax=800" width="736" height="426" /></a></p> <p>WinRT is an object-oriented API, consisting of 1800 objects, accessible to managed, unmanaged and JavaScript code alike. Sinofsky emphasised that this WinRT is a peer to Win32, not another abstraction layer built on top of it. As this diagram clearly shows, and Sinofsky stressed in his talk, Win32, .Net and Silverlight developers have nothing to fear, all current frameworks continue to work in Windows 8.</p> <p>I’m sure to have more to say about WinRT in the coming days. In the meantime, InfoQ has a couple of articles <a href="http://www.infoq.com/news/2011/09/WinRT-API">summarising</a> <a href="http://www.infoq.com/news/2011/09/WinRT">what we learned</a> in the keynote. If you’re wanting a sneak peak at the API’s themselves, check out the <a href="http://msdn.microsoft.com/en-us/library/windows/apps/br211377">preview documentation</a> on MSDN.</p> <p>The videos are the first few sessions of the conference are already up on the web:</p> <ul> <li>The <a href="http://channel9.msdn.com/Events/BUILD/BUILD2011/KEY-0001">Day 1 Keynote</a> </li> <li>Jensen Harris: <a href="http://channel9.msdn.com/events/BUILD/BUILD2011/BPS-1004">8 traits of great Metro style apps</a> </li> <li>Aleš Holeček and John Sheehan: <a href="http://channel9.msdn.com/events/BUILD/BUILD2011/BPS-1005">Platform for Metro style apps</a> </li> </ul> <h4>What’s next?</h4> <p>In other news, the <a href="http://channel9.msdn.com/events/BUILD/BUILD2011">session list</a> is now up for the rest of the week. Here are a few that grab my attention.</p> <ul> <li>Anders Hejlsberg on <a href="http://channel9.msdn.com/Events/BUILD/BUILD2011/TOOL-816T">Future directions for C# and Visual Basic</a>. Doesn’t look like “Roslyn” (compiler-as-a-service) will make it into Visual Studio 11. But he might announce some new language features for C# 5.0. </li> <li>Mark Miller and Pracheeti Nagarkar give a <a href="http://channel9.msdn.com/Events/BUILD/BUILD2011/TOOL-813T">Deep dive into the kernel of the .Net Framework</a>. Sounds like they’ve done yet more work to improve code-generation and garbage collection. </li> <li>Stephen Toub, one of my favourite speakers from previous years, is doing two sessions: <a href="http://channel9.msdn.com/Events/BUILD/BUILD2011/TOOL-829T">The zen of async: Best practices for performance</a> (vital know-how, given that many of the new WinRT API’s will be asynchronous) and <a href="http://channel9.msdn.com/Events/BUILD/BUILD2011/SAC-808T">Building parallelized apps with .Net and Visual Studio</a> (look for some announcements about new parallelization libraries). </li> <li>Harry Pierson and Jesse Kaplan are doing a talk on <a href="http://channel9.msdn.com/Events/BUILD/BUILD2011/TOOL-531T">Using the Windows Runtime from C# and Visual Basic</a> </li> <li>Out of curiosity, I make take a look at Daniel Moth’s <a href="http://channel9.msdn.com/Events/BUILD/BUILD2011/TOOL-802T">Taming GPU compute with C++ AMP</a> where he’s going to introduce new tools and language features for using the GPU within C++ solutions. </li> <li>Boris Jabes talk <a href="http://channel9.msdn.com/Events/BUILD/BUILD2011/TOOL-761T">A lap around DirectX game development tools</a> also piques my interest, as it promises the “most significant set of improvements for developing graphics-intensive apps in over a decade”. </li> </ul> <p>And now, on with the show!</p> Anonymoushttp://www.blogger.com/profile/01345100698738870730noreply@blogger.com3