<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0">

<channel>
	<title>Andrei Rinea's technical blog</title>
	
	<link>http://blog.andrei.rinea.ro</link>
	<description>.NET and SQL Server</description>
	<lastBuildDate>Fri, 10 May 2013 09:18:50 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/Andrei-Rinea" /><feedburner:info uri="andrei-rinea" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><item>
		<title>Bing it on, Reactive Extensions!</title>
		<link>http://feedproxy.google.com/~r/Andrei-Rinea/~3/WRZeAYYG_0I/</link>
		<comments>http://blog.andrei.rinea.ro/2013/05/10/bing-it-on-reactive-extensions/#comments</comments>
		<pubDate>Fri, 10 May 2013 09:18:50 +0000</pubDate>
		<dc:creator>Andrei Rinea</dc:creator>
				<category><![CDATA[Presentations]]></category>
		<category><![CDATA[bing]]></category>
		<category><![CDATA[bucharest]]></category>
		<category><![CDATA[presentation]]></category>
		<category><![CDATA[Reactive Extensions]]></category>
		<category><![CDATA[RONUA]]></category>
		<category><![CDATA[Rx]]></category>

		<guid isPermaLink="false">http://blog.andrei.rinea.ro/?p=320</guid>
		<description><![CDATA[Next Tuesday (May 14th, 2013) I will be presenting a small demo of how Reactive Extensions can help you out in a desktop application. I&#8217;ll develop a small WPF app that will do internet searching via Bing. Anyone in Bucharest &#8230;<p class="read-more"><a href="http://blog.andrei.rinea.ro/2013/05/10/bing-it-on-reactive-extensions/">Read more &#187;</a></p>]]></description>
			<content:encoded><![CDATA[<div class="google_plusone_widget"><g:plusone 
      count="true" href="http://blog.andrei.rinea.ro/2013/05/10/bing-it-on-reactive-extensions/" size="tall"></g:plusone></div><p>Next Tuesday (May 14th, 2013) I will be presenting a small demo of how Reactive Extensions can help you out in a desktop application.</p>
<p>I&#8217;ll develop a small WPF app that will do internet searching via Bing.</p>
<p>Anyone in Bucharest is free to drop by and watch my demo or my colleague&#8217;s demo (Alexandru Gatej will be presenting &#8220;Aspects of plan caching and recompilation in Microsoft SQL Server&#8221;).</p>
<p><strong>Location and time :</strong></p>
<p>Beginning at 18:30 (Alexandru&#8217;s presentation will go first) at <a href="http://binged.it/10Khugu">UBISOFT Romania</a> ( <- click for map ), 2 Expozitiei Boulevard, district 1, Bucharest.</p>
<p>Hope to see many people!</p>
<img src="http://feeds.feedburner.com/~r/Andrei-Rinea/~4/WRZeAYYG_0I" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.andrei.rinea.ro/2013/05/10/bing-it-on-reactive-extensions/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://blog.andrei.rinea.ro/2013/05/10/bing-it-on-reactive-extensions/?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=bing-it-on-reactive-extensions</feedburner:origLink></item>
		<item>
		<title>Windows Phone 8 – Samsung ATIV S</title>
		<link>http://feedproxy.google.com/~r/Andrei-Rinea/~3/JZE9Li4cAUY/</link>
		<comments>http://blog.andrei.rinea.ro/2013/04/17/windows-phone-8-samsung-ativ-s/#comments</comments>
		<pubDate>Wed, 17 Apr 2013 15:12:59 +0000</pubDate>
		<dc:creator>Andrei Rinea</dc:creator>
				<category><![CDATA[Hardware]]></category>
		<category><![CDATA[ATIV S]]></category>
		<category><![CDATA[Samsung]]></category>
		<category><![CDATA[Windows Phone]]></category>
		<category><![CDATA[Windows Phone 8]]></category>

		<guid isPermaLink="false">http://blog.andrei.rinea.ro/?p=306</guid>
		<description><![CDATA[After two and a half year of struggling with the crappy Android OS on Samsung Galaxy S I&#8217;ve finally decided that &#8216;enough is enough&#8217;. I&#8217;ve wanted a small tablet so I can read (blogs and so on) easily so I &#8230;<p class="read-more"><a href="http://blog.andrei.rinea.ro/2013/04/17/windows-phone-8-samsung-ativ-s/">Read more &#187;</a></p>]]></description>
			<content:encoded><![CDATA[<div class="google_plusone_widget"><g:plusone 
      count="true" href="http://blog.andrei.rinea.ro/2013/04/17/windows-phone-8-samsung-ativ-s/" size="tall"></g:plusone></div><p>After two and a half year of struggling with the crappy Android OS on <a href="http://www.gsmarena.com/samsung_i9000_galaxy_s-3115.php">Samsung Galaxy S</a> I&#8217;ve finally decided that &#8216;enough is enough&#8217;.</p>
<p>I&#8217;ve wanted a small tablet so I can read (blogs and so on) easily so I was a bit into <a href="http://www.gsmarena.com/samsung_galaxy_note_ii_n7100-4854.php">Samsung Galaxy Note II</a>. Along with the fact that this too is an Android phone (OS which corrupts its own system files and lost my whole user data, lags horribly and so on) several fellow colleagues from <a href="http://ronua.ro">RONUA</a> (a local programming user group) warned me against as they already are owners.</p>
<p>One told me that approximately 50% of the phone calls he can&#8217;t hear the other party nor he can be heard and the other one told me he is experiencing approximately a complete OS freeze once per day. He is only able to restart the device by removing the battery and reinstering it.</p>
<p>I then looked for another-OS, large-display and low-SAR phone in the market. iOS &#8216;simply works&#8217;, I can&#8217;t deny but there was no large screen phone available, no low-SAR phone and nonetheless objective-C sucks incredibly bad.<br />
Ironically I found another Samsung, the <a href="http://www.gsmarena.com/samsung_ativ_s_i8750-4960.php">ATIV S</a>.</p>
<p><img src="http://blog.andrei.rinea.ro/wp-content/uploads/2013/04/samsung-ativ-s-rogers-hands-on-1355498536.jpg" alt="" title="samsung-ativ-s-rogers-hands-on-1355498536" width="426" height="411" class="alignnone size-full wp-image-312" /><br />
Image source : <a href="http://www.engadget.com/">Engadget</a></p>
<p><span id="more-306"></span><br />
Windows development is my main job plus I&#8217;ve heard that the apps ecosystem in the Windows Phone marketplace is quite poor. Therefore I thought to myself : &#8216;maybe I could also write an app for it too!&#8217;. Having already tried development on Android and being quite <strike>outraged</strike> surprised by its <a href="http://blog.andrei.rinea.ro/2013/01/30/some-more-android-development-peculiarities/">quirks</a>.</p>
<p>I bit the bullet and bought the <a href="http://profitshare.emag.ro/click.php?ad_client=e7a951e157930aa7e618b20498c0ef75&#038;add_id=287859&#038;redirect=telefon-mobil-samsung-ativ-s-i8750-silver-sami8750as%2Fpd%2FE35XNBBBM%2F">ATIV S</a><img src="http://profitshare.emag.ro/link_track.php?ad_client=e7a951e157930aa7e618b20498c0ef75&#038;add_id=287859" alt="" border="0" width="1" height="1" style="border:none !important; margin:0px !important;" /> from eMAG (a local retailer).</p>
<p>The first thing that surprised me was the curiosity of the shipping consultant (the guy that brings the product&#8217;s box, unboxes it and tests it in front of you). He was quite curious and said he&#8217;s never seen a Windows phone before.</p>
<p>Nice display, nice case and so on. Tried to insert the SIM card at home from the old phone but, to my shame, I did not pay attention to the fact that I needed a microSIM not a &#8216;standard&#8217; SIM. So I had to wait till the next day to get to Vodacrap (Vodafone) to get it replaced.</p>
<p>I also found out that the contacts that Android told me that were saved on the Google Account were not. In fact I could not even access them via web. I simply had to manually move once again contacts. Thanks again Google, thank you to Linux (Android, whatever, same <strike>sh</strike>thing).</p>
<p>The phone boots fast (20-30 sec compared to 2min30..3min of Galaxy S) and whatever you do <strong>it will not lag AT ALL no matter what</strong>. Combine with the fast and fluid animations this does indeed make up a very nice user experience.<br />
The real nice thing is, however, the battery. A 2300 mAH battery combined with the battery saver mode will allow me to talk, text, browse websites, check in on FourSquare, etc etc and recharge it every three &#8230; three and a half days.</p>
<p>So far I didn&#8217;t had to use a kind of app and not find something in the marketplace. There are even Google Maps. Sure, Instagram is a missing thing for some but not for me. And even for that there is something in development as far as I&#8217;ve heard.</p>
<p><img src="http://blog.andrei.rinea.ro/wp-content/uploads/2013/04/Samsung-ATIV-S.png" alt="" title="Samsung-ATIV-S" width="550" height="342" class="alignnone size-full wp-image-315" /></p>
<p>In another case, having a pretty quiet week and on average one phonecall per day I managed to go well beyond 5 days between recharges. I haven&#8217;t seen another smartphone reach these levels. Well at least not without <a href="http://www.mugen-power-batteries.com/">Mugen Power batteries</a>.</p>
<p>&#8216;Bling&#8217; features include NFC (who has / will use this anyway?), Bluetooth 3.0 and a microSD card slot (had one on the Galaxy S but never had the need to use it..).</p>
<p>The only things that I would consider lacking but by no means a &#8216;deal-breaker&#8217; would be :</p>
<ul>
<li>A larger than 5 inch screen</li>
<li>Easy to find leather cases (I found only one but not in the same city, I had to have it shipped)</li>
<li>4G / LTE connectivity</li>
</ul>
<p>The camera is just as good as a phone camera can be, IMHO and at least it does have a LED &#8216;flash&#8217; unlike Galaxy S. Not as good as Lumia 920&#8242;s of course but good enough to take some easy photos in the sunshine..</p>
<p>Now I will give Windows Phone 8 development a chance and see how this goes..</p>
<img src="http://feeds.feedburner.com/~r/Andrei-Rinea/~4/JZE9Li4cAUY" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.andrei.rinea.ro/2013/04/17/windows-phone-8-samsung-ativ-s/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		<feedburner:origLink>http://blog.andrei.rinea.ro/2013/04/17/windows-phone-8-samsung-ativ-s/?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=windows-phone-8-samsung-ativ-s</feedburner:origLink></item>
		<item>
		<title>Windows Explorer contextual menu gotcha</title>
		<link>http://feedproxy.google.com/~r/Andrei-Rinea/~3/sCslLrZ4QK4/</link>
		<comments>http://blog.andrei.rinea.ro/2013/03/08/windows-explorer-contextual-menu-gotcha/#comments</comments>
		<pubDate>Fri, 08 Mar 2013 11:22:21 +0000</pubDate>
		<dc:creator>Andrei Rinea</dc:creator>
				<category><![CDATA[TIps & tricks]]></category>
		<category><![CDATA[command prompt]]></category>
		<category><![CDATA[path]]></category>
		<category><![CDATA[tips]]></category>
		<category><![CDATA[windows explorer]]></category>

		<guid isPermaLink="false">http://blog.andrei.rinea.ro/?p=300</guid>
		<description><![CDATA[Recently I had to extract the public key from a signed .NET assembly and I needed to run the sn.exe tool in order to obtain it. That required opening a command prompt and then setting the current directory to the &#8230;<p class="read-more"><a href="http://blog.andrei.rinea.ro/2013/03/08/windows-explorer-contextual-menu-gotcha/">Read more &#187;</a></p>]]></description>
			<content:encoded><![CDATA[<div class="google_plusone_widget"><g:plusone 
      count="true" href="http://blog.andrei.rinea.ro/2013/03/08/windows-explorer-contextual-menu-gotcha/" size="tall"></g:plusone></div><p>Recently I had to extract the public key from a signed .NET assembly and I needed to run the sn.exe tool in order to obtain it. That required opening a command prompt and then setting the current directory to the one in which the assembly resided.</p>
<p>Typically I did :</p>
<ol>
<li>Win+R (Run)</li>
<li>cmd</li>
<li>Enter</li>
<li>F: [ENTER] (or whatever the drive was)</li>
<li>CD and either type the directory (using the TAB autocomplete or not) or copy the folder path and pasting it into the command prompt [ENTER]</li>
</ol>
<p>Then I thought how can I simplify this little tedious task, which I sometimes do many times a day. After looking for Microsoft PowerToys which is no longer available I found out a little gem hidden in Windows Explorer. This is what my contextual menu looks like normally :</p>
<p><img src="http://blog.andrei.rinea.ro/wp-content/uploads/2013/03/contextmenu1.png" alt="" title="contextmenu1" width="232" height="332" class="alignnone size-full wp-image-302" /></p>
<p>But just pressing (and keeping pressed) SHIFT before the right-click will give you this :</p>
<p><a href="http://blog.andrei.rinea.ro/wp-content/uploads/2013/03/contextmenu2.png"><img src="http://blog.andrei.rinea.ro/wp-content/uploads/2013/03/contextmenu2.png" alt="" title="contextmenu2" width="262" height="352" class="alignnone size-full wp-image-301" /></a></p>
<p>Selecting this command will do the opening of the command prompt and setting the drive and path in one click.</p>
<p>Of course, the next thing is to add the path to SN.EXE in the Environment Variable PATH in order to be able to execute it &#8220;anywhere&#8221;.</p>
<p>I hope this helps at least some of us <img src='http://blog.andrei.rinea.ro/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<img src="http://feeds.feedburner.com/~r/Andrei-Rinea/~4/sCslLrZ4QK4" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.andrei.rinea.ro/2013/03/08/windows-explorer-contextual-menu-gotcha/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		<feedburner:origLink>http://blog.andrei.rinea.ro/2013/03/08/windows-explorer-contextual-menu-gotcha/?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=windows-explorer-contextual-menu-gotcha</feedburner:origLink></item>
		<item>
		<title>Some more Android development peculiarities</title>
		<link>http://feedproxy.google.com/~r/Andrei-Rinea/~3/wRCE8sObkr4/</link>
		<comments>http://blog.andrei.rinea.ro/2013/01/30/some-more-android-development-peculiarities/#comments</comments>
		<pubDate>Tue, 29 Jan 2013 23:22:18 +0000</pubDate>
		<dc:creator>Andrei Rinea</dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Activity]]></category>
		<category><![CDATA[debug]]></category>
		<category><![CDATA[Eclipse]]></category>
		<category><![CDATA[error]]></category>
		<category><![CDATA[import]]></category>
		<category><![CDATA[Log]]></category>
		<category><![CDATA[Monodroid]]></category>
		<category><![CDATA[namespace]]></category>
		<category><![CDATA[package]]></category>
		<category><![CDATA[super]]></category>
		<category><![CDATA[using]]></category>
		<category><![CDATA[Visual-Studio]]></category>
		<category><![CDATA[wtf]]></category>
		<category><![CDATA[Xamarin]]></category>

		<guid isPermaLink="false">http://blog.andrei.rinea.ro/?p=294</guid>
		<description><![CDATA[There is a baked in logging class called, intuitively, Log. For some strange reason the authors chose to name its methods, most of them, with one letter. That is : Until you hit This one&#8217;s funny and I appreciate their &#8230;<p class="read-more"><a href="http://blog.andrei.rinea.ro/2013/01/30/some-more-android-development-peculiarities/">Read more &#187;</a></p>]]></description>
			<content:encoded><![CDATA[<div class="google_plusone_widget"><g:plusone 
      count="true" href="http://blog.andrei.rinea.ro/2013/01/30/some-more-android-development-peculiarities/" size="tall"></g:plusone></div><p>There is a baked in logging class called, intuitively, Log. For some strange reason the authors chose to name its methods, most of them, with one letter. That is :</p>
<pre class="brush: java; title: ; notranslate">
Log.d(..); // debug level
Log.e(..); // error level
...
</pre>
<p>Until you hit </p>
<pre class="brush: java; title: ; notranslate">
...
Log.wtf(..);
...
</pre>
<p>This one&#8217;s funny and I appreciate their sense of humor as it goes up to renaming WTF to &#8220;What a Terrible Failure&#8221;. Like we&#8217;re so dumb that we can&#8217;t figure what they really had in mind <img src='http://blog.andrei.rinea.ro/wp-includes/images/smilies/icon_razz.gif' alt=':P' class='wp-smiley' /> </p>
<p>Another peculiarity is that in an activity (this akin to a Page / Form / whatever) you have some methods that you can/should override such as onCreate(). Everywhere is stated that the first thing you should write in the overriding method is a call to the super (that is base) class&#8217;s method. If it is really all that important and vital why didn&#8217;t the class designers go with a template method in first place?</p>
<p>That is a design pattern, that in this case, would go like so :</p>
<pre class="brush: java; title: ; notranslate">
public class Activity {

    // ...

    private void onCreateInternal(Bundle savedInstanceState) {
        //vital stuff
        onCreate(savedInstanceState);
    }

    protected void onCreate(Bundle savedInstanceState) {
    }

    // ...

}
</pre>
<p>Take note of another difference between C# and Java : the methods and classes are virtual/unsealed by default. So the onCreate method in my example above is overrideable in any subclass. Also in Java terminology the base class is called the superclass.</p>
<p>Other differences of terminology include :</p>
<ul>
<li>A namespace is called a package</li>
<li>By default an import (which is akin to a using directive) imports by default just the specified type and not the whole package (namespace). You need to use a wildcard to import the whole package</li>
<li>The closest thing to an assembly is called a JAR (Java ARchive).</li>
<li>Eclipse by default is set to autocompile. That is whenever you hit CTRL-S (Save) to a Java file the project is (re)compiled. This sounds terrible but it isn&#8217;t! You can&#8217;t even notice. Either there is an incremental compilation either the performance of the compiler is incredible.</li>
<li>Unlike Visual Studio, Eclipse presents the import block collapsed by default. I wish I had this in VS&#8230; Just like a mobile app fan would say &#8220;there&#8217;s an app for that&#8221;, I bet for VS &#8220;there&#8217;s a plugin for that&#8221; <img src='http://blog.andrei.rinea.ro/wp-includes/images/smilies/icon_razz.gif' alt=':P' class='wp-smiley' /> </li>
<li>In Java if you want to call the super (base) class&#8217;s constructor from the current class&#8217;s constructor you will write &#8220;super(&#8230;);&#8221; in the constructor&#8217;s body. When I first saw this I said to myself <a href="http://borntofish.blogspot.ro/2007/05/learn-chinese-in-5-minutes.html">Fu-Kin-Su-Pa</a> (er&#8230; &#8220;great&#8221;, that is). &#8220;Now I have the liberty to call the base/super constructor from wherever inside the constructor I want&#8221;. Well, no. It&#8217;s either the first line or it isn&#8217;t.</li>
</ul>
<p>Well, I&#8217;ll rant more as I go learning Android development.</p>
<p>My goal is to get to know enough so I can do it in Xamarin via C# but first I must understand the underlying things in order to go a level of abstraction above.</p>
<p>In the next episode(s) : I am indebted with a follow-up from my <a href="http://blog.andrei.rinea.ro/2012/11/07/efficiently-serving-binary-content-from-sql-server-in-asp-net-mvc-local-user-group-talk/">presentation</a> held at RONUA last year.</p>
<img src="http://feeds.feedburner.com/~r/Andrei-Rinea/~4/wRCE8sObkr4" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.andrei.rinea.ro/2013/01/30/some-more-android-development-peculiarities/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		<feedburner:origLink>http://blog.andrei.rinea.ro/2013/01/30/some-more-android-development-peculiarities/?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=some-more-android-development-peculiarities</feedburner:origLink></item>
		<item>
		<title>Java / C# differences part 1 of n</title>
		<link>http://feedproxy.google.com/~r/Andrei-Rinea/~3/_w0ZiJvObDA/</link>
		<comments>http://blog.andrei.rinea.ro/2013/01/29/java-vs-csharp-differences-part-1-of/#comments</comments>
		<pubDate>Tue, 29 Jan 2013 17:56:11 +0000</pubDate>
		<dc:creator>Andrei Rinea</dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[access-modifier]]></category>
		<category><![CDATA[default]]></category>
		<category><![CDATA[Eclipse]]></category>
		<category><![CDATA[overload]]></category>
		<category><![CDATA[override]]></category>
		<category><![CDATA[properties]]></category>
		<category><![CDATA[Silverlight]]></category>
		<category><![CDATA[wpf]]></category>

		<guid isPermaLink="false">http://blog.andrei.rinea.ro/?p=286</guid>
		<description><![CDATA[Recently I&#8217;ve been toying around with Android development (since I own an Android &#8220;smart&#8221; phone for over 2 years now) and mobile development is all the rage now. Moreover, I&#8217;ve been trying to do new things lately since even the &#8230;<p class="read-more"><a href="http://blog.andrei.rinea.ro/2013/01/29/java-vs-csharp-differences-part-1-of/">Read more &#187;</a></p>]]></description>
			<content:encoded><![CDATA[<div class="google_plusone_widget"><g:plusone 
      count="true" href="http://blog.andrei.rinea.ro/2013/01/29/java-vs-csharp-differences-part-1-of/" size="tall"></g:plusone></div><p>Recently I&#8217;ve been toying around with Android development (since I own an Android &#8220;smart&#8221; phone for over 2 years now) and mobile development is all the rage now. Moreover, I&#8217;ve been trying to do new things lately since even the pragmatic programmer guide advises us to learn a new language each year (kind of aggressive if you ask me).</p>
<p>Anyway I will try to show what a C# developer (almost 8 years now) discovers by doing Java development on Eclipse for Android.</p>
<p>For today : </p>
<p><strong>leaving a member of a class without an access modifier defaults to internal instead of private :</strong></p>
<pre class="brush: csharp; title: ; notranslate">
// C#
void Test() // private method
{
}
</pre>
<pre class="brush: java; title: ; notranslate">
// Java
void test() { // internal method
}
</pre>
<p>Overriding a method does not require any kind of keyword or special ceremony. You can use the @Override annotation but this is optional. You can get burned this way easily.</p>
<pre class="brush: csharp; title: ; notranslate">
// C#
public override bool Equals(object other)
{
    return _id == other._id;
}
</pre>
<pre class="brush: java; title: ; notranslate">
// Java; WRONG! DO NOT USE
public bool equals(Person other) {
    return this.id == other.id;
}

//Correct
public bool equals(Object other) {
    return this.id == other.id;
}
</pre>
<p><strong>Overriding requires that you use the same method signature (that is, the same return type, the same parameter types and order). If you accidentally mistake the signature (Person instead of Object) you will overload instead of overriding with unknown effects.</strong></p>
<p><span id="more-286"></span></p>
<p>In other &#8220;news&#8221;, Android development has a lot of similarities with WPF :</p>
<ul>
<li>You have activities (similar to pages in Silverlight/WPF).</li>
<li>These are XML-defined.</li>
<li>There are a few base-layout controls (viewobjects) like LinearLayout (StackPanel), GridLayout and so on.</li>
<li>You must not access UI elements from other threads than the main / UI thread.</li>
<li>The layout viewobjects have similar properties to the layout controls in WPF/Silverlight : width/height which can be specified absolutely or relatively and so on.</li>
</ul>
<p>The lack of properties baked in the language is annoying regardless of the features of Eclipse (generate getters and setters). The auto-complete feature is far from Visual Studio and there is no &#8220;ReSharper&#8221; to easily import missing types. Yes there is F2 but still..</p>
<p>The lack of delegates makes multithreading a pain (you know where this pain is located) and so is the wiring of the handlers for clicking buttons and all.</p>
<p>Oh well, I&#8217;ll carry on and be back with new opinions as I go.</p>
<img src="http://feeds.feedburner.com/~r/Andrei-Rinea/~4/_w0ZiJvObDA" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.andrei.rinea.ro/2013/01/29/java-vs-csharp-differences-part-1-of/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://blog.andrei.rinea.ro/2013/01/29/java-vs-csharp-differences-part-1-of/?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=java-vs-csharp-differences-part-1-of</feedburner:origLink></item>
		<item>
		<title>Efficiently serving binary content from SQL Server in ASP.NET MVC – local user group talk</title>
		<link>http://feedproxy.google.com/~r/Andrei-Rinea/~3/T73XCGhhjtY/</link>
		<comments>http://blog.andrei.rinea.ro/2012/11/07/efficiently-serving-binary-content-from-sql-server-in-asp-net-mvc-local-user-group-talk/#comments</comments>
		<pubDate>Wed, 07 Nov 2012 10:22:51 +0000</pubDate>
		<dc:creator>Andrei Rinea</dc:creator>
				<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[Presentations]]></category>
		<category><![CDATA[SQL Server]]></category>
		<category><![CDATA[ASP.NET MVC 4]]></category>
		<category><![CDATA[binary]]></category>
		<category><![CDATA[filestream]]></category>
		<category><![CDATA[FileTables]]></category>
		<category><![CDATA[RONUA]]></category>
		<category><![CDATA[SQL Server 2012]]></category>
		<category><![CDATA[streaming]]></category>
		<category><![CDATA[TeamNet]]></category>

		<guid isPermaLink="false">http://blog.andrei.rinea.ro/?p=271</guid>
		<description><![CDATA[This will be a local user group talk that I&#8217;ll be having, in Bucharest on Tuesday 13th of November. Storing large binary objects (usually image files) in the RDBMS has been a blessing but for some is unconceivable. We will &#8230;<p class="read-more"><a href="http://blog.andrei.rinea.ro/2012/11/07/efficiently-serving-binary-content-from-sql-server-in-asp-net-mvc-local-user-group-talk/">Read more &#187;</a></p>]]></description>
			<content:encoded><![CDATA[<div class="google_plusone_widget"><g:plusone 
      count="true" href="http://blog.andrei.rinea.ro/2012/11/07/efficiently-serving-binary-content-from-sql-server-in-asp-net-mvc-local-user-group-talk/" size="tall"></g:plusone></div><p>This will be a local user group talk that I&#8217;ll be having, in Bucharest on Tuesday 13th of November.</p>
<p>Storing large binary objects (usually image files) in the RDBMS has been a blessing but for some is unconceivable. We will explore different ways to do this, from worse to best and we will take advantage of a new feature introduced by SQL Server 2012.</p>
<p>The location is TeamNet Int&#8217;l HQ &#8211; Sema Parc, Splaiul Independenţei nr. 319, clădirea RiverView, etaj 8<br />
Except an ID there is nothing else that you need to bring in order to participate to the event.<br />
Further <a href="http://goo.gl/maps/ofwel">geographical details</a>. </p>
<p>The most popular way to get there is by taking the subway as there is a station right near the building.</p>
<p>The <a href="http://ronua.ro/CS/groups/ronua-bucuresti/default.aspx">official announcement</a> can be found on RONUA&#8217;s site.</p>
<p>See you there!</p>
<p>&#8212;&#8212;&#8211;</p>
<p>Later edit : It&#8217;s been great! Not too many people but keen to learn new stuff. Here&#8217;s two pictures from the talk. Notice a new generation of programmers forming <img src='http://blog.andrei.rinea.ro/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p><a href="http://blog.andrei.rinea.ro/wp-content/uploads/2012/11/RONUA1.jpg"><img src="http://blog.andrei.rinea.ro/wp-content/uploads/2012/11/RONUA1-300x225.jpg" alt="" title="SQL Server 2012 / ASP.NET MVC 4" width="300" height="225" class="alignnone size-medium wp-image-276" /></a></p>
<p><a href="http://blog.andrei.rinea.ro/wp-content/uploads/2012/11/RONUA2.jpg"><img src="http://blog.andrei.rinea.ro/wp-content/uploads/2012/11/RONUA2-300x225.jpg" alt="" title="SQL Server 2012 / ASP.NET MVC 4" width="300" height="225" class="alignnone size-medium wp-image-277" /></a></p>
<img src="http://feeds.feedburner.com/~r/Andrei-Rinea/~4/T73XCGhhjtY" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.andrei.rinea.ro/2012/11/07/efficiently-serving-binary-content-from-sql-server-in-asp-net-mvc-local-user-group-talk/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		<feedburner:origLink>http://blog.andrei.rinea.ro/2012/11/07/efficiently-serving-binary-content-from-sql-server-in-asp-net-mvc-local-user-group-talk/?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=efficiently-serving-binary-content-from-sql-server-in-asp-net-mvc-local-user-group-talk</feedburner:origLink></item>
		<item>
		<title>Type check and inheritance – and a nice ReSharper tip</title>
		<link>http://feedproxy.google.com/~r/Andrei-Rinea/~3/Q49DZdwrt5o/</link>
		<comments>http://blog.andrei.rinea.ro/2012/10/25/type-check-and-inheritance-and-a-nice-resharper-ti/#comments</comments>
		<pubDate>Thu, 25 Oct 2012 10:55:43 +0000</pubDate>
		<dc:creator>Andrei Rinea</dc:creator>
				<category><![CDATA[Basics]]></category>
		<category><![CDATA[CodeProject]]></category>
		<category><![CDATA[Recruitment]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[OOP]]></category>
		<category><![CDATA[ReSharper]]></category>
		<category><![CDATA[System.Type]]></category>
		<category><![CDATA[typeof]]></category>

		<guid isPermaLink="false">http://blog.andrei.rinea.ro/?p=261</guid>
		<description><![CDATA[Let&#8217;s suppose you have three classes in a simple hierarchy : Now suppose you receive an instance of one of these classes (you don&#8217;t know the exact type to which this instance belongs). How can you determine programatically if the &#8230;<p class="read-more"><a href="http://blog.andrei.rinea.ro/2012/10/25/type-check-and-inheritance-and-a-nice-resharper-ti/">Read more &#187;</a></p>]]></description>
			<content:encoded><![CDATA[<div class="google_plusone_widget"><g:plusone 
      count="true" href="http://blog.andrei.rinea.ro/2012/10/25/type-check-and-inheritance-and-a-nice-resharper-ti/" size="tall"></g:plusone></div><p>Let&#8217;s suppose you have three classes in a simple hierarchy :</p>
<pre class="brush: csharp; title: ; notranslate">
public class A
{
}

public class B : A
{
}

public class C : A
{
}
</pre>
<p>Now suppose you receive an instance of one of these classes (you don&#8217;t know the exact type to which this instance belongs). How can you determine programatically if the instance is of a type inheriting from A or it is of type A exactly?</p>
<p>Normally I would do the following :</p>
<pre class="brush: csharp; title: ; notranslate">
var instance = ObtainInstanceFromSomeWhere(); // this method will not return null
var instanceIsExactlyOfTypeA = typeof(A) == instance.GetType();
var instanceIsOfTypeAOrAnInheritingType = typeof(A).IsAssignableFrom(instance.GetType());
</pre>
<p>All these work and are nice and dandy. However <a href="http://www.jetbrains.com/resharper/">ReSharper</a> showed me a nicer alternative to the last statement :</p>
<pre class="brush: csharp; title: ; notranslate">
var instanceIsOfTypeAOrAnInheritingType = typeof(A).IsInstanceOfType(instance);
</pre>
<p>Now, pro&#8217;lly, many of you knew about this method but I didn&#8217;t! <img src='http://blog.andrei.rinea.ro/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /><br />
Hopefully it will help someone..</p>
<img src="http://feeds.feedburner.com/~r/Andrei-Rinea/~4/Q49DZdwrt5o" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.andrei.rinea.ro/2012/10/25/type-check-and-inheritance-and-a-nice-resharper-ti/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		<feedburner:origLink>http://blog.andrei.rinea.ro/2012/10/25/type-check-and-inheritance-and-a-nice-resharper-ti/?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=type-check-and-inheritance-and-a-nice-resharper-ti</feedburner:origLink></item>
		<item>
		<title>CallMemberName – an easier way to do INotifyPropertyChanged AND MORE</title>
		<link>http://feedproxy.google.com/~r/Andrei-Rinea/~3/yAyf7_dzX4E/</link>
		<comments>http://blog.andrei.rinea.ro/2012/08/24/callmembername-an-easier-way-to-do-notifypropertychanged-and-mor/#comments</comments>
		<pubDate>Fri, 24 Aug 2012 09:56:29 +0000</pubDate>
		<dc:creator>Andrei Rinea</dc:creator>
				<category><![CDATA[CodeProject]]></category>
		<category><![CDATA[SQL Server]]></category>
		<category><![CDATA[WPF]]></category>
		<category><![CDATA[.NET 4.5]]></category>
		<category><![CDATA[CallMemberInfo]]></category>
		<category><![CDATA[INotifyPropertyChanged]]></category>
		<category><![CDATA[mvvm]]></category>
		<category><![CDATA[stored-procedures]]></category>
		<category><![CDATA[type-safety]]></category>
		<category><![CDATA[ViewModel]]></category>
		<category><![CDATA[wpf]]></category>

		<guid isPermaLink="false">http://blog.andrei.rinea.ro/?p=251</guid>
		<description><![CDATA[In WPF, when applying the MVVM (an arhitectural pattern) we often need to implement the INotifyPropertyChanged on certain classes (ViewModel classes), which means something like this : In case you&#8217;re wondering why I copied the PropertyChanged value to the local &#8230;<p class="read-more"><a href="http://blog.andrei.rinea.ro/2012/08/24/callmembername-an-easier-way-to-do-notifypropertychanged-and-mor/">Read more &#187;</a></p>]]></description>
			<content:encoded><![CDATA[<div class="google_plusone_widget"><g:plusone 
      count="true" href="http://blog.andrei.rinea.ro/2012/08/24/callmembername-an-easier-way-to-do-notifypropertychanged-and-mor/" size="tall"></g:plusone></div><p>In WPF, when applying the MVVM (an arhitectural pattern) we often need to implement the INotifyPropertyChanged on certain classes (ViewModel classes), which means something like this :</p>
<pre class="brush: csharp; title: ; notranslate">

public class PersonViewModel : INotifyPropertyChanged
{
    private string _name;
    public string Name
    {
        get { return _name; }
        set
        {
            if (_name == value) return;
            _name = value;
            NotifyPropertyChanged(&quot;Name&quot;);
        }
    }

    private void NotifyPropertyChanged(string propertyName)
    {
        var evt = PropertyChanged;
        if (evt != null) evt(this, new PropertyChangedEventArgs(propertyName));
    }

    public event PropertyChangedEventHandler PropertyChanged;
}
</pre>
<p>In case you&#8217;re wondering why I copied the PropertyChanged value to the local variable called &#8220;evt&#8221; and then tested it for null is that you can have race conditions, in general, triggering events (i.e.: you test the attribute value, it is not null and before you trigger it some other thread sets it to null and bang, NullReferenceException when you trigger it). More details on this <a href="http://www.codeproject.com/Articles/61878/How-to-Safely-Trigger-Events-the-Easy-Way">CodeProject</a>.</p>
<p>The next step is to pull the NotifyPropertyChanged method and PropertyChanged event into a base class (let&#8217;s call it ViewModelBase) and you&#8217;ve eliminated redundancy between several ViewModel classes.</p>
<p>The not-so-nice part is having the call to NotifyPropertyChanged <a href="http://blog.lexspoon.org/2010/05/stringly-typed-code.html">stringly-typed</a>. That means that if later you rename (via Visual Studio or ReSharper) the Name property to &#8220;FullName&#8221; the call will still pass &#8220;Name&#8221; as the argument.</p>
<p><a href="http://mfelicio.com/2010/01/10/safe-usage-of-inotifypropertychanged-in-mvvm-scenarios/">Some blog posts</a> around the web show how you can use a Func to make it type-safe (refactor safe etc).</p>
<p>More or less they&#8217;re doing the same thing :</p>
<pre class="brush: csharp; title: ; notranslate">

public abstract class ViewModelBase : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    protected void NotifyPropertyChanged(Expression&lt;Func&lt;object&gt;&gt; propertyAccessor)
    {
        var evt = PropertyChanged;
        if (evt == null) return;
        var propertyName = propertyAccessor.GetName();
        evt(this, new PropertyChangedEventArgs(propertyName));
    }
}

public static class Utils
{
    public static string GetName(this LambdaExpression expression)
    {
        MemberExpression memberExpression;
        if (expression.Body is UnaryExpression)
        {
            var unaryExpression = (UnaryExpression)expression.Body;
            memberExpression = (MemberExpression)unaryExpression.Operand;
        }
        else if (expression.Body is MemberExpression)
        {
            memberExpression = (MemberExpression)expression.Body;
        }
        else
        {
            return null;
        }
        return memberExpression.Member.Name;
    }
}
</pre>
<p>This is definitely nicer, not-redundant and type-safe. It does have the drawback of having some runtime performance penalty associated with the reflection of the expression. You could cache the property name string in a private field but then you&#8217;d have to write more code in the ViewModel classes which would&#8230; suck. In practice this performance penalty is negligible so you can just ignore this.</p>
<p>Then came <a href="http://msdn.microsoft.com/en-us/library/ms171868.aspx">.NET 4.5</a> and among other improvements a new mechanism has been introduced : <a href="http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.callermembernameattribute.aspx">CallMemberName</a>.</p>
<p>Historically some folks tried to get programatically the name of the caller method by inspecting the StackTrace (for example using <a href="http://msdn.microsoft.com/en-us/library/system.environment.stacktrace.aspx">System.Environment.StackTrace</a>) but this is prone to errors since in Release mode the compiler could eliminate some methods by <a href="http://en.wikipedia.org/wiki/Inline_expansion">inlining</a> them and you&#8217;ll be screwed. Plus the penalty would be higher than reflecting an expression.</p>
<p>The new mechanism in .NET 4.5 is type-safe, has no runtime performance penalty and it&#8217;s more elegant. Here&#8217;s how you can use it :</p>
<pre class="brush: csharp; title: ; notranslate">
public abstract class ViewModelBase : INotifyPropertyChanged
{
    protected void NotifyPropertyChanged([CallerMemberName] string propertyName = null)
    {
        var deleg = PropertyChanged;
        if (deleg != null)
        {
            deleg(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
}

public class PersonViewModel : ViewModelBase
{
    private string _name;
    public string Name
    {
        get { return _name; }
        set
        {
            if (_name == value) return;
            _name = value;
            NotifyPropertyChanged();
        }
    }
}
</pre>
<p>I&#8217;ve recently built a very small GuidGen utility (which as the name implies generates GUIDs, copies it in the Windows Clipboard and stores a history of past generated GUIDs). You can browse <a href="http://guidgen.codeplex.com/SourceControl/changeset/view/18750#252470">some of the code</a> and check out <a href="http://guidgen.codeplex.com">the project</a>.</p>
<p>Much nicer, isn&#8217;t it?</p>
<p>Funny thing, this new mechanism can be used for non-UI tasks. For example if you have a project that uses and RDBMS and you use stored procedures. Let&#8217;s say you have one method in a repository class for each stored procedure, and even more, the method&#8217;s name matches the stored procedure&#8217;s name :</p>
<pre class="brush: csharp; title: ; notranslate">

public VerificationResult VerifyUser(VerificationData verificationData)
{
    if (EmailValidator.IsEmailInvalid(verificationData.EmailAddress)) throw new FormatException(&quot;emailAddress&quot;);

    var result = CreateNewCommand(&quot;VerifyUser&quot;).GetEnumResult&lt;VerificationFailReason&gt;(
        CreateEmailAddressParameter(verificationData.EmailAddress),
        CreateUniqueIdentifierParam(&quot;@VerificationCode&quot;, verificationData.VerificationCode));

    return new VerificationResult(result);
}
</pre>
<p>Observe on line 5 how the call to CreateNewCommand passes a string which matches the current method&#8217;s name. This can also be simplified (and become refactor-safe) using the new CallMemberName mechanism.</p>
<p>So you can&#8217;t really say that CallMemberName is useful only for UI tasks <img src='http://blog.andrei.rinea.ro/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<img src="http://feeds.feedburner.com/~r/Andrei-Rinea/~4/yAyf7_dzX4E" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.andrei.rinea.ro/2012/08/24/callmembername-an-easier-way-to-do-notifypropertychanged-and-mor/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		<feedburner:origLink>http://blog.andrei.rinea.ro/2012/08/24/callmembername-an-easier-way-to-do-notifypropertychanged-and-mor/?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=callmembername-an-easier-way-to-do-notifypropertychanged-and-mor</feedburner:origLink></item>
		<item>
		<title>OUTPUT clause in UPDATE statements</title>
		<link>http://feedproxy.google.com/~r/Andrei-Rinea/~3/lQUgvegRuac/</link>
		<comments>http://blog.andrei.rinea.ro/2012/08/19/output-clause-in-update-statements/#comments</comments>
		<pubDate>Sun, 19 Aug 2012 00:14:07 +0000</pubDate>
		<dc:creator>Andrei Rinea</dc:creator>
				<category><![CDATA[CodeProject]]></category>
		<category><![CDATA[SQL Server]]></category>
		<category><![CDATA[concurrency]]></category>
		<category><![CDATA[OUTPUT]]></category>
		<category><![CDATA[race-condition]]></category>
		<category><![CDATA[T-SQL]]></category>
		<category><![CDATA[UPDATE]]></category>

		<guid isPermaLink="false">http://blog.andrei.rinea.ro/?p=243</guid>
		<description><![CDATA[Sometimes you need to update data in a table and then update data in another table but based on a filter condition found from the first table. Specifically have you had to do this in the past? This is not &#8230;<p class="read-more"><a href="http://blog.andrei.rinea.ro/2012/08/19/output-clause-in-update-statements/">Read more &#187;</a></p>]]></description>
			<content:encoded><![CDATA[<div class="google_plusone_widget"><g:plusone 
      count="true" href="http://blog.andrei.rinea.ro/2012/08/19/output-clause-in-update-statements/" size="tall"></g:plusone></div><p>Sometimes you need to update data in a table and then update data in another table but based on a filter condition found from the first table. Specifically have you had to do this in the past?</p>
<pre class="brush: sql; title: ; notranslate">

-- ...

UPDATE Users
SET    Verified     = 1
FROM   Logins
WHERE  EmailAddress = @EmailAddress

DECLARE @UserId INT;

SELECT TOP 1
       @UserId = UserId
FROM   Logins
WHERE  EmailAddress = @EmailAddress

UPDATE  Users
SET     State = 2 -- Verified
WHERE   Id = @UserId

-- ...
</pre>
<p>This is not only inefficient (from an execution plan perspective) but also prone to race conditions and requires more code. The simpler and safer alternative is to use the OUTPUT clause of the UPDATE.</p>
<p>Here&#8217;s how : </p>
<pre class="brush: sql; title: ; notranslate">DECLARE @UserIdTable TABLE ( Id INT );

UPDATE Users
SET    Verified     = 1
OUTPUT UserId
INTO   @UserIdTable
FROM   Logins
WHERE  EmailAddress = @EmailAddress

DECLARE @UserId INT = SELECT TOP 1 Id FROM @UserIdTable;

UPDATE  Users
SET     State = 2 -- Verified
WHERE   Id = @UserId</pre>
<p>In the above code sample I take advantage of the new declare and initialize syntax introduced in SQL Server 2008. The <a href="http://msdn.microsoft.com/en-us/library/ms177564.aspx">OUTPUT clause</a> has been introduced in SQL Server 2005 so nothing here is really news.</p>
<p>Another simplification that I hoped it was possible was to avoid the declaration of the local table variable and just push the OUTPUT into the local variable (@UserId) but <a href="http://dba.stackexchange.com/q/22684/3046">it seems you can&#8217;t</a>.</p>
<p>I found out about the OUTPUT clause recently from <a href="http://rusanu.com/2010/03/26/using-tables-as-queues/">Remus Rusanu&#8217;s blog post</a> about implementing queues with tables. These have, usually, high concurrency and any race condition that might occur will occur. OUTPUT is usually the best way to solve it.</p>
<img src="http://feeds.feedburner.com/~r/Andrei-Rinea/~4/lQUgvegRuac" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.andrei.rinea.ro/2012/08/19/output-clause-in-update-statements/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		<feedburner:origLink>http://blog.andrei.rinea.ro/2012/08/19/output-clause-in-update-statements/?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=output-clause-in-update-statements</feedburner:origLink></item>
		<item>
		<title>Prefix cast or as-cast?</title>
		<link>http://feedproxy.google.com/~r/Andrei-Rinea/~3/VX7WF4zyQjs/</link>
		<comments>http://blog.andrei.rinea.ro/2012/08/14/prefix-cast-or-as-cast/#comments</comments>
		<pubDate>Tue, 14 Aug 2012 09:09:49 +0000</pubDate>
		<dc:creator>Andrei Rinea</dc:creator>
				<category><![CDATA[Best practices]]></category>
		<category><![CDATA[CodeProject]]></category>
		<category><![CDATA[as]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[cast]]></category>
		<category><![CDATA[InvalidCastException]]></category>
		<category><![CDATA[NullReferenceException]]></category>
		<category><![CDATA[prefix-cast]]></category>

		<guid isPermaLink="false">http://blog.andrei.rinea.ro/?p=207</guid>
		<description><![CDATA[I read today a nice article, from Kathleen Dollard, called To “as” or not to “as”. This is a pain-point for me on which I stumble often, so I decided to write this little rant. I particularly liked a paragraph &#8230;<p class="read-more"><a href="http://blog.andrei.rinea.ro/2012/08/14/prefix-cast-or-as-cast/">Read more &#187;</a></p>]]></description>
			<content:encoded><![CDATA[<div class="google_plusone_widget"><g:plusone 
      count="true" href="http://blog.andrei.rinea.ro/2012/08/14/prefix-cast-or-as-cast/" size="tall"></g:plusone></div><p>I read today a nice article, from <a href="http://msmvps.com/blogs/kathleen">Kathleen Dollard</a>, called <a href="http://msmvps.com/blogs/kathleen/archive/2012/08/12/to-as-or-not-to-as.aspx">To “as” or not to “as”</a>. This is a pain-point for me on which I stumble often, so I decided to write this little rant.</p>
<p>I particularly liked a paragraph from the above-cited article :</p>
<blockquote><p>One of the things that makes hard bugs hard is when there is a disconnect in time or space between the cause and the symptom. Time is time, space is lines of code, assembly placement, etc. Code can be written to minimize these disconnects. One of the ways to do that is to fail quickly. When application state becomes incorrect, yell about it immediately and rarely continue with the application in an invalid state. A null-reference exception at an unexpected time just makes code more difficult to debug.</p></blockquote>
<p>I couldn&#8217;t express this as good as Kathleen did. Make no mistake I am quite biased in this comparison (direct-cast vs. as-cast). I kind of hate the abuse of the as operator.</p>
<p>Very often people turn to as instead of the direct (prefix) cast because:</p>
<ul>
<li>They fear the InvalidCastException (strange, they don&#8217;t seem to fear the NullReferenceException)</li>
<li>They feel the syntax more fluent, closer to the human language.</li>
</ul>
<p>I would consider the only valid case to use the as-cast is, just like Kathleen states, when a null value result is valid for the rest of the execution of the code. For the rest of the cases it&#8217;s just <strong>wrong</strong>.</p>
<p>This also promotes (doesn&#8217;t necessarily causes but promotes) bad practices like this :</p>
<pre class="brush: csharp; title: ; notranslate">

public static void OnButtonClick(object sender, EventArgs e)
{
    var button = sender as Button;
    if (button == null)
    {
        return;
    }
    if (button.Tag == &amp;quot;somevalue&amp;quot;)
    {
        // do something
    }
    // ...
}
</pre>
<p>In this example the event handler (which could be attached to more than one distinct button) simply forces under the rug a situation which would be abnormal (the sender not being a button) instead of releasing it so the developers could find it easier and debug it. A saner approach is :</p>
<pre class="brush: csharp; title: ; notranslate">

public static void OnButtonClick(object sender, EventArgs e)
{
    var button = (Button)sender;
    if (button.Tag == &amp;quot;somevalue&amp;quot;)
    {
        // do something
    }
    // ...
}
</pre>
<p>This brings me to another advantage of the prefix-cast : it produces <strong>shorter</strong>, clearer code.</p>
<p>In other cases the <strong>as</strong> abuse does more harm, hiding the source of a bug :</p>
<pre class="brush: csharp; title: ; notranslate">

public void ProcessData(Entity entity)
{
    var person = entity as Person;
    UpdatePersonStatistics(person);
    // .. more code
}

public void UpdatePersonStatistics(Person person)
{
    NormalizeData(person);
    // .. more code
}

public void NormalizeData(Person person)
{
    person.Name = person.Name.Substring(0, 50);
    person.Address = person.Address.Substring(0, 100);
    // .. more code
}
</pre>
<p>Of course this is a contrived example full of bad practices but for now let&#8217;s focus on the <strong>as</strong> usage. Suppose the ProcessData method receives an instance of <em>Category</em> by mistake. Since Category inherits Entity the compiler will not complain.</p>
<p>The result is that there will be a NullReferenceException two methods further, in the NormalizeData method. If the cast was done with a prefix cast the error was a little bit easier to spot. This is confusing two-fold :</p>
<ol>
<li>The name of the exception suggests that a null reference was somehow obtained but in fact a real instance of Category was passed, not a null</li>
<li>The error does not originate from the NormalizeData code but from the caller of the ProcessData</li>
</ol>
<p><strong>Summary</strong></p>
<p>Use as only if a null result of the conversion makes sense for the flow of the execution. Otherwise use prefix cast.</p>
<img src="http://feeds.feedburner.com/~r/Andrei-Rinea/~4/VX7WF4zyQjs" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.andrei.rinea.ro/2012/08/14/prefix-cast-or-as-cast/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		<feedburner:origLink>http://blog.andrei.rinea.ro/2012/08/14/prefix-cast-or-as-cast/?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=prefix-cast-or-as-cast</feedburner:origLink></item>
		<item>
		<title>ReSharper hidden features – Generate Delegating Members</title>
		<link>http://feedproxy.google.com/~r/Andrei-Rinea/~3/jOBaubpF__A/</link>
		<comments>http://blog.andrei.rinea.ro/2012/07/30/resharper-hidden-features-generate-delegating-members/#comments</comments>
		<pubDate>Mon, 30 Jul 2012 15:59:36 +0000</pubDate>
		<dc:creator>Andrei Rinea</dc:creator>
				<category><![CDATA[CodeProject]]></category>
		<category><![CDATA[TIps & tricks]]></category>
		<category><![CDATA[Adapter]]></category>
		<category><![CDATA[Decorator]]></category>
		<category><![CDATA[design-patterns]]></category>
		<category><![CDATA[mixin]]></category>
		<category><![CDATA[productivity]]></category>
		<category><![CDATA[ReSharper]]></category>
		<category><![CDATA[Visual-Studio]]></category>

		<guid isPermaLink="false">http://blog.andrei.rinea.ro/?p=197</guid>
		<description><![CDATA[A frequently-used design pattern is the Decorator. This is also known as a mixin (or they might not be the very same thing but certainly they are related). Typically you might need to create a class that implements a certain &#8230;<p class="read-more"><a href="http://blog.andrei.rinea.ro/2012/07/30/resharper-hidden-features-generate-delegating-members/">Read more &#187;</a></p>]]></description>
			<content:encoded><![CDATA[<div class="google_plusone_widget"><g:plusone 
      count="true" href="http://blog.andrei.rinea.ro/2012/07/30/resharper-hidden-features-generate-delegating-members/" size="tall"></g:plusone></div><p>A frequently-used design pattern is the <a href="http://en.wikipedia.org/wiki/Decorator_design_pattern">Decorator</a>. This is also known as a <a href="http://en.wikipedia.org/wiki/Mixin">mixin</a> (or they might not be the very same thing but certainly they are related).</p>
<p>Typically you might need to create a class that implements a certain interface and uses another class that implements that exact interface but you need to provide some additional feature(s). An example would be a class that adds transactional behavior to an existing data-access class (a naive example) :</p>
<pre class="brush: csharp; title: ; notranslate">

public interface IDataAccess
{
    void AddCustomerInvoice(Invoice invoice, User user);
}

public class DataAccess : IDataAccess
{
    public void AddCustomerInvoice(Invoice invoice, User user)
    {
        InsertInvoice(invoice, user);
        UpdateCustomerDebt(user, invoice.Total);
    }

    // ... the rest of the implementation
}

public class TransactionalDataAccess : IDataAccess
{
    private readonly IDataAccess _dataAccess;

    public TransactionalDataAccess(IDataAccess dataAccess)
    {
        if (dataAccess == null)
        {
            throw new ArgumentNullException();
        }
        _dataAccess = dataAccess;
    }

    public void AddCustomerInvoice(Invoice invoice, User user)
    {
         using(var tx = new TransactionScope())
         {
             _dataAccess.AddCustomerInvoice(invoice, user);
             tx.Complete();
         }
    }

    // ... the rest of the implementation
}
</pre>
<p>Another type of example would be the <a href="http://en.wikipedia.org/wiki/Adapter_pattern">Adapter</a> design pattern. An example would be providing access to a (static) class (that may be out of your control) in a mock-able manner. That is, implement another class, non-static, which implements a defined interface and eases unit-testing :</p>
<p><span id="more-197"></span></p>
<pre class="brush: csharp; title: ; notranslate">

public class StorageManager
{
    public void StoreData(string key, byte[] data)
    {
         if (string.IsNullOrWhiteSpace(key))
         {
              throw new ArgumentNullException(&quot;key&quot;);
         }
         if (data == null)
         {
             throw new ArgumentNullException(&quot;data&quot;);
         }
         System.IO.File.WriteAllBytes(key + &quot;.bin&quot;, data);
    }
}
</pre>
<p>This class, as you can see, uses the static File class in the BCL of .NET Framework. If I need to unit-test the StoreData method in a way to assert that the data is actually written to the file (and maybe test the file is named as the key and the binary data and only the binary data is placed in that file etc.) then I can&#8217;t do it. Well you might get away with <a href="http://www.typemock.com/isolator-product-page/">TypeMock Isolator</a> (expensive piece of&#8230; software) or <a href="http://research.microsoft.com/en-us/projects/pex/">Moles/Pex</a> but it&#8217;s just not right™.</p>
<p>So we define an interface :</p>
<pre class="brush: csharp; title: ; notranslate">

public interface IFileAccess
{
    void WriteAllBytes(string filePath, byte[] binaryContent);
}
</pre>
<p>and then we write an implementation for this class</p>
<pre class="brush: csharp; title: ; notranslate">

public class FileAccessAdapter : IFileAccess
{
    public void WriteAllBytes(string filePath, byte[] binaryContent)
    {
        System.IO.File.WriteAllBytes(filePath, binaryContent);
    }
}
</pre>
<p>Finally we update the StorageManager class :</p>
<pre class="brush: csharp; title: ; notranslate">

public class StorageManager
{
    private readonly IFileAccess _fileAccess;

    public StorageManager(IFileAccess fileAccess)
    {
         if (fileAccess == null)
         {
             throw new ArgumentNullException(&quot;fileAccess&quot;);
         }
         _fileAccess = fileAccess;
    }

    public void StoreData(string key, byte[] data)
    {
         if (string.IsNullOrWhiteSpace(key))
         {
              throw new ArgumentNullException(&quot;key&quot;);
         }
         if (data == null)
         {
             throw new ArgumentNullException(&quot;data&quot;);
         }
         _fileAccess.WriteAllBytes(key + &quot;.bin&quot;, data);
    }
}
</pre>
<p>Now we can unit test the StorageManager class by providing a mock of the IFileAccess interface.</p>
<p>Having finished the introduction let&#8217;s get to business. The nice thing is that using these patterns you have a more loosely-coupled code and you can unit test it. The not-so-nice thing is that you need to write a lot of repetitive code that&#8217;s really boring. I mean usually the interfaces won&#8217;t have 1-2 methods like my examples above but sometimes tens or even a hundred (yes, unfortunately some people haven&#8217;t heard of ISP &#8211; <a href="http://en.wikipedia.org/wiki/Interface_segregation_principle">Interface Segregation Principle</a>).</p>
<p>Today, as I was creating such an adapter for a static class to which I don&#8217;t have much control, I thought : maybe <a href="http://www.jetbrains.com/resharper/">ReSharper</a> can help me&#8230; I looked in the implement interface dialog box but no help. Then I turned to Google and as usual in the past few years one of the best piece of information came from Stackoverflow : <a href="http://stackoverflow.com/q/1419913/1796">How to (visual studio 2008 / Resharper) refactor / automate mixin pattern</a>.</p>
<p>Trying to implement the adapter pattern I failed since ReSharper does not support this scenario directly but being intrigued I tried to create a decorator (the first scenario presented above). However, let&#8217;s resume the first example. At first I wrote the class definition and the constructor for the TransactionalDataAccess class :</p>
<pre class="brush: csharp; title: ; notranslate">

public class TransactionalDataAccess : IDataAccess
{
    private readonly IDataAccess _dataAccess;

    public TransactionalDataAccess(IDataAccess dataAccess)
    {
        if (dataAccess == null)
        {
            throw new ArgumentNullException();
        }
        _dataAccess = dataAccess;
    }
}
</pre>
<p>Then I pressed ALT-INSERT inside the block of code of the class :</p>
<p><a href="http://blog.andrei.rinea.ro/wp-content/uploads/2012/07/Menu.png"><img class="alignnone size-full wp-image-200" title="Menu" src="http://blog.andrei.rinea.ro/wp-content/uploads/2012/07/Menu.png" alt="" width="473" height="487" /></a></p>
<p>I selected <strong>Delegating members</strong> and then in the following dialog box :</p>
<p><a href="http://blog.andrei.rinea.ro/wp-content/uploads/2012/07/dialog.png"><img class="alignnone size-full wp-image-202" title="dialog" src="http://blog.andrei.rinea.ro/wp-content/uploads/2012/07/dialog.png" alt="" width="500" height="500" /></a></p>
<p>I selected all the interface&#8217;s members (in this simple example there was only one but in production I selected around 50 members). Finally the code generated was like this :</p>
<pre class="brush: csharp; title: ; notranslate">

public class TransactionalDataAccess : IDataAccess
{
    private readonly IDataAccess _dataAccess;

    public TransactionalDataAccess(IDataAccess dataAccess)
    {
        if (dataAccess == null)
        {
            throw new ArgumentNullException();
        }
        _dataAccess = dataAccess;
    }

    public void AddCustomerInvoice(Invoice invoice, User user)
    {
        _dataAccess.AddCustomerInvoice(invoice, user);
    }
}
</pre>
<p>I just added the transaction wrapper :</p>
<pre class="brush: csharp; title: ; notranslate">

public class TransactionalDataAccess : IDataAccess
{
    private readonly IDataAccess _dataAccess;

    public TransactionalDataAccess(IDataAccess dataAccess)
    {
        if (dataAccess == null)
        {
            throw new ArgumentNullException();
        }
        _dataAccess = dataAccess;
    }

    public void AddCustomerInvoice(Invoice invoice, User user)
    {
        using (var tx = new TransactionScope())
        {
            _dataAccess.AddCustomerInvoice(invoice, user);
            tx.Complete();
        }
    }
}
</pre>
<p>&#8230; and I was done with it. For the adapter class all you need is to extract the interface from the static class (you can view the metadata using Visual Studio and copy/paste it). Then create the adapter class, create a constructor with (at least) one parameter of the interface type, generate the delegating members just like above, modify or delete the constructor and the private field and replace (CTRL-H) all the occurences of the private field with a call to the static class being adapted.</p>
<p>&#8230; that&#8217;s all folks!</p>
<img src="http://feeds.feedburner.com/~r/Andrei-Rinea/~4/jOBaubpF__A" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.andrei.rinea.ro/2012/07/30/resharper-hidden-features-generate-delegating-members/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://blog.andrei.rinea.ro/2012/07/30/resharper-hidden-features-generate-delegating-members/?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=resharper-hidden-features-generate-delegating-members</feedburner:origLink></item>
		<item>
		<title>Windows 8 – first impressions</title>
		<link>http://feedproxy.google.com/~r/Andrei-Rinea/~3/zjLnZOzLszk/</link>
		<comments>http://blog.andrei.rinea.ro/2012/07/27/windows-8-first-impressions/#comments</comments>
		<pubDate>Fri, 27 Jul 2012 14:18:05 +0000</pubDate>
		<dc:creator>Andrei Rinea</dc:creator>
				<category><![CDATA[Operating Systems]]></category>
		<category><![CDATA[Aero]]></category>
		<category><![CDATA[microsoft]]></category>
		<category><![CDATA[OS]]></category>
		<category><![CDATA[Windows 8]]></category>

		<guid isPermaLink="false">http://blog.andrei.rinea.ro/?p=189</guid>
		<description><![CDATA[I downloaded and installed Windows 8 Release Preview on two of my computers since one (the laptop) was up for selling to a friend and the (up to then) unused desktop was OS-less. The installation is well streamlined, just like &#8230;<p class="read-more"><a href="http://blog.andrei.rinea.ro/2012/07/27/windows-8-first-impressions/">Read more &#187;</a></p>]]></description>
			<content:encoded><![CDATA[<div class="google_plusone_widget"><g:plusone 
      count="true" href="http://blog.andrei.rinea.ro/2012/07/27/windows-8-first-impressions/" size="tall"></g:plusone></div><p>I <a href="http://windows.microsoft.com/en-US/windows-8/iso">downloaded</a> and installed Windows 8 Release Preview on two of my computers since one (the laptop) was up for selling to a friend and the (up to then) unused desktop was OS-less.</p>
<p><a href="http://blog.andrei.rinea.ro/wp-content/uploads/2012/07/win8.jpg"><img class="alignnone size-full wp-image-193" title="win8" src="http://blog.andrei.rinea.ro/wp-content/uploads/2012/07/win8.jpg" alt="" width="550" height="402" /></a></p>
<p>The installation is well streamlined, just like Office 2010 (or maybe even 2007?) in that it provides a large and attractive &#8220;Install now&#8221; button so you have very little to think. If you need to customize the installation there is a small link beneath that allows you to do just that. I didn&#8217;t opt for that.</p>
<p>It took, I think, 20 minutes to install completely which is pretty decent in my opinion. At this moment I need to state the hardware involved :</p>
<ul>
<li><a href="http://www.intel.com/products/processor/core2quad/specifications.htm">Intel Core 2 Quad 2.4 GHz CPU</a></li>
<li><a href="http://www.gigabyte.com/products/product-page.aspx?pid=2951#sp">GIGABYTE GA-EP-45-UD3LR Mainboard</a></li>
<li><a href="http://www.emag.ro/hdd-western-digital-rs-1tb-64mb-sata-wd10ears/pd/EHSD2BBBM/">HDD 1.0 TB Western Digital (5400 rpm &#8211; yeah, it will fly out the window soon)</a></li>
<li>8 GB RAM DDR2</li>
</ul>
<p>As you can guess the major visual difference is the start menu which looks pretty freaky as in the picture above. You will need some time to get accustomed to it. The tiles at the left are metro apps (which work pretty different, running in full screen and having the same visual style). At the right there are non-metro apps (should we call them &#8220;legacy apps&#8221;?). The desktop itself is a metro app.</p>
<p>The taskbar does not have the start button anymore since the start menu is a full screen thing. So you&#8217;ll probably start up, by mistake, IE 10 a few times since by default it is the leftmost thing on the taskbar. IE 10 seems to be pretty much the same thing as IE 9 but snappier.</p>
<p>I also struggled a bit to change the audio volume but I found that &#8220;touching&#8221; (with the mouse cursor) the top right corner brings up a band/pane which contains several settings such as audio volume, power commands and others (search, share, start, devices and settings).</p>
<p>A similar &#8220;charm&#8221; (it seems this is the name) exists on the left, for switching apps. You can get used to these, it ain&#8217;t too hard.</p>
<p>A really nice improvement is the copy/cut files dialog :</p>
<p><a href="http://blog.andrei.rinea.ro/wp-content/uploads/2012/07/win8progress.png"><img class="alignnone size-full wp-image-195" title="win8progress" src="http://blog.andrei.rinea.ro/wp-content/uploads/2012/07/win8progress.png" alt="" width="571" height="370" /></a></p>
<p>It&#8217;s nice because it has a graph and shows actual average as a horizontal line which varies depending on the actual speed of the process. It also has a nice new addition : the pause button which can be pretty handy if you need to relax a drive&#8217;s load.</p>
<p>The <a href="http://farm1.static.flickr.com/92/229709775_47c9571c33.jpg">Win-TAB 3D animation</a> for switching apps seems gone (or at least you won&#8217;t be able to trigger it with Win-TAB) which kinda sucks.</p>
<p>The dialog boxes are somewhat improved in the way they are simpler to understand and to decide what to do further. The file searching seems faster and app searching too.</p>
<p>All in all it seems like a real upgrade.</p>
<img src="http://feeds.feedburner.com/~r/Andrei-Rinea/~4/zjLnZOzLszk" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.andrei.rinea.ro/2012/07/27/windows-8-first-impressions/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		<feedburner:origLink>http://blog.andrei.rinea.ro/2012/07/27/windows-8-first-impressions/?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=windows-8-first-impressions</feedburner:origLink></item>
		<item>
		<title>Beware of switch</title>
		<link>http://feedproxy.google.com/~r/Andrei-Rinea/~3/phb8L8FKVuw/</link>
		<comments>http://blog.andrei.rinea.ro/2012/07/24/beware-of-switch/#comments</comments>
		<pubDate>Tue, 24 Jul 2012 09:51:45 +0000</pubDate>
		<dc:creator>Andrei Rinea</dc:creator>
				<category><![CDATA[Best practices]]></category>
		<category><![CDATA[CodeProject]]></category>
		<category><![CDATA[antipatterns]]></category>
		<category><![CDATA[best-practices]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[design]]></category>
		<category><![CDATA[design-patterns]]></category>
		<category><![CDATA[OOP]]></category>
		<category><![CDATA[polymorphism]]></category>
		<category><![CDATA[refactoring]]></category>
		<category><![CDATA[switch]]></category>

		<guid isPermaLink="false">http://blog.andrei.rinea.ro/?p=181</guid>
		<description><![CDATA[I am by no means against any of the instructions which exist in C#, including goto (wow, I said that). Each of them can have its place and its normal use in an application. However things can be abused and &#8230;<p class="read-more"><a href="http://blog.andrei.rinea.ro/2012/07/24/beware-of-switch/">Read more &#187;</a></p>]]></description>
			<content:encoded><![CDATA[<div class="google_plusone_widget"><g:plusone 
      count="true" href="http://blog.andrei.rinea.ro/2012/07/24/beware-of-switch/" size="tall"></g:plusone></div><p>I am by no means against any of the instructions which exist in C#, including goto (wow, I said that). Each of them can have its place and its normal use in an application. However things can be abused and code gets nasty.</p>
<p>For example let&#8217;s consider we are displaying a hierarchy of people in an organization in a tree-like visual component. We will create a class that models a person :</p>
<pre class="brush: csharp; title: ; notranslate">
public class Person
{
    public string Name { get; set; }
    public IEnumerable Subordinates { get; set; }
}
</pre>
<p>All is nice but some requests come in, such as : each type of person should have a distinctive icon at its left, the managers should have salutation type displayed etc.</p>
<p>Then you think &#8220;I know, I&#8217;ll create a PersonType enum&#8221;. That&#8217;s when things will begin to get nasty.</p>
<pre class="brush: csharp; title: ; notranslate">
public enum PersonType
{
    Undefined,
    Simple,
    Manager
}

public class Person
{
    public IEnumerable Subordinates { get; set; }

    // new members :
    public PersonType Type { get; set; }
    public string Salutation { get; set; }
    private string _name;

    // modified members :
    public string Name
    {
        get
        {
             switch(Type)
             {
                 case PersonType.Simple: return _name;
                 case PersonType.Manager : return Salutation + &quot; &quot; + _name;
                 default : throw new InvalidOperationException();
             }
        }
        set { _name = value; }
    }

    public Image Icon
    {
        get
        {
            switch(Type)
            {
                 case PersonType.Simple: return Icons.SimplePersonIcon;
                 case PersonType.Manager : return Icons.ManagerIcon;
                 default : throw new InvalidOperationException();
            }
        }
    }
}
</pre>
<p>If you find yourself writing switches in one or more properties or methods of the class, switching on the same thing (PersonType here) then stop it. You are writing hard-to-maintain and error-prone code. Plus its inelegant. This practically is a cry for polymorphism.</p>
<p>The right thing to do™ is to have three classes : an abstract Person class, a SimplePerson class (inheriting the Person class) and a ManagerPerson class (also inheriting the Person class) :</p>
<pre class="brush: csharp; title: ; notranslate">

public abstract class Person
{
    public virtual string Name { get; set; }
    public IEnumerable Subordinates { get; set; }
    public abstract Image Icon { get; }
    public string Salutation { get; set; }
}

public class SimplePerson : Person
{
    public override Image Icon { get { Icons.SimplePersonIcon; } }
}

public class ManagerPerson : Person
{
    private string _name;

    public override Image Icon { get { Icons.ManagerIcon; } }
    public override string Name
    {
        get
        {
            return Salutation + &quot; &quot; + _name;
        }
        set
        {
            _name = value;
        }
    }
}
</pre>
<p>Notice that the code is shorter, simpler to follow and understand. Furthermore although we did introduce two more classes, we also removed the PersonType enum so at a total we introduced only one more class.</p>
<img src="http://feeds.feedburner.com/~r/Andrei-Rinea/~4/phb8L8FKVuw" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.andrei.rinea.ro/2012/07/24/beware-of-switch/feed/</wfw:commentRss>
		<slash:comments>20</slash:comments>
		<feedburner:origLink>http://blog.andrei.rinea.ro/2012/07/24/beware-of-switch/?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=beware-of-switch</feedburner:origLink></item>
		<item>
		<title>New features for database developers in SQL Server 2012 : simpler paging, sequences and FileTables</title>
		<link>http://feedproxy.google.com/~r/Andrei-Rinea/~3/mqGcflrhUYk/</link>
		<comments>http://blog.andrei.rinea.ro/2012/07/13/new-features-for-database-developers-in-sql-server-2012-simpler-paging-sequences-and-filetables/#comments</comments>
		<pubDate>Fri, 13 Jul 2012 11:01:15 +0000</pubDate>
		<dc:creator>Andrei Rinea</dc:creator>
				<category><![CDATA[CodeProject]]></category>
		<category><![CDATA[SQL Server]]></category>
		<category><![CDATA[BIGINT]]></category>
		<category><![CDATA[binary]]></category>
		<category><![CDATA[DECIMAL]]></category>
		<category><![CDATA[execution-plan]]></category>
		<category><![CDATA[filestream]]></category>
		<category><![CDATA[FileTable]]></category>
		<category><![CDATA[INT]]></category>
		<category><![CDATA[NUMERIC]]></category>
		<category><![CDATA[paging]]></category>
		<category><![CDATA[sequence]]></category>
		<category><![CDATA[share]]></category>
		<category><![CDATA[SMALLINT]]></category>
		<category><![CDATA[SQL Server 2012]]></category>
		<category><![CDATA[throw]]></category>
		<category><![CDATA[TINYINT]]></category>
		<category><![CDATA[VARBINARY(MAX)]]></category>

		<guid isPermaLink="false">http://blog.andrei.rinea.ro/?p=144</guid>
		<description><![CDATA[TL;DR : Paging got simpler and more efficient Sequences have been introduced; better performance for auto-generated IDs and easier to have IDs unique across tables FileTables have been introduced : building upon the FileStream feature now we can have non-transactional access to files stored &#8230;<p class="read-more"><a href="http://blog.andrei.rinea.ro/2012/07/13/new-features-for-database-developers-in-sql-server-2012-simpler-paging-sequences-and-filetables/">Read more &#187;</a></p>]]></description>
			<content:encoded><![CDATA[<div class="google_plusone_widget"><g:plusone 
      count="true" href="http://blog.andrei.rinea.ro/2012/07/13/new-features-for-database-developers-in-sql-server-2012-simpler-paging-sequences-and-filetables/" size="tall"></g:plusone></div><p><strong>TL;DR :</strong></p>
<ul>
<li>Paging got simpler and more efficient</li>
<li>Sequences have been introduced; better performance for auto-generated IDs and easier to have IDs unique across tables</li>
<li>FileTables have been introduced : building upon the FileStream feature now we can have non-transactional access to files stored in the DB as a windows share along with transactional access via T-SQL</li>
</ul>
<p><strong>Lengthier version :</strong></p>
<p>SQL Server 2012, in my opinion does not come with earth-shaking changes but comes with performance improvements, feature improvements and a some new features.</p>
<p>First of all, Management Studio has the same engine as Visual Studio which means you get a nice WPF experience, better font rendering and CTRL-scroll quick zoom-in/zoom-out.</p>
<p><a href="http://blog.andrei.rinea.ro/wp-content/uploads/2012/07/1-logo.png"><img title="SQL Server 2012 logo" src="http://blog.andrei.rinea.ro/wp-content/uploads/2012/07/1-logo.png" alt="" width="469" height="304" /></a></p>
<p>Let&#8217;s say you want to retrieve data from the database in a paged way (that means chunks of data of a requested size or smaller). Typically you would write this in SQL Server 2008 R2 or older :</p>
<pre class="brush: sql; title: ; notranslate">

DECLARE	@Offset		AS INT = 6
DECLARE @PageSize	AS INT = 5

SELECT	Id,
		Name
FROM
(
	SELECT	Id,
			Name,
			ROW_NUMBER()	OVER (ORDER BY Id)	AS	RowNumber
	FROM	Users
) UsersSelection

WHERE	UsersSelection.RowNumber &gt;  @Offset
	AND	UsersSelection.RowNumber &lt;= @Offset + @PageSize
</pre>
<p>In SQL Server 2012 the T-SQL syntax has been updated introducing keywords that facilitate a simpler and more efficient paging, keywords such as OFFSET, FETCH, NEXT ROWS and ONLY. A script that would retrieve the same data would be :</p>
<pre class="brush: sql; title: ; notranslate">

DECLARE	@Offset		AS INT = 6
DECLARE @PageSize	AS INT = 5

SELECT		Id,
			Name
FROM		Users
ORDER BY	Id
OFFSET		@Offset		ROWS
FETCH NEXT	@PageSize	ROWS ONLY
</pre>
<p>Observe the simpler, clearer syntax. Also, considering that the subselect has been eliminated (the subselect was required because the ROW_NUMBER column could not be addressed in the same select &#8211; for the WHERE clause), also the query cost was improved :</p>
<p>2008 :</p>
<p><a href="http://blog.andrei.rinea.ro/wp-content/uploads/2012/07/2-2008pg-cost.png"><img src="http://blog.andrei.rinea.ro/wp-content/uploads/2012/07/2-2008pg-cost.png" alt="" title="2-2008pg-cost" width="839" height="71" class="alignnone size-full wp-image-154" /></a></p>
<p>2012 : </p>
<p><span id="more-144"></span></p>
<p><a href="http://blog.andrei.rinea.ro/wp-content/uploads/2012/07/2-2012pg-cost.png"><img src="http://blog.andrei.rinea.ro/wp-content/uploads/2012/07/2-2012pg-cost.png" alt="" title="2-2012pg-cost" width="443" height="69" class="alignnone size-full wp-image-155" /></a></p>
<p><a href="http://msdn.microsoft.com/en-us/library/ms188385.aspx">More details</a> about the paging (some call it pagination) semantics can be found on MSDN.</p>
<p>Next, let&#8217;s introduce <a href="http://msdn.microsoft.com/en-us/library/ff878091.aspx">sequences</a>. MSDN states that :</p>
<blockquote>
<p>A sequence is a user-defined schema bound object that generates a sequence of numeric values according to the specification with which the sequence was created. The sequence of numeric values is generated in an ascending or descending order at a defined interval and can be configured to restart (cycle) when exhausted. Sequences, unlike identity columns, are not associated with specific tables. Applications refer to a sequence object to retrieve its next value. The relationship between sequences and tables is controlled by the application. User applications can reference a sequence object and coordinate the values across multiple rows and tables.</p>
<p>&#8230;<br />
&#8230;<br />
&#8230;</p>
<p>Use sequences instead of identity columns in the following scenarios:</p>
<ul>
<li>The application requires a number before the insert into the table is made.</li>
<li>The application requires sharing a single series of numbers between multiple tables or multiple columns within a table.</li>
<li>The application must restart the number series when a specified number is reached. For example, after assigning values 1 through 10, the application starts assigning values 1 through 10 again.</li>
<li>The application requires sequence values to be sorted by another field. The NEXT VALUE FOR function can apply the OVER clause to the function call. The OVER clause guarantees that the values returned are generated in the order of the OVER clause&#8217;s ORDER BY clause.</li>
<li>An application requires multiple numbers to be assigned at the same time. For example, an application needs to reserve five sequential numbers. Requesting identity values could result in gaps in the series if other processes were simultaneously issued numbers. Calling sp_sequence_get_range can retrieve several numbers in the sequence at once.</li>
<li>You need to change the specification of the sequence, such as the increment value.</li>
</ul>
</blockquote>
<p>Now, let&#8217;s take a concrete example of a scenario. Let&#8217;s say there is some kind of inventory in your company that needs to track certain company assets. Each asset must have its identifier which should be unique across the entire inventory. Let&#8217;s suppose we need to track chairs, monitors and other office items and their main characteristics.</p>
<p>One way to do this would be to create a wide table such as :</p>
<pre class="brush: sql; title: ; notranslate">

CREATE TABLE Inventory (
    Id INT IDENTITY(1,1) NOT NULL,
    ItemTypeId TINYINT NOT NULL,
    InchSize TINYINT NULL, -- applies only to monitors
    HasArmRest BIT NULL, -- applies only to chairs
    AdjustableHeight BIT NULL, --might apply to monitors and chairs

 -- ... and so on
</pre>
<p>That would be a wrong way to do this because of several reasons :</p>
<ul>
<li>It would be hard to read, maintain, query</li>
<li>It would violate several database design rules</li>
<li>Most of the columns would be nullable increasing the storage space and query speed</li>
</ul>
<p>Therefore we will design several tables, one for each of the inventory item, also getting rid of the ItemTypeId column.</p>
<p>However generating the ID would no longer be so simple. If we put an ID column as an IDENTITY on each table then we won&#8217;t have unique IDs across the inventory. So the 2008-R2-and-older approach would be to create another table, with a single IDENTITY column, table whose whole purpose would be to generate unique IDs. The script to insert an item in this scenario would be :</p>
<pre class="brush: sql; title: ; notranslate">

DECLARE @Id INT
BEGIN TRY
	BEGIN TRANSACTION
		INSERT INTO InventoryIds DEFAULT VALUES
		SET @Id = SCOPE_IDENTITY()
		INSERT INTO Monitors
		(
			[Id],
			[Width]
		)
		VALUES
		(
			@Id,
			17
		)
	COMMIT TRANSACTION
END TRY
BEGIN CATCH
	ROLLBACK TRANSACTION;
	DECLARE @ErrorMessage NVARCHAR(4000);
    DECLARE @ErrorSeverity INT;
    DECLARE @ErrorState INT;
    SELECT	@ErrorMessage = ERROR_MESSAGE(),
			@ErrorSeverity = ERROR_SEVERITY(),
			@ErrorState = ERROR_STATE();
    RAISERROR (@ErrorMessage,
               @ErrorSeverity,
               @ErrorState);
END CATCH
</pre>
<p>Notice the use of SCOPE_IDENTITY() instead of @@IDENTITY (a short and nice comparison can be found in this <a href="http://stackoverflow.com/a/1920640/1796">StackOverflow response</a>) and INSERT INTO [TableName] DEFAULT VALUES, which at least for me, was a new thing.</p>
<p>Seems overly complicated and to an extent it is. But at least it does a few things well :</p>
<ul>
<li>It is transactional so if for some reasons a part of fails, all fails and no orphan IDs will be left behind in the </li>
<li>It employs a simpler error-handling through the use of TRY/CATCH. By the way 2012 introduces the THROW keyword which can be used as is (no parameters) to rethrow the error to the caller.</li>
<li>On error it rolls back the transaction AND it reports the error to the caller as close as it was.</li>
</ul>
<p>Let&#8217;s see how we can simplify this in SQL Server 2012 using sequences :</p>
<p>First, we don&#8217;t need the InventoryIds any more. Then we&#8217;ll create a sequence :</p>
<p><a href="http://blog.andrei.rinea.ro/wp-content/uploads/2012/07/4-Add-sequence.png"><img src="http://blog.andrei.rinea.ro/wp-content/uploads/2012/07/4-Add-sequence.png" alt="" title="4-Add-sequence" width="270" height="472" class="alignnone size-full wp-image-163" /></a></p>
<p>Notice the new &#8220;Sequences&#8221; node under &#8220;Programability&#8221;. Next we&#8217;ll set up the sequence attributes :</p>
<p><a href="http://blog.andrei.rinea.ro/wp-content/uploads/2012/07/5-Sequence-definition.png"><img src="http://blog.andrei.rinea.ro/wp-content/uploads/2012/07/5-Sequence-definition.png" alt="" title="" width="758" height="598" class="alignnone size-full wp-image-164" /></a></p>
<p>The cycle option is useless in this and the rest of the majority of scenarios. The cache option can be useful in high-loads scenarios since the database engine doesn&#8217;t need to read the disk for each ID generated, as it was the case with IDENTITY. The performance improvement is not huge but it&#8217;s welcome nevertheless.</p>
<p>Next we&#8217;ll write the SQL script to insert the same data : </p>
<pre class="brush: sql; title: ; notranslate">

INSERT INTO Monitors
(
	Id,
	Width
)
VALUES
(
	NEXT VALUE FOR seqInventory,
	19
)
</pre>
<p>Notice the simpler syntax, a lot shorter and more elegant. Also the monitor is larger <img src='http://blog.andrei.rinea.ro/wp-includes/images/smilies/icon_razz.gif' alt=':P' class='wp-smiley' /> </p>
<p>During the presentation at <a href="http://ronua.ro">RONUA</a> I was asked two questions that I didn&#8217;t have a (definitive) answer back then :</p>
<ol>
<li>Can&#8217;t we use UNIQUEIDENTIFIERs and be done with these sequences or sequence-simulation via that table?
<p><strong>Yes, we can but this has some disadvantages : longer key means more I/O and more storage which hampers JOIN performance and a GUID will be harder to manipulate for a human being &#8211; let&#8217;s say the poor guy that has to stamp all the inventory goods with the IDs</strong></li>
<li>What data types are supported by sequences?
<p><strong>TINYINT, INT, SMALLINT, BIGINT, DECIMAL and NUMERIC</strong></li>
</ol>
<p>Finally we approach filetables. This addresses storing (large) binary content in the database. Since this was possible the database people have been torn in two camps : the ones that see this as the best solution and the ones that hate this to death. Personally I&#8217;m in the first camp <img src='http://blog.andrei.rinea.ro/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>Typically a CMS / or some other type of website will allow (some) users to upload pictures. This is a common scenario that is encountered but, of course, it&#8217;s not the only one.</p>
<p>The other solution would be to store the files on the disk (in the file system, that is) and have a table in the database which contains all the related data (filename, extension, length, date-modified, date-uploaded, actual-filename, actual-path and so on).</p>
<p>The advantages of storing the files in the database would be, in my opinion :</p>
<ul>
<li>One data store for all the application&#8217;s data; better organization</li>
<li>A single backup not two or more</li>
<li>Online backup; the app can add/delete/modify files while the backup is running</li>
<li>Incremental backups; yes, rsync could do incremental backups for the filesystem but it&#8217;s harder</li>
</ul>
<p>Now considering you would opt for this solution &#8211; storing the files in the DB &#8211; SQL Server 2012 offers you the filetable feature. This is a solution built upon the <a href="http://technet.microsoft.com/en-us/library/bb933993(SQL.105).aspx">FILESTREAM</a> feature which means storing the binary data outside of the MDF (Main Data File) of the database in order to avoid degrading the performance of the typical structured data.</p>
<p>The FileTable feature also allows you to access the files stored in the database via a virtual windows share so any app can access the files from there.</p>
<p>Let&#8217;s walk this through and we&#8217;ll comment on the feature as we go.</p>
<p>First let&#8217;s enable the FILESTREAM support at the server level. Open SQL Server Configuration Manager (requires Administrator privileges) select the SQL Server instance and right-click to properties :</p>
<p><a href="http://blog.andrei.rinea.ro/wp-content/uploads/2012/07/6-serverlevel-support.png"><img src="http://blog.andrei.rinea.ro/wp-content/uploads/2012/07/6-serverlevel-support.png" alt="" title="6-serverlevel-support" width="428" height="499" class="alignnone size-full wp-image-172" /></a></p>
<p>We&#8217;ll check all the check-boxes. After this a server restart might be required. Next we&#8217;ll create a new database (an existing database can be enabled too, but for clarity we&#8217;ll start with a new database).<br />
In the &#8216;New Database&#8217; dialog we&#8217;ll go through the three tabs from bottom to top. Let&#8217;s start with Filegroups and create a new FILESTREAM group :</p>
<p><a href="http://blog.andrei.rinea.ro/wp-content/uploads/2012/07/7-newdb-filegroup.png"><img src="http://blog.andrei.rinea.ro/wp-content/uploads/2012/07/7-newdb-filegroup.png" alt="" title="7-newdb-filegroup" width="704" height="632" class="alignnone size-full wp-image-168" /></a></p>
<p>Next, at the options tab, choose a directory name and select the desired access level to the windows share (&#8216;non-transacted access&#8217;). For this demo I chose &#8216;Full&#8217; :</p>
<p><a href="http://blog.andrei.rinea.ro/wp-content/uploads/2012/07/8-newdb-options.png"><img src="http://blog.andrei.rinea.ro/wp-content/uploads/2012/07/8-newdb-options.png" alt="" title="8-newdb-options" width="708" height="633" class="alignnone size-full wp-image-169" /></a></p>
<p>Finally we&#8217;ll add a new file in the General tab, then choose a name for the file, select FILESTREAM Data as its type, select the FILESTREAM group and choose a path. The path must exist and it will not be created by SQL Server. You need to create it before finalizing the database creation.</p>
<p><a href="http://blog.andrei.rinea.ro/wp-content/uploads/2012/07/9-newdb-file.png"><img src="http://blog.andrei.rinea.ro/wp-content/uploads/2012/07/9-newdb-file.png" alt="" title="9-newdb-file" width="1370" height="632" class="alignnone size-full wp-image-170" /></a></p>
<p>Now click ok and the database is finally created. It&#8217;s a bit of &#8216;pain in the side&#8217; but it only hurts the first time (like other things in life..). Let&#8217;s create a filetable in this new database : </p>
<p><a href="http://blog.andrei.rinea.ro/wp-content/uploads/2012/07/10-create-filetable.png"><img src="http://blog.andrei.rinea.ro/wp-content/uploads/2012/07/10-create-filetable.png" alt="" title="10-create-filetable" width="270" height="193" class="alignnone size-full wp-image-174" /></a></p>
<p>Notice the new &#8216;FileTable&#8217; node under &#8216;Tables&#8217;. While doing this we&#8217;ll not be greeted with a dialog box (as I consider we should be) but with a new script like so :</p>
<pre class="brush: sql; title: ; notranslate">
-- =========================================
-- Create FileTable template
-- =========================================
USE &lt;database, sysname, AdventureWorks&gt;
GO

IF OBJECT_ID('&lt;schema_name, sysname, dbo&gt;.&lt;table_name, sysname, sample_filetable&gt;', 'U') IS NOT NULL
  DROP TABLE &lt;schema_name, sysname, dbo&gt;.&lt;table_name, sysname, sample_filetable&gt;
GO

CREATE TABLE &lt;schema_name, sysname, dbo&gt;.&lt;table_name, sysname, sample_filetable&gt; AS FILETABLE
  WITH
  (
    FILETABLE_DIRECTORY = '&lt;file_table_directory_name, sysname, sample_filetable&gt;',
    FILETABLE_COLLATE_FILENAME = &lt;file_table_filename_collation, sysname, database_default&gt;
  )
GO
</pre>
<p>From all this mess we&#8217;ll strip out the unnecessary and we&#8217;ll be left with this :</p>
<pre class="brush: sql; title: ; notranslate">
CREATE TABLE MyImages AS FILETABLE
  WITH
  (
    FILETABLE_DIRECTORY = 'MyImages'
  )
</pre>
<p>This little statement will create a table like so :</p>
<p><a href="http://blog.andrei.rinea.ro/wp-content/uploads/2012/07/11-filetable-structure.png"><img src="http://blog.andrei.rinea.ro/wp-content/uploads/2012/07/11-filetable-structure.png" alt="" title="11-filetable-structure" width="423" height="521" class="alignnone size-full wp-image-176" /></a></p>
<p>Right click on the file table (in Object Explorer) and select the Explore FileTable Directory. This will bring up an empty shared folder. Create a new text file and open it, write some text, save it and close the Notepad.</p>
<p>Now run </p>
<pre class="brush: sql; title: ; notranslate">
SELECT	*,
		CAST(file_stream as VARCHAR(MAX))	AS [TextContent]
FROM	MyImages
</pre>
<p>You&#8217;ll notice how the files moved, renamed, deleted, content-changed and any kind of change done in the windows share is reflected back in the FileTable and vice-versa!</p>
<p>This is a very powerful feature, and in my opinion, quite welcome.</p>
<img src="http://feeds.feedburner.com/~r/Andrei-Rinea/~4/mqGcflrhUYk" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.andrei.rinea.ro/2012/07/13/new-features-for-database-developers-in-sql-server-2012-simpler-paging-sequences-and-filetables/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		<feedburner:origLink>http://blog.andrei.rinea.ro/2012/07/13/new-features-for-database-developers-in-sql-server-2012-simpler-paging-sequences-and-filetables/?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=new-features-for-database-developers-in-sql-server-2012-simpler-paging-sequences-and-filetables</feedburner:origLink></item>
		<item>
		<title>SQL Server 2012 local talk</title>
		<link>http://feedproxy.google.com/~r/Andrei-Rinea/~3/MeamFGUOWdw/</link>
		<comments>http://blog.andrei.rinea.ro/2012/07/02/sql-server-2012-local-talk/#comments</comments>
		<pubDate>Mon, 02 Jul 2012 13:32:37 +0000</pubDate>
		<dc:creator>Andrei Rinea</dc:creator>
				<category><![CDATA[Presentations]]></category>
		<category><![CDATA[SQL Server]]></category>
		<category><![CDATA[bucharest]]></category>
		<category><![CDATA[FileTable]]></category>
		<category><![CDATA[offset]]></category>
		<category><![CDATA[paging]]></category>
		<category><![CDATA[RONUA]]></category>
		<category><![CDATA[sequence]]></category>
		<category><![CDATA[SQL Server 2012]]></category>
		<category><![CDATA[TeamNet]]></category>

		<guid isPermaLink="false">http://blog.andrei.rinea.ro/?p=137</guid>
		<description><![CDATA[Tuesday, July 10th, I&#8217;ll hold a small presentation on the new features of SQL Server 2012 for the database developer, consisting mainly of the sequences, new paging semantics and filetables. I&#8217;ll post the code and slides soon after the presentation. &#8230;<p class="read-more"><a href="http://blog.andrei.rinea.ro/2012/07/02/sql-server-2012-local-talk/">Read more &#187;</a></p>]]></description>
			<content:encoded><![CDATA[<div class="google_plusone_widget"><g:plusone 
      count="true" href="http://blog.andrei.rinea.ro/2012/07/02/sql-server-2012-local-talk/" size="tall"></g:plusone></div><p>Tuesday, July 10th, I&#8217;ll hold a small presentation on the new features of SQL Server 2012 for the database developer, consisting mainly of the sequences, new paging semantics and filetables.</p>
<p>I&#8217;ll post the code <del datetime="2012-07-06T09:44:24+00:00">and slides</del> soon after the presentation. <em>I decided to <strong>drop</strong> (oh the irony) the slides.</em></p>
<p>Anyone close to Bucharest is more than welcome to come! Details can be found <a href="http://ronua.ro/CS/groups/ronua-bucuresti/default.aspx">here</a>.</p>
<p>The opening of the evening will be made by <a href="http://alexpeta.ro/">Alex Peta</a>, <a href="http://www.alexpeta.ro/article/presenting-a-asp-mvc-user-notification-widget-at-ronua/">presenting</a> a cool <a href="https://notificationswidget.codeplex.com/">notification system</a> built upon JS and ASP.NET MVC 3.</p>
<img src="http://feeds.feedburner.com/~r/Andrei-Rinea/~4/MeamFGUOWdw" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.andrei.rinea.ro/2012/07/02/sql-server-2012-local-talk/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://blog.andrei.rinea.ro/2012/07/02/sql-server-2012-local-talk/?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=sql-server-2012-local-talk</feedburner:origLink></item>
		<item>
		<title>Character test utility</title>
		<link>http://feedproxy.google.com/~r/Andrei-Rinea/~3/g6tP410nVtA/</link>
		<comments>http://blog.andrei.rinea.ro/2012/06/15/character-test-utility/#comments</comments>
		<pubDate>Fri, 15 Jun 2012 07:57:42 +0000</pubDate>
		<dc:creator>Andrei Rinea</dc:creator>
				<category><![CDATA[CodeProject]]></category>
		<category><![CDATA[Utility]]></category>
		<category><![CDATA[char]]></category>
		<category><![CDATA[IsControl]]></category>
		<category><![CDATA[IsDigit]]></category>
		<category><![CDATA[IsHighSurrogate]]></category>
		<category><![CDATA[IsLetter]]></category>
		<category><![CDATA[IsLetterOrDigit]]></category>
		<category><![CDATA[IsLower]]></category>
		<category><![CDATA[IsLowSurrogate]]></category>
		<category><![CDATA[IsNumber]]></category>
		<category><![CDATA[IsPunctuation]]></category>
		<category><![CDATA[IsSeparator]]></category>
		<category><![CDATA[IsSurrogate]]></category>
		<category><![CDATA[IsSymbol]]></category>
		<category><![CDATA[IsUpper]]></category>
		<category><![CDATA[IsWhiteSpace]]></category>

		<guid isPermaLink="false">http://blog.andrei.rinea.ro/?p=132</guid>
		<description><![CDATA[Every now and then I have to decide if a character satisfies a predicate (char.IsPunctuation, char.IsSymbol and so on) found on the System.Char class. The MSDN pages are of limited help plus I need to browse each predicate. Therefore I &#8230;<p class="read-more"><a href="http://blog.andrei.rinea.ro/2012/06/15/character-test-utility/">Read more &#187;</a></p>]]></description>
			<content:encoded><![CDATA[<div class="google_plusone_widget"><g:plusone 
      count="true" href="http://blog.andrei.rinea.ro/2012/06/15/character-test-utility/" size="tall"></g:plusone></div><p>Every now and then I have to decide if a character satisfies a predicate (char.IsPunctuation, char.IsSymbol and so on) found on the System.Char class. The MSDN pages are of limited help plus I need to browse each predicate. Therefore I wrote a small piece of code that, aside from the fact that it&#8217;s quite simple and has nothing spectacular, tests a set of characters through all these predicates.</p>
<p>Basically this is a reference for me, in order to avoid rewriting this over and over again, but since it could be helpful to others too I decided to publish it here.</p>
<pre class="brush: csharp; title: ; notranslate">

using System;
using System.Linq;

namespace CharTest
{
    internal class Program
    {
        static void Main()
        {
            var charPredicates = new Predicate&lt;char&gt;[]
            {
                char.IsControl,
                char.IsDigit,
                char.IsHighSurrogate,
                char.IsLetter,
                char.IsLetterOrDigit,
                char.IsLowSurrogate,
                char.IsLower,
                char.IsNumber,
                char.IsPunctuation,
                char.IsSeparator,
                char.IsSurrogate,
                char.IsSymbol,
                char.IsUpper,
                char.IsWhiteSpace
            };

            Console.WriteLine(&quot;Enter an empty line to exit&quot;);
            Console.WriteLine();
            Console.WriteLine();

            string line;
            do
            {
                line = Console.ReadLine();
                var chars = line.Distinct().ToArray();
                for (var i = 0; i &lt; chars.Count(); i++)
                {
                    var ch = chars[i];
                    Console.WriteLine();
                    Console.WriteLine(&quot;Distinct character &quot; + (i + 1) + &quot; : '&quot; + ch + &quot;'&quot;);
                    Console.WriteLine(&quot;-----------------------------------------&quot;);
                    foreach (var predicate in charPredicates)
                    {

                        Console.Write(predicate.Method.Name);
                        Console.SetCursorPosition(20, Console.CursorTop);
                        Console.WriteLine(predicate(ch));
                    }
                }
            }
            while (line != &quot;&quot;);
        }
    }
}
</pre>
<img src="http://feeds.feedburner.com/~r/Andrei-Rinea/~4/g6tP410nVtA" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.andrei.rinea.ro/2012/06/15/character-test-utility/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://blog.andrei.rinea.ro/2012/06/15/character-test-utility/?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=character-test-utility</feedburner:origLink></item>
		<item>
		<title>The monthly WTF : You will execute</title>
		<link>http://feedproxy.google.com/~r/Andrei-Rinea/~3/ej_Mjak_U40/</link>
		<comments>http://blog.andrei.rinea.ro/2012/06/06/the-monthly-wtf-you-will-execute/#comments</comments>
		<pubDate>Wed, 06 Jun 2012 09:51:04 +0000</pubDate>
		<dc:creator>Andrei Rinea</dc:creator>
				<category><![CDATA[The monthly WTF]]></category>
		<category><![CDATA[CanExecute]]></category>
		<category><![CDATA[conditional]]></category>
		<category><![CDATA[if]]></category>
		<category><![CDATA[mvvm]]></category>
		<category><![CDATA[wpf]]></category>

		<guid isPermaLink="false">http://blog.andrei.rinea.ro/?p=129</guid>
		<description><![CDATA[As I wander free upon the large fields of code in this world I sometimes come upon interesting things. The wonder, the joy, the mysteries that I encounter I must share with all of you, otherwise it would be selfish &#8230;<p class="read-more"><a href="http://blog.andrei.rinea.ro/2012/06/06/the-monthly-wtf-you-will-execute/">Read more &#187;</a></p>]]></description>
			<content:encoded><![CDATA[<div class="google_plusone_widget"><g:plusone 
      count="true" href="http://blog.andrei.rinea.ro/2012/06/06/the-monthly-wtf-you-will-execute/" size="tall"></g:plusone></div><p>As I wander free upon the large fields of code in this world I sometimes come upon interesting things. The wonder, the joy, the mysteries that I encounter I must share with all of you, otherwise it would be selfish of me.</p>
<p>I will, therefore, start a series (it surely will be a series) of such posts called &#8220;The monthly WTF&#8221;. </p>
<p>Today I present you :</p>
<pre class="brush: csharp; title: ; notranslate">
        private static void CanWhatever(object sender, CanExecuteRoutedEventArgs e)
        {
            if (SomeString.IsNotNullOrEmpty())
            {
                if (Repo.AllowSingleSignOn)
                {
                    e.CanExecute = false;
                }
            }
            e.CanExecute = true;
        }
</pre>
<p>Notice anything special?</p>
<img src="http://feeds.feedburner.com/~r/Andrei-Rinea/~4/ej_Mjak_U40" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.andrei.rinea.ro/2012/06/06/the-monthly-wtf-you-will-execute/feed/</wfw:commentRss>
		<slash:comments>16</slash:comments>
		<feedburner:origLink>http://blog.andrei.rinea.ro/2012/06/06/the-monthly-wtf-you-will-execute/?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=the-monthly-wtf-you-will-execute</feedburner:origLink></item>
		<item>
		<title>WPF default binding format culture</title>
		<link>http://feedproxy.google.com/~r/Andrei-Rinea/~3/dRkEgfxkFH0/</link>
		<comments>http://blog.andrei.rinea.ro/2012/05/30/wpf-default-binding-format-culture/#comments</comments>
		<pubDate>Wed, 30 May 2012 12:07:29 +0000</pubDate>
		<dc:creator>Andrei Rinea</dc:creator>
				<category><![CDATA[CodeProject]]></category>
		<category><![CDATA[WPF]]></category>
		<category><![CDATA[binding]]></category>
		<category><![CDATA[format]]></category>
		<category><![CDATA[i18n]]></category>
		<category><![CDATA[localization]]></category>
		<category><![CDATA[mvvm]]></category>
		<category><![CDATA[wpf]]></category>

		<guid isPermaLink="false">http://blog.andrei.rinea.ro/?p=119</guid>
		<description><![CDATA[WPF formats non-string objects to a string using a fixed/hardcoded culture (en-US) regardless of the current culture (as in Thread.CurrentThread.CurrentCulture / CultureInfo.CurrentCulture). Suppose you have a simple DataContext (ViewModel) like so : Binding an instance of `Data` to a view, &#8230;<p class="read-more"><a href="http://blog.andrei.rinea.ro/2012/05/30/wpf-default-binding-format-culture/">Read more &#187;</a></p>]]></description>
			<content:encoded><![CDATA[<div class="google_plusone_widget"><g:plusone 
      count="true" href="http://blog.andrei.rinea.ro/2012/05/30/wpf-default-binding-format-culture/" size="tall"></g:plusone></div><p>WPF formats non-string objects to a string using a fixed/hardcoded culture (en-US) regardless of the current culture (as in Thread.CurrentThread.CurrentCulture / CultureInfo.CurrentCulture).</p>
<p>Suppose you have a simple DataContext (ViewModel) like so :</p>
<pre class="brush: csharp; title: ; notranslate">
public class Data
{
    public DateTime Now
    {
        get
        {
             return DateTime.Now;
        }
    }

    public string NowText
    {
        get
        {
              return DateTime.Now.ToString();
        }
    }
}
</pre>
<p>Binding an instance of `Data` to a view, with two TextBlocks each of which using &#8216;Now&#8217; and &#8216;NowText&#8217; respectively will yield different results if your CurrentCulture is NOT en-US.</p>
<p>Working on an internationalizable WPF app I&#8217;ve found out this sad truth. I don&#8217;t fully understand why this happens but I&#8217;ve found a way to &#8220;fix it&#8221;.</p>
<p>Somewhere before any piece of UI is shown on the screen (for example in App.xaml.cs in ApplicationStartup) just place this little piece of code :</p>
<pre class="brush: csharp; title: ; notranslate">
FrameworkElement.LanguageProperty.OverrideMetadata(
  typeof(FrameworkElement),
  new FrameworkPropertyMetadata(XmlLanguage.GetLanguage(CultureInfo.CurrentCulture.IetfLanguageTag)));
</pre>
<p>It sets for any FrameworkElement (TextBlock and Label are included) the formatting culture to the current culture. Of course you might need to change it again if the current culture changes (for example an on-the-fly UI language changes).</p>
<img src="http://feeds.feedburner.com/~r/Andrei-Rinea/~4/dRkEgfxkFH0" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.andrei.rinea.ro/2012/05/30/wpf-default-binding-format-culture/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://blog.andrei.rinea.ro/2012/05/30/wpf-default-binding-format-culture/?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=wpf-default-binding-format-culture</feedburner:origLink></item>
		<item>
		<title>How to deal with unwanted LinkedIn invites</title>
		<link>http://feedproxy.google.com/~r/Andrei-Rinea/~3/hCMertvHfIo/</link>
		<comments>http://blog.andrei.rinea.ro/2012/05/07/how-to-deal-with-unwanted-linkedin-invites/#comments</comments>
		<pubDate>Mon, 07 May 2012 15:22:24 +0000</pubDate>
		<dc:creator>Andrei Rinea</dc:creator>
				<category><![CDATA[Recruitment]]></category>
		<category><![CDATA[hr]]></category>
		<category><![CDATA[it]]></category>
		<category><![CDATA[LinkedIn]]></category>
		<category><![CDATA[recruitment]]></category>
		<category><![CDATA[report]]></category>
		<category><![CDATA[spam]]></category>
		<category><![CDATA[strategy]]></category>

		<guid isPermaLink="false">http://blog.andrei.rinea.ro/?p=109</guid>
		<description><![CDATA[How many of haven&#8217;t received unwanted LinkedIn invites from people that claim to know you, been colleagues and you haven&#8217;t even heard of? Like&#8230; so : or like so : Don&#8217;t be fooled, they&#8217;re just trying to get their recruitment &#8230;<p class="read-more"><a href="http://blog.andrei.rinea.ro/2012/05/07/how-to-deal-with-unwanted-linkedin-invites/">Read more &#187;</a></p>]]></description>
			<content:encoded><![CDATA[<div class="google_plusone_widget"><g:plusone 
      count="true" href="http://blog.andrei.rinea.ro/2012/05/07/how-to-deal-with-unwanted-linkedin-invites/" size="tall"></g:plusone></div><p>How many of haven&#8217;t received unwanted LinkedIn invites from people that claim to know you, been colleagues and you haven&#8217;t even heard of?</p>
<p>Like&#8230; so :</p>
<p><img class="size-full wp-image-110" title="linkedinspam1" src="http://blog.andrei.rinea.ro/wp-content/uploads/2012/05/linkedinspam1.png" alt="" width="539" height="240" /></p>
<p>or like so :</p>
<p><img class="size-full wp-image-110" title="linkedinspam1" src="http://blog.andrei.rinea.ro/wp-content/uploads/2012/05/linkedinspam2.png" alt="" /></p>
<p>Don&#8217;t be fooled, they&#8217;re just trying to get their recruitment bonus. The right choice? The &#8220;REPORT SPAM&#8221; button up above. Press it. They deserve it. The correct way would have been a private message but it&#8217;s more useful for the recruiters to add a new contact since they may need to contact him/her again.</p>
<img src="http://feeds.feedburner.com/~r/Andrei-Rinea/~4/hCMertvHfIo" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.andrei.rinea.ro/2012/05/07/how-to-deal-with-unwanted-linkedin-invites/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		<feedburner:origLink>http://blog.andrei.rinea.ro/2012/05/07/how-to-deal-with-unwanted-linkedin-invites/?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=how-to-deal-with-unwanted-linkedin-invites</feedburner:origLink></item>
		<item>
		<title>Back to basics – object equality</title>
		<link>http://feedproxy.google.com/~r/Andrei-Rinea/~3/rlXghKYXNvA/</link>
		<comments>http://blog.andrei.rinea.ro/2012/04/05/back-to-basics-object-equality/#comments</comments>
		<pubDate>Thu, 05 Apr 2012 12:31:44 +0000</pubDate>
		<dc:creator>Andrei Rinea</dc:creator>
				<category><![CDATA[Basics]]></category>
		<category><![CDATA[CodeProject]]></category>
		<category><![CDATA[boxing]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[equals]]></category>
		<category><![CDATA[referenceequals]]></category>
		<category><![CDATA[ReSharper]]></category>
		<category><![CDATA[unboxing]]></category>

		<guid isPermaLink="false">http://blog.andrei.rinea.ro/?p=103</guid>
		<description><![CDATA[What do you think this piece of code will output? I won&#8217;t be like others and ask you not to run the code. Run the code if you feel like it. I&#8217;ll wait here. &#8230; Back already? Surprised? I surely &#8230;<p class="read-more"><a href="http://blog.andrei.rinea.ro/2012/04/05/back-to-basics-object-equality/">Read more &#187;</a></p>]]></description>
			<content:encoded><![CDATA[<div class="google_plusone_widget"><g:plusone 
      count="true" href="http://blog.andrei.rinea.ro/2012/04/05/back-to-basics-object-equality/" size="tall"></g:plusone></div><p>What do you think this piece of code will output?</p>
<pre class="brush: csharp; title: ; notranslate">
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(GetValue() == (object)true);
            Console.WriteLine(object.Equals(GetValue(), true));
        }

        static object GetValue()
        {
            return true;
        }
    }
</pre>
<p>I won&#8217;t be like others and ask you not to run the code. Run the code if you feel like it. I&#8217;ll wait here.</p>
<p>&#8230;</p>
<p>Back already? Surprised?<br />
I surely have been.. I&#8217;ve found a piece of code similar to this as I was cleaning up code in our repository. You have a method that is required to return object (as in <a href="http://msdn.microsoft.com/en-us/library/system.object.aspx">System.Object</a>) and you want to check if, <a href="http://msdn.microsoft.com/en-us/library/yz2be5wk.aspx">unboxed</a>, it holds the value of true (or not).</p>
<p>Why exactly does </p>
<pre class="brush: csharp; title: ; notranslate">
    GetValue() == (object)true
</pre>
<p>return false considering that GetValue() returns always a true value? Well&#8230; because you are comparing two instances of a <a href="http://msdn.microsoft.com/en-us/library/system.object.aspx">System.Object</a> and the &#8216;==&#8217; operator is coded in a way that uses the <a href="http://msdn.microsoft.com/en-us/library/system.object.referenceequals.aspx">ReferenceEquals</a> (and not <a href="http://msdn.microsoft.com/en-us/library/bsc2ak47.aspx">Equals</a>) method on <a href="http://msdn.microsoft.com/en-us/library/system.object.aspx">System.Object</a>.</p>
<p>The author could have unboxed it to a local variable and do the check after but the speed of coding is so much important for some of us.. Thank you <a href="http://www.jetbrains.com/resharper/">ReSharper</a> for pointing this to us and fixing a potentially subtle bug.</p>
<img src="http://feeds.feedburner.com/~r/Andrei-Rinea/~4/rlXghKYXNvA" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.andrei.rinea.ro/2012/04/05/back-to-basics-object-equality/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://blog.andrei.rinea.ro/2012/04/05/back-to-basics-object-equality/?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=back-to-basics-object-equality</feedburner:origLink></item>
		<item>
		<title>How not to build an online flight booking site</title>
		<link>http://feedproxy.google.com/~r/Andrei-Rinea/~3/F3liBa3YSVs/</link>
		<comments>http://blog.andrei.rinea.ro/2012/04/03/how-not-to-build-an-online-flight-booking-site/#comments</comments>
		<pubDate>Tue, 03 Apr 2012 15:45:23 +0000</pubDate>
		<dc:creator>Andrei Rinea</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[absolute-expiration]]></category>
		<category><![CDATA[architecture]]></category>
		<category><![CDATA[banking]]></category>
		<category><![CDATA[fail]]></category>
		<category><![CDATA[session]]></category>
		<category><![CDATA[TAROM]]></category>
		<category><![CDATA[wtf]]></category>

		<guid isPermaLink="false">http://blog.andrei.rinea.ro/?p=92</guid>
		<description><![CDATA[I had a rough experience a few days ago while trying to book a flight for my upcoming holiday. I &#8230; no, we, chose TAROM (site link here). What happened, in short, I started to book the flight, filled-in all &#8230;<p class="read-more"><a href="http://blog.andrei.rinea.ro/2012/04/03/how-not-to-build-an-online-flight-booking-site/">Read more &#187;</a></p>]]></description>
			<content:encoded><![CDATA[<div class="google_plusone_widget"><g:plusone 
      count="true" href="http://blog.andrei.rinea.ro/2012/04/03/how-not-to-build-an-online-flight-booking-site/" size="tall"></g:plusone></div><p>I had a rough experience a few days ago while trying to book a flight for my upcoming holiday. I &#8230; no, we, chose <a href="http://en.wikipedia.org/wiki/Tarom">TAROM</a> (site link <a href="http://www.tarom.ro/en/">here</a>).</p>
<p>What happened, in short, I started to book the flight, filled-in all the flight details, got to the point where I need to provide the billing details (card number etc.), pressed next and then&#8230; &#8220;session expired, please start over again&#8221;. For a moment I checked my bank account. Sure enough they took the money and offered me just an error. No email, no nothing.</p>
<p>After 1 hour and something, I finally got to customer service representative who manually issued the tickets which couldn&#8217;t have been issued by the site. (Meanwhile I found out how hard is to cancel a payment from your bank to a rogue vendor).</p>
<p>In the end things got fixed but a bitter taste persists towards this TAROM operator. Anyway I tried to understand what went wrong in the process, IT-wise and this is what happened, I think :</p>
<ol>
<li>The site gathered all the flight details from the <del datetime="2012-04-03T13:45:42+00:00">sucker</del> customer (me)</li>
<li>The site then asked for the billing info</li>
<li>Tried to bill me and succeeded</li>
<li>Tried to book the flight and failed (the session expired in the meanwhile)</li>
</ol>
<p>From this short analysis a few WTFs have emerged :</p>
<ul>
<li>Why did they chose to have an absolute-date expiration policy for the session? (i.e. the session expires precisely 10 minutes after you start the booking process, no matter how many or how frequent you do further requests</li>
<li>Why didn&#8217;t they leave the billing step as the final step?</li>
</ul>
<p>Having had to put up with Romanian services for the last three decades I&#8217;ve learnt that the most probable reason for these WTFs is this : </p>
<p><img src="http://blog.andrei.rinea.ro/wp-content/uploads/2012/04/why-because-fuck-you-that-s-why.jpg" alt="Why? Because FUCK YOU! that's why.." title="Why? Because FUCK YOU! that's why.." width="453" height="604" /></p>
<p>Leaving the funny thing aside I suppose the &#8216;architects&#8217; that built TAROM&#8217;s site (hope the plane doesn&#8217;t crash like the site) thought that it&#8217;s better to have the money in the bag and then see if all else went ok&#8230; or maybe they thought of a situation where many people would try to book few tickets? Or who knows&#8230;</p>
<p><strong><em>What do you think dear reader?</em></strong></p>
<img src="http://feeds.feedburner.com/~r/Andrei-Rinea/~4/F3liBa3YSVs" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.andrei.rinea.ro/2012/04/03/how-not-to-build-an-online-flight-booking-site/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://blog.andrei.rinea.ro/2012/04/03/how-not-to-build-an-online-flight-booking-site/?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=how-not-to-build-an-online-flight-booking-site</feedburner:origLink></item>
		<item>
		<title>Benchmark code blocks easy</title>
		<link>http://feedproxy.google.com/~r/Andrei-Rinea/~3/hQZD1Ac22Z4/</link>
		<comments>http://blog.andrei.rinea.ro/2012/03/15/benchmark-code-blocks-easy/#comments</comments>
		<pubDate>Thu, 15 Mar 2012 16:20:17 +0000</pubDate>
		<dc:creator>Andrei Rinea</dc:creator>
				<category><![CDATA[CodeProject]]></category>
		<category><![CDATA[Performance]]></category>
		<category><![CDATA[benchmark]]></category>
		<category><![CDATA[Benchmark.NET]]></category>
		<category><![CDATA[Codeplex]]></category>
		<category><![CDATA[open-source]]></category>
		<category><![CDATA[performance]]></category>
		<category><![CDATA[Stopwatch]]></category>

		<guid isPermaLink="false">http://blog.andrei.rinea.ro/?p=79</guid>
		<description><![CDATA[Have you been testing code speed like this? Or maybe you&#8217;ve found the Stopwatch class and been happy with its superior time precision? Better, I&#8217;d say, but I&#8217;ve quite had it. Plus I needed to benchmark a local website and &#8230;<p class="read-more"><a href="http://blog.andrei.rinea.ro/2012/03/15/benchmark-code-blocks-easy/">Read more &#187;</a></p>]]></description>
			<content:encoded><![CDATA[<div class="google_plusone_widget"><g:plusone 
      count="true" href="http://blog.andrei.rinea.ro/2012/03/15/benchmark-code-blocks-easy/" size="tall"></g:plusone></div><p>Have you been testing code speed like this?</p>
<pre class="brush: csharp; title: ; notranslate">

var start = DateTime.Now;
int i;
for(i = 0; i &lt; 1000; i++)
{
    DoSomething();
}
var stop = DateTime.Now;
var total = stop - start;
var timePerIteration = total.Ticks / i;
</pre>
<p>Or maybe you&#8217;ve found <a href="http://msdn.microsoft.com/en-us/library/system.diagnostics.stopwatch.aspx">the Stopwatch class</a> and been happy with its superior time precision?</p>
<p>Better, I&#8217;d say, but I&#8217;ve quite had it. Plus I needed to benchmark a local website and needed to test parallel requests (something similar to <a href="http://en.wikipedia.org/wiki/ApacheBench">ab &#8211; ApacheBench</a>)</p>
<p>What does a programmer in such a case? Writes his own tools! <img src='http://blog.andrei.rinea.ro/wp-includes/images/smilies/icon_razz.gif' alt=':P' class='wp-smiley' />  That&#8217;s how <a href="http://benchmarknet.codeplex.com">BenchmarkNET</a> appeared. Using BenchmarkNET you can write the same thing as above only much shorter and with a better timing precision :</p>
<pre class="brush: csharp; title: ; notranslate">
var result = Benchmark.Sequentially(() =&gt; DoSomething(), 1000);
</pre>
<p>Neat? That&#8217;s not all. The result can easily printed out to a console or inspected with a debugger :</p>
<p><a href="http://blog.andrei.rinea.ro/wp-content/uploads/2012/03/benchmark.png"><img class="alignleft size-full wp-image-82" title="benchmark" src="http://blog.andrei.rinea.ro/wp-content/uploads/2012/03/benchmark.png" alt="" width="678" height="69" /></a></p>
<p>Benchmarking an HTTP operation over 10 parallel threads, 100 times for each thread?</p>
<pre class="brush: csharp; title: ; notranslate">
var dl2 = Benchmark.Parallel(new BenchmarkParams&lt;WebClient&gt;(c =&gt; c.DownloadString(&quot;http://localhost/&quot;), 100), 10, () =&gt; new WebClient());
</pre>
<p>The project has been published as open source (LGPL license) on <a href="http://benchmarknet.codeplex.com/">CodePlex</a>. You can <a href="http://benchmarknet.codeplex.com/discussions">discuss it</a>, <a href="http://benchmarknet.codeplex.com/workitem/list/basic">file bugs</a>, or even <a href="http://benchmarknet.codeplex.com/team/view">contribute to it</a>.</p>
<p>Have fun and if you test it out, please leave some feedback!</p>
<p><strong>Later edit</strong> : It seems <a href="http://alexpeta.ro/article/y-u-no-test-speed-code-with-benchmarknet/">some people already dig it</a> <img src='http://blog.andrei.rinea.ro/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
<img src="http://feeds.feedburner.com/~r/Andrei-Rinea/~4/hQZD1Ac22Z4" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.andrei.rinea.ro/2012/03/15/benchmark-code-blocks-easy/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		<feedburner:origLink>http://blog.andrei.rinea.ro/2012/03/15/benchmark-code-blocks-easy/?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=benchmark-code-blocks-easy</feedburner:origLink></item>
		<item>
		<title>Random performance findings</title>
		<link>http://feedproxy.google.com/~r/Andrei-Rinea/~3/B3onYkTOi24/</link>
		<comments>http://blog.andrei.rinea.ro/2011/12/13/random-performance-findings/#comments</comments>
		<pubDate>Tue, 13 Dec 2011 20:10:16 +0000</pubDate>
		<dc:creator>Andrei Rinea</dc:creator>
				<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[CodeProject]]></category>
		<category><![CDATA[WCF]]></category>
		<category><![CDATA[ashx]]></category>
		<category><![CDATA[asp.net]]></category>
		<category><![CDATA[basicHttpBinding]]></category>
		<category><![CDATA[benchmark]]></category>
		<category><![CDATA[debug]]></category>
		<category><![CDATA[handler]]></category>
		<category><![CDATA[iis]]></category>
		<category><![CDATA[iis-express]]></category>
		<category><![CDATA[performance]]></category>
		<category><![CDATA[release]]></category>
		<category><![CDATA[sql server]]></category>
		<category><![CDATA[StackOverflow]]></category>
		<category><![CDATA[wcf]]></category>

		<guid isPermaLink="false">http://blog.andrei.rinea.ro/?p=61</guid>
		<description><![CDATA[TL;DR version : Upon a curiosity of mine I found out that WCF with basicHttpBinding can be easily beaten (performance-wise) by plain-old ASP.NET even if stripped down of transactions, reliability, security etc. (1500 req/sec vs  800 req/sec) Also SQL Server &#8230;<p class="read-more"><a href="http://blog.andrei.rinea.ro/2011/12/13/random-performance-findings/">Read more &#187;</a></p>]]></description>
			<content:encoded><![CDATA[<div class="google_plusone_widget"><g:plusone 
      count="true" href="http://blog.andrei.rinea.ro/2011/12/13/random-performance-findings/" size="tall"></g:plusone></div><p><strong>TL;DR version :</strong></p>
<p>Upon a curiosity of mine I found out that WCF with basicHttpBinding can be easily beaten (performance-wise) by plain-old ASP.NET even if stripped down of transactions, reliability, security etc. (1500 req/sec vs  800 req/sec)</p>
<p>Also SQL Server Express can handle 1300 inserts per second easily and up to 4300 queries per second just as well. This on a 6+ million rows table and stored on the hard disk not in RAM.</p>
<p><strong>Long version :</strong></p>
<p>A few days ago I was thinking how I implemented a certain web service a few years ago, a few employers ago. Although it was quite fast and efficient it wasn&#8217;t scalable. I, then, thought how I should have implemented it.</p>
<p>The web service had to receive an incoming (public) HTTP request, check for a visitor cookie. If there was a visitor-identifying cookie it would check against a data store (in-memory dictionary at that time) to see if that visitor answered.</p>
<p>It was about inviting visitors of certain sites to an on-line survey. A new visitor would be presented with a pop-up box having a &#8220;yes&#8221;, a &#8220;no&#8221; and &#8220;X&#8221; (close) button.</p>
<p>The business rules stated that if the visitor answered yes, the answer would be stored, the pop-up would close and then a new tab/window would appear with the survey. If the visitor answered no, then the same things would happen except opening the survey. If the visitor closed the pop-up, the next time the pop-up would appear again. If the visitor closed three times the pop-up then (s)he wouldn&#8217;t be bothered anymore with the invitation.</p>
<p><span id="more-61"></span></p>
<p>Quite simple I&#8217;d say. The tough thing was we only had one machine available (a quad-core Xeon 3.5 GHz 4GB RAM) and the expected traffic was 300-400 req/sec during normal load and maybe a peak load of 800-1000 req/sec. In that situation I decided to use a simple in-memory dictionary as data-store that I&#8217;d backup to disk a few times per hour. Things went smooth (at least till I left the company but also after I left, as an ex-colleague of mine told me).</p>
<p>You can easily see that this architecture, although efficient, is not scalable. At least not if you <a href="http://en.wikipedia.org/wiki/Scalability#Scale_horizontally_.28scale_out.29">scale out</a> I personally find efficiency and the ability to scale out completely independent.</p>
<p>So how would I reimplement this (if I would) in a scalable manner? Balancing and scaling the front-facing web servers would be straight-forward : a simple hardware NLB (network</p>
<p>load balancer) in front of n web servers and that&#8217;s that. In the back there would be m storage servers that would just store the visitors&#8217; responses and server query responses</p>
<p>to the web servers. Having naturally partitionable data such as this (especially because it is not inter-related) makes the &#8220;<a href="http://en.wikipedia.org/wiki/Sharding">sharding</a>&#8221; easy.</p>
<p>My questions that arise are :</p>
<ol>
<li><em><strong>What type of communication should I employ between the web servers and the storage servers?</strong></em></li>
<li><em><strong>What type of storage should I use on the storage servers?</strong></em></li>
</ol>
<p>For communication I tested and benchmarked WCF (with basicHttpBinding) hosted in IIS and a simple ASP.NET Generic handler (.ashx thingie) in an empty web application. As for the storage I only tested SQL Server 2008 R2 Express with a database stored on the hard disk (I fancied using MySql with an in-memory storage engine or SQL Server with a database stored on a ram disk, and a periodic backup on a hard disk). However the test results on a standard DB on SQL Server satisfied me and I didn&#8217;t need to go any further.</p>
<p>A few words on the machine I used for testing : my el-cheapo laptop : a two-year old, AMD dual core with 3GB of RAM with Windows 7 Ultimate 64 bit. (<a href="http://www.techsmart.co.za/hardware/notebook_and_tablet_pcs/Compaq_615_techspecs.html">complete specs here</a>)</p>
<p>I started testing communication options. I set up a WCF service hosted in IIS Express, with minimal features, intended to max out performance (no security, singleton service instance, multiple concurrent calls, 1000 max concurrent connections and so on). I then made a small console app that would set up 10 threads that each of them would sequentially make 1,000 calls to the service and measure the whole time.</p>
<p style="padding-left: 30px;">10 x 1,000 calls completed in <strong>60 seconds [170 req/sec]</strong>. Like lame, dude..</p>
<p>Then I thrown up a small, empty web application with just one generic handler which could be queried a bit like so : http://localhost:1234/GetData.ashx?id=39283&amp;opId=1 and it would only send out a single byte that would be the user state.</p>
<p style="padding-left: 30px;">10 x 1,000 calls completed in <strong>15 seconds [670 req/sec]</strong>.</p>
<p>Wow, quite a different set of results&#8230; I then went out to turn to the community to find out how to improve the WCF service and <a href="http://stackoverflow.com/q/8460013/1796">I asked this on stackoverflow</a>. Not much help there (at least at the time of this writing). I then set both web apps on IIS (full not express) 7.5 and turned compilation to release in all projects (wcf web app, asp.net web app and the test harness project). Things changed &#8220;a bit&#8221; :</p>
<p style="padding-left: 30px;">ASP.NET Generic handler : <strong>6.7 sec [1492 req/sec]</strong><br />
WCF service : <strong>13.7 sec [730 req/sec]</strong></p>
<p>Good enough I said to myself, since, in the end, you could easily scale them out. Then I went to see how the DB would stand up to this beating. At first I was quite pesimist about an RDBMS with the backing store on the HDD (no RAID 0, no nothing) &#8211; a 7200 rpm laptop hard-drive.</p>
<p>Starting from an empty table (Id &#8211; bigint &#8211; 64 bit, Response &#8211; tinyint &#8211; 8 bit) I started to insert sequentially (over the same connection, unclosed) 6 million rows. At first the table had a clustered index on the Id column slowing down the inserts. From 0 to the first 100,000th record it inserted at an approximate rate of 1500 rows/sec and then went down and down asymptotically until I got bored and stopped it (at around 3.5 million rows).</p>
<p>Then I truncated the table, removed the clustered index and I was able to insert consistently (again, sequentially on a single connection) at <strong>1250 rows/sec</strong>. For kicks I truncated the table again (use TRUNCATE rather than DELETE TABLE because it&#8217;s way faster and cleaner) and used BULK INSERT just as in <a href="http://blog.sqlauthority.com/2008/02/06/sql-server-import-csv-file-into-sql-server-using-bulk-insert-load-comma-delimited-file-into-sql-server/">Dave&#8217;s article</a> and got something like <strong>58,000 rows/second</strong>!!!</p>
<p>Being satisfied with the findings I got to test the query performance. I used a 6 million rows content for the table and tested with a clustered index and got around <strong>4.291 queries per second</strong>!!! while without an index the table scan ruined the performance to <strong>1 (one) query per second</strong>. Adding back the index to the indexless table took <strong>21 seconds</strong>. Decent, I&#8217;d say.</p>
<p>In the end I had one more &#8220;What if&#8221; question on the top of my head : What if instead of a bigint (Int64, long , however you call it) I would have a normal int (32 bits)? For 6 million generated visitorIds how many collisions I&#8217;d get? And by collision I mean something simillar to <a href="http://en.wikipedia.org/wiki/Hash_collision">hash collisions</a>. I got <strong>11,000</strong> for 6,000,000 (<strong>0.1%</strong>). Acceptable for the business case. Generating long (64 bit) Ids would not generate any collision.</p>
<p>&nbsp;</p>
<p><span style="text-decoration: underline;"><strong>Conclusion :</strong></span> You can safely use WCF with SQL Server and still get decent performance. If you really need and want to tweak the performance you can use other solutions (generic handlers, in-memory dictionaries or memory-backed DBMS&#8217;es or even NoSQL solutions) but they will be harder to design, implement, deploy and maintain. So start simple and then find your way.</p>
<p>http://en.wikipedia.org/wiki/Hash_collision</p>
<img src="http://feeds.feedburner.com/~r/Andrei-Rinea/~4/B3onYkTOi24" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.andrei.rinea.ro/2011/12/13/random-performance-findings/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		<feedburner:origLink>http://blog.andrei.rinea.ro/2011/12/13/random-performance-findings/?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=random-performance-findings</feedburner:origLink></item>
		<item>
		<title>WCF Streaming – slides and code</title>
		<link>http://feedproxy.google.com/~r/Andrei-Rinea/~3/cO50QSFCyjQ/</link>
		<comments>http://blog.andrei.rinea.ro/2011/11/26/wcf-streaming-slides-and-code/#comments</comments>
		<pubDate>Sat, 26 Nov 2011 15:53:15 +0000</pubDate>
		<dc:creator>Andrei Rinea</dc:creator>
				<category><![CDATA[CodeProject]]></category>
		<category><![CDATA[Presentations]]></category>
		<category><![CDATA[WCF]]></category>
		<category><![CDATA[cassini]]></category>
		<category><![CDATA[iis-express]]></category>
		<category><![CDATA[messagebodymember]]></category>
		<category><![CDATA[MessageContract]]></category>
		<category><![CDATA[messageheader]]></category>
		<category><![CDATA[operationcontract]]></category>
		<category><![CDATA[servicecontract]]></category>
		<category><![CDATA[streaming]]></category>
		<category><![CDATA[wcf]]></category>

		<guid isPermaLink="false">http://blog.andrei.rinea.ro/2011/11/26/wcf-streaming/</guid>
		<description><![CDATA[I held a presentation about WCF Streaming last Saturday, November 26th, at Microsoft HQ Bucharest. I illustrated WCF Streaming in a small client/server application which was supposed to (and in the end implemented it all) : Show all files available &#8230;<p class="read-more"><a href="http://blog.andrei.rinea.ro/2011/11/26/wcf-streaming-slides-and-code/">Read more &#187;</a></p>]]></description>
			<content:encoded><![CDATA[<div class="google_plusone_widget"><g:plusone 
      count="true" href="http://blog.andrei.rinea.ro/2011/11/26/wcf-streaming-slides-and-code/" size="tall"></g:plusone></div><p><a href="http://blog.andrei.rinea.ro/2011/11/15/it-community-meeting-codecamp-itspark/">I held a presentation about WCF Streaming last Saturday, November 26th, at Microsoft HQ Bucharest</a>. I illustrated WCF Streaming in a small client/server application which was supposed to (and in the end implemented it all) :</p>
<ul>
<li>Show all files available on the server in the client application</li>
<li>Allow the end user to upload a file (up to 2GB) to the server</li>
<li>Allow the user to download a file from the server</li>
<li>Display a progress bar that would update in real-time showing the progress of the current transfer (upload or download)</li>
<li>Allow the user to press the &#8220;Stop&#8221; button to stop the current transfer (upload or download)</li>
</ul>
<p>The code to achieve this in a simple (non-robust, not production quality etc.) manner is quite small : around 50 lines of code for the server and around 200 lines for the client. <strong>The WCF runtime takes care of the rest</strong>.</p>
<p>Points of interest (things for which I suffered and hopefully you won&#8217;t) :</p>
<ul>
<li>Cassini (ASP.NET Web development) server <a href="http://blog.andrei.rinea.ro/2011/11/07/cassini-and-wcf-streaming/">does not support streaming</a>, reports a cryptic (400 Bad request) error and <strong><em>it&#8217;s not documented at Microsoft</em></strong>!</li>
<li>It&#8217;s not enough at the server level to set the maxReceivedMessageSize at the binding element, you must also set it in the maxRequestLength attribute on the system.web/httpRuntime element if you host the service in a site.</li>
<li>Don&#8217;t try to define an operation with mixed types, that is, complex types that are decorated with MessageContract and any other types (including System.String). If one is MessageContract then all have to be. Found out the hard way, at runtime (not compile time)</li>
<li>In order to get the folder path for a WCF application you must use <a href="http://blog.andrei.rinea.ro/2011/11/08/wcf-service-local-path/">HostingEnvironment.GetApplicationPhysicalPath</a>.</li>
<li>In .NET 4 there is a CopyTo method on the Stream class which simplifies copying data from a stream to another.</li>
<li>Opt in for asynchronous method generation for the client-side WCF proxies</li>
</ul>
<p>You can find below the PowerPoint slides and the code archive attached to this post.</p>
<p><a href="http://blog.andrei.rinea.ro/wp-content/uploads/2011/11/WCF-Streaming.pptx">WCF Streaming &#8211; slides</a></p>
<p><a href="http://blog.andrei.rinea.ro/wp-content/uploads/2011/11/WCF-Streaming1.zip">WCF Streaming &#8211; the code</a></p>
<img src="http://feeds.feedburner.com/~r/Andrei-Rinea/~4/cO50QSFCyjQ" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.andrei.rinea.ro/2011/11/26/wcf-streaming-slides-and-code/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		<feedburner:origLink>http://blog.andrei.rinea.ro/2011/11/26/wcf-streaming-slides-and-code/?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=wcf-streaming-slides-and-code</feedburner:origLink></item>
		<item>
		<title>IT community meeting (CodeCamp &amp; ITSpark)</title>
		<link>http://feedproxy.google.com/~r/Andrei-Rinea/~3/N3xbtwj7rho/</link>
		<comments>http://blog.andrei.rinea.ro/2011/11/15/it-community-meeting-codecamp-itspark/#comments</comments>
		<pubDate>Tue, 15 Nov 2011 20:41:45 +0000</pubDate>
		<dc:creator>Andrei Rinea</dc:creator>
				<category><![CDATA[Presentations]]></category>
		<category><![CDATA[azure]]></category>
		<category><![CDATA[bucharest]]></category>
		<category><![CDATA[cristea]]></category>
		<category><![CDATA[dionisie]]></category>
		<category><![CDATA[ef]]></category>
		<category><![CDATA[hyper-v]]></category>
		<category><![CDATA[ignat]]></category>
		<category><![CDATA[lefter]]></category>
		<category><![CDATA[lync]]></category>
		<category><![CDATA[microsoft]]></category>
		<category><![CDATA[mvc]]></category>
		<category><![CDATA[nadas]]></category>
		<category><![CDATA[office-365]]></category>
		<category><![CDATA[roman]]></category>
		<category><![CDATA[rusu]]></category>
		<category><![CDATA[scvmm]]></category>
		<category><![CDATA[show]]></category>
		<category><![CDATA[sql]]></category>
		<category><![CDATA[wcf]]></category>
		<category><![CDATA[windows8]]></category>

		<guid isPermaLink="false">http://blog.andrei.rinea.ro/?p=47</guid>
		<description><![CDATA[Saturday, November 26th, there will be a session of presentations at Microsoft&#8217;s Bucharest Headquarters. Free entrance, drinks and lunch on the house. The event agenda : 09:30 &#8211; 10:00 Arrival 10:00 &#8211; 11:00 MVC / EF (Andrei Ignat) 11:00 &#8211; &#8230;<p class="read-more"><a href="http://blog.andrei.rinea.ro/2011/11/15/it-community-meeting-codecamp-itspark/">Read more &#187;</a></p>]]></description>
			<content:encoded><![CDATA[<div class="google_plusone_widget"><g:plusone 
      count="true" href="http://blog.andrei.rinea.ro/2011/11/15/it-community-meeting-codecamp-itspark/" size="tall"></g:plusone></div><p>Saturday, November 26th, there will be a session of presentations at Microsoft&#8217;s Bucharest Headquarters.</p>
<p>Free entrance, drinks and lunch on the house.</p>
<p>The event agenda :</p>
<ul>
<li>09:30 &#8211; 10:00 Arrival</li>
<li>10:00 &#8211; 11:00 MVC / EF (Andrei Ignat)</li>
<li><strong>11:00 &#8211; 12:00 WCF Streaming (Andrei Rinea)</strong></li>
<li>12:00 &#8211; 13:00 SQL Server Denali (Cristian Lefter)</li>
<li>13:00 &#8211; 13:30 LUNCH</li>
<li>13:30 &#8211; 14:00 A lap around Windows 8 (Mihai Nadăș)</li>
<li>14:00 &#8211; 15:15 Hyper-V 3.0 și SCVMM 2012 (Valentin Cristea &amp; Răzvan Rusu)</li>
<li>15:15 &#8211; 16:30 Office 365 și Lync Online &amp; On-Premise (Alexandru Dionisie &amp; Paul Roman)</li>
</ul>
<p>I will be presenting WCF Streaming at 11:00. But I assure you the other presentations will be just as interesting as this!</p>
<p>Come and join us and you won&#8217;t regret it! But first <a href="http://itcamp-bucuresti.eventbrite.com/">register at the event site first</a>! Only 22 seats available at the time of the writing.</p>
<p>Hope to see you there!.</p>
<img src="http://feeds.feedburner.com/~r/Andrei-Rinea/~4/N3xbtwj7rho" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.andrei.rinea.ro/2011/11/15/it-community-meeting-codecamp-itspark/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		<feedburner:origLink>http://blog.andrei.rinea.ro/2011/11/15/it-community-meeting-codecamp-itspark/?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=it-community-meeting-codecamp-itspark</feedburner:origLink></item>
		<item>
		<title>WCF service local path</title>
		<link>http://feedproxy.google.com/~r/Andrei-Rinea/~3/zC07sY2_c_U/</link>
		<comments>http://blog.andrei.rinea.ro/2011/11/08/wcf-service-local-path/#comments</comments>
		<pubDate>Tue, 08 Nov 2011 08:55:01 +0000</pubDate>
		<dc:creator>Andrei Rinea</dc:creator>
				<category><![CDATA[CodeProject]]></category>
		<category><![CDATA[WCF]]></category>
		<category><![CDATA[ApplicationPhysicalPath]]></category>
		<category><![CDATA[App_Data]]></category>
		<category><![CDATA[basicHttpBinding]]></category>
		<category><![CDATA[HostingEnvironment]]></category>
		<category><![CDATA[HttpContext]]></category>
		<category><![CDATA[null]]></category>
		<category><![CDATA[StackOverflow]]></category>
		<category><![CDATA[wcf service]]></category>

		<guid isPermaLink="false">http://blog.andrei.rinea.ro/?p=26</guid>
		<description><![CDATA[Developing that small WCF presentation that I was talking about earlier, I got stumped on trying to get the local path. The server needs to access the App_Data folder to handle uploads and downloads but it needs the base path &#8230;<p class="read-more"><a href="http://blog.andrei.rinea.ro/2011/11/08/wcf-service-local-path/">Read more &#187;</a></p>]]></description>
			<content:encoded><![CDATA[<div class="google_plusone_widget"><g:plusone 
      count="true" href="http://blog.andrei.rinea.ro/2011/11/08/wcf-service-local-path/" size="tall"></g:plusone></div><p>Developing that small WCF presentation that <a href="http://blog.andrei.rinea.ro/2011/11/07/cassini-and-wcf-streaming/">I was talking about earlier</a>, I got stumped on trying to get the local path. The server needs to access the App_Data folder to handle uploads and downloads but it needs the base path for that.</p>
<p>No, you don&#8217;t get <a href="http://msdn.microsoft.com/en-us/library/system.web.httpcontext.aspx">HttpContext</a> (HttpContext.Current is null) although the service is bound over basicHttpBinding.</p>
<p>Luckily <a href="http://stackoverflow.com/q/480504/1796">I&#8217;ve found</a><a href="http://stackoverflow.com/q/480504/1796"> via StackOverflow</a> that there is <a href="http://msdn.microsoft.com/en-us/library/system.web.hosting.hostingenvironment.applicationphysicalpath.aspx">HostingEnvironment.ApplicationPhysicalPath</a> which will help you.</p>
<p>Therefore a simple</p>
<pre class="brush: csharp; title: ; notranslate">
public class Service : IService
{
    private readonly string _dataFolder;

    public Service()
    {
       _dataFolder = Path.Combine(HostingEnvironment.ApplicationPhysicalPath, &quot;App_Data&quot;);
    }
}
</pre>
<p>.. will suffice.</p>
<img src="http://feeds.feedburner.com/~r/Andrei-Rinea/~4/zC07sY2_c_U" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.andrei.rinea.ro/2011/11/08/wcf-service-local-path/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		<feedburner:origLink>http://blog.andrei.rinea.ro/2011/11/08/wcf-service-local-path/?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=wcf-service-local-path</feedburner:origLink></item>
		<item>
		<title>Cassini and WCF streaming</title>
		<link>http://feedproxy.google.com/~r/Andrei-Rinea/~3/SQjykQRgt0A/</link>
		<comments>http://blog.andrei.rinea.ro/2011/11/07/cassini-and-wcf-streaming/#comments</comments>
		<pubDate>Mon, 07 Nov 2011 10:49:33 +0000</pubDate>
		<dc:creator>Andrei Rinea</dc:creator>
				<category><![CDATA[CodeProject]]></category>
		<category><![CDATA[WCF]]></category>
		<category><![CDATA[.net3.5]]></category>
		<category><![CDATA[.net4.0]]></category>
		<category><![CDATA[cassini]]></category>
		<category><![CDATA[iis]]></category>
		<category><![CDATA[iis-express]]></category>
		<category><![CDATA[MessageContract]]></category>
		<category><![CDATA[Stream]]></category>
		<category><![CDATA[streamedrequest]]></category>
		<category><![CDATA[streamedresponse]]></category>
		<category><![CDATA[streaming]]></category>
		<category><![CDATA[transferMode]]></category>
		<category><![CDATA[wcf]]></category>

		<guid isPermaLink="false">http://blog.andrei.rinea.ro/?p=22</guid>
		<description><![CDATA[I am preparing a small talk &#38; demo on WCF streaming and I&#8217;ve tried a lot of things to get it started and working (the practical demo). I was trying to showcase uploading and downloading large files, in an async &#8230;<p class="read-more"><a href="http://blog.andrei.rinea.ro/2011/11/07/cassini-and-wcf-streaming/">Read more &#187;</a></p>]]></description>
			<content:encoded><![CDATA[<div class="google_plusone_widget"><g:plusone 
      count="true" href="http://blog.andrei.rinea.ro/2011/11/07/cassini-and-wcf-streaming/" size="tall"></g:plusone></div><p>I am preparing a small talk &amp; demo on WCF streaming and I&#8217;ve tried a lot of things to get it started and working (the practical demo).</p>
<p>I was trying to showcase uploading and downloading large files, in an async manner with progress report and so on.</p>
<p>Turns out I get an exception, with HTTP code 400 Bad request no matter what I&#8217;ve tried :</p>
<ul>
<li>transferMode : StreamedRequest, StreamedResponse or Streamed (Buffered works but it&#8217;s not streaming so&#8230;)</li>
<li>Tried using MessageContracts or plain Stream&#8217;s</li>
<li>.NET Framework 3.5 or 4.0</li>
<li>.. and many other things.</li>
</ul>
<p>What was the issue? Well the damn development server (code named Cassini) !!! It seems <a href="http://stackoverflow.com/q/1532078/1796">another guy had the same issue, reported on StackOverflow</a> and I was lucky to find it in the large WCF pile.</p>
<p><img class="alignnone" title="Cassini tray icon" src="http://cgeers.files.wordpress.com/2011/04/cassini.jpg" alt="" width="467" height="103" /></p>
<p>Running the same server project on the new <a title="Introducing IIS Express" href="http://weblogs.asp.net/scottgu/archive/2010/06/28/introducing-iis-express.aspx">IIS Express</a> or plain old IIS makes it work.</p>
<p>Hope this will help someone too.. At all costs avoid Cassini (&#8220;ASP.NET Development Server&#8221;). This is not the first issue that this damn server introduces and surely not the last. I hope Visual Studi vNext will NOT include it anymore and will ship with IIS Express only.</p>
<img src="http://feeds.feedburner.com/~r/Andrei-Rinea/~4/SQjykQRgt0A" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.andrei.rinea.ro/2011/11/07/cassini-and-wcf-streaming/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		<feedburner:origLink>http://blog.andrei.rinea.ro/2011/11/07/cassini-and-wcf-streaming/?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=cassini-and-wcf-streaming</feedburner:origLink></item>
		<item>
		<title>IEnumerable.All() gotcha</title>
		<link>http://feedproxy.google.com/~r/Andrei-Rinea/~3/RDUpS3Pe7RI/</link>
		<comments>http://blog.andrei.rinea.ro/2011/11/04/ienumerable-all-gotcha/#comments</comments>
		<pubDate>Fri, 04 Nov 2011 12:06:14 +0000</pubDate>
		<dc:creator>Andrei Rinea</dc:creator>
				<category><![CDATA[CodeProject]]></category>
		<category><![CDATA[LINQ]]></category>
		<category><![CDATA[All]]></category>
		<category><![CDATA[Any]]></category>
		<category><![CDATA[IEnumerable]]></category>
		<category><![CDATA[linq]]></category>

		<guid isPermaLink="false">http://blog.andrei.rinea.ro/?p=8</guid>
		<description><![CDATA[Today as I was inspecting why some condition was evaluated to true instead of false I found out a strange thing. The code is something like : I was expecting that in case of an empty collection the All method &#8230;<p class="read-more"><a href="http://blog.andrei.rinea.ro/2011/11/04/ienumerable-all-gotcha/">Read more &#187;</a></p>]]></description>
			<content:encoded><![CDATA[<div class="google_plusone_widget"><g:plusone 
      count="true" href="http://blog.andrei.rinea.ro/2011/11/04/ienumerable-all-gotcha/" size="tall"></g:plusone></div><p>Today as I was inspecting why some condition was evaluated to true instead of false I found out a strange thing. The code is something like :</p>
<pre class="brush: csharp; title: ; notranslate">
var someList = new List&lt;Person&gt;();
if (someList.All(v =&gt; v.Age &gt; 18))
{
    Console.WriteLine(&quot;All are 18 or older.&quot;);
}
else
{
    Console.WriteLine(&quot;At least one is less than 18.&quot;);
}
</pre>
<p>I was expecting that in case of an empty collection the <strong>All</strong> method would return false. But it doesn&#8217;t. The &#8220;All are 18 or older.&#8221; string would be printed.</p>
<p>In my case one more simple condition solved this issue :</p>
<pre class="brush: csharp; title: ; notranslate">
    if (someList.Any() &amp;&amp; someList.All(v =&gt; v.Age &gt; 18))
</pre>
<p>After this I read the manual (<a href="http://en.wikipedia.org/wiki/RTFM">RTFM</a>) and <a href="http://msdn.microsoft.com/en-us/library/bb548541.aspx">according to MSDN (in a community comment however)</a> :</p>
<blockquote><p>It&#8217;s important to note that Enumerable.All() returns true for empty sequences</p></blockquote>
<p>So it&#8217;s a &#8220;doh&#8221; moment for me.</p>
<p>Watch out for this in your code.</p>
<img src="http://feeds.feedburner.com/~r/Andrei-Rinea/~4/RDUpS3Pe7RI" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.andrei.rinea.ro/2011/11/04/ienumerable-all-gotcha/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		<feedburner:origLink>http://blog.andrei.rinea.ro/2011/11/04/ienumerable-all-gotcha/?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=ienumerable-all-gotcha</feedburner:origLink></item>
		<item>
		<title>A useful custom configuration section for inline unconstrained XML</title>
		<link>http://feedproxy.google.com/~r/Andrei-Rinea/~3/u3DsnhEKOJY/</link>
		<comments>http://blog.andrei.rinea.ro/2009/09/20/a-useful-custom-configuration-section-for-inline-unconstrained-xml/#comments</comments>
		<pubDate>Sun, 20 Sep 2009 09:39:41 +0000</pubDate>
		<dc:creator>Andrei Rinea</dc:creator>
				<category><![CDATA[CodeProject]]></category>
		<category><![CDATA[TIps & tricks]]></category>
		<category><![CDATA[.config]]></category>
		<category><![CDATA[.net]]></category>
		<category><![CDATA[configuration]]></category>
		<category><![CDATA[ConfigurationSection]]></category>
		<category><![CDATA[xml]]></category>

		<guid isPermaLink="false">http://blog.andrei.rinea.ro/?p=230</guid>
		<description><![CDATA[As I was writing a small TCP server for serving a Silverlight local TCP policy, I came across a certain need. Inspired by Dan Wahlin&#8217;s server implementation, I chose to write a simplified version for myself. I needed to keep &#8230;<p class="read-more"><a href="http://blog.andrei.rinea.ro/2009/09/20/a-useful-custom-configuration-section-for-inline-unconstrained-xml/">Read more &#187;</a></p>]]></description>
			<content:encoded><![CDATA[<div class="google_plusone_widget"><g:plusone 
      count="true" href="http://blog.andrei.rinea.ro/2009/09/20/a-useful-custom-configuration-section-for-inline-unconstrained-xml/" size="tall"></g:plusone></div><p>As I was writing a small TCP server for serving a Silverlight local TCP policy, I came across a certain need. Inspired by Dan Wahlin&#8217;s server implementation, I chose to write a simplified version for myself. I needed to keep some XML in the <em>App.config</em> without constraining it with a schema.</p>
<p>The normal solution in this case is a custom section, sibling to <strong>appSettings</strong> if you wish. So my <em>App.Config</em> looked at first like this:</p>
<pre class="brush: xml; title: ; notranslate">&lt;configuration&gt;
  &lt;appSettings&gt;
    &lt;add key=&quot;ipAddress&quot; value=&quot;127.0.0.1&quot;/&gt;
  &lt;/appSettings&gt;
  &lt;access-policy&gt;
    &lt;cross-domain-access&gt;
      &lt;policy&gt;
        &lt;allow-from&gt;
          &lt;domain uri=&quot;*&quot; /&gt;
        &lt;/allow-from&gt;
        &lt;grant-to&gt;
          &lt;socket-resource port=&quot;4502&quot; protocol=&quot;tcp&quot; /&gt;
        &lt;/grant-to&gt;
      &lt;/policy&gt;
    &lt;/cross-domain-access&gt;
  &lt;/access-policy&gt;
&lt;/configuration&gt;
</pre>
<p>Upon running the program, even addressing the &#8220;<strong>ipAddress</strong>&#8221; key in the <strong>appSettings</strong> section throws an exception like:</p>
<pre lang="text">System.Configuration.ConfigurationErrorsException was unhandled
  Message="Configuration system failed to initialize"
  Source="System.Configuration"
  BareMessage="Configuration system failed to initialize"
  Line=0
  StackTrace:
       at System.Configuration.ConfigurationManager.PrepareConfigSystem()
       at System.Configuration.ConfigurationManager.GetSection(String sectionName)
       at System.Configuration.ConfigurationManager.get_AppSettings()
       at ConsoleApplication1.Program.Main(String[] args) in C:\Users\Andrei\Documents\Visual Studio 2008\Projects\ConsoleApplication1\ConsoleApplication1\Program.cs:line 21
       at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException: System.Configuration.ConfigurationErrorsException
       Message="Unrecognized configuration section access-policy.
               (C:\\Users\\Andrei\\Documents\\Visual Studio 2008\\Projects\\ConsoleApplication1\\ConsoleApplication1\\bin\\Debug\\ConsoleApplication1.vshost.exe.config line 8)"
       Source="System.Configuration"
       BareMessage="Unrecognized configuration section access-policy."
       Filename="C:\\Users\\Andrei\\Documents\\Visual Studio 2008\\Projects\\ConsoleApplication1\\ConsoleApplication1\\bin\\Debug\\ConsoleApplication1.vshost.exe.config"
       Line=8
       StackTrace:
            at System.Configuration.ConfigurationSchemaErrors.ThrowIfErrors(Boolean ignoreLocal)
            at System.Configuration.BaseConfigurationRecord.ThrowIfParseErrors(ConfigurationSchemaErrors schemaErrors)
            at System.Configuration.BaseConfigurationRecord.ThrowIfInitErrors()
            at System.Configuration.ClientConfigurationSystem.EnsureInit(String configKey)
       InnerException:</pre>
<p>So something is wrong. We need to tell the runtime that the &#8220;access-policy&#8221; section is allowed.</p>
<pre class="brush: xml; title: ; notranslate">
&lt;configuration&gt;
   &lt;configSections&gt;
    &lt;section name=&quot;access-policy&quot; type=&quot;CustomSections.InlineXmlSection, CustomSections&quot;/&gt;
   &lt;/configSections&gt;
  ...
</pre>
<p>At first, I didn&#8217;t place the <strong>type</strong> attribute in the &#8220;<strong>section</strong>&#8221; element, but it turned out it had to be specified and not be empty. Moreover, it must contain the fully-qualified class name and the assembly which contains it. The class must inherit from <strong>System.Configuration.ConfigurationSection</strong>.<br />
Also ensure that the assembly name is specified after the coma, in the type attribute and the configSections section is the first child element of the configuration (root) element.
</p>
<p>So, I created an assembly called CustomSections, and added references to the System.Configuration assembly and the System.Xml assembly.</p>
<p>All you need to do is override the <strong>DeserializeSection</strong> method and load the XML document in there:</p>
<pre class="brush: csharp; title: ; notranslate">using System.Configuration;
using System.Xml;

namespace CustomSections
{
  public class InlineXmlSection : ConfigurationSection
  {
    public XmlDocument Content { get; private set; }

    protected override void DeserializeSection(XmlReader reader)
    {
      (this.Content = new XmlDocument()).Load(reader);
    }
  }
}
</pre>
<p>The code is pretty self-explanatory: we instantiate a new <strong>XmlDocument</strong> and load it from the <strong>XmlReader</strong> provided to us by the configuration infrastructure. If anything goes bad, the exception handling will be the responsibility of the caller. In this case, the first call to <strong>ConfigurationManager</strong>.</p>
<p>Now, let&#8217;s put the code to use:</p>
<pre class="brush: csharp; title: ; notranslate">
private static void Main(string[] args)
{
  expectedRequestBytes = Encoding.UTF8.GetBytes(&quot;&lt;policy-file-request/&gt;&quot;);
  listener = new TcpListener(IPAddress.Parse(ConfigurationManager.AppSettings[&quot;ipAddress&quot;]), 943);
  var policySection = (InlineXmlSection)ConfigurationManager.GetSection(&quot;access-policy&quot;);
  policyBytes = Encoding.UTF8.GetBytes(policySection.Content.OuterXml);
  ...
}
</pre>
<p>The underlined code is the relevant portion (the rest is provided for context). We get the section via <strong>ConfigurationManager.GetSection</strong>, and we have to cast the result to the desired section type. Then we use the section as we see fit.</p>
<img src="http://feeds.feedburner.com/~r/Andrei-Rinea/~4/u3DsnhEKOJY" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.andrei.rinea.ro/2009/09/20/a-useful-custom-configuration-section-for-inline-unconstrained-xml/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		<feedburner:origLink>http://blog.andrei.rinea.ro/2009/09/20/a-useful-custom-configuration-section-for-inline-unconstrained-xml/?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=a-useful-custom-configuration-section-for-inline-unconstrained-xml</feedburner:origLink></item>
	</channel>
</rss>
