<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Andrei Rinea&#039;s technical blog</title>
	<atom:link href="https://blog.andrei.rinea.ro/feed/" rel="self" type="application/rss+xml" />
	<link>https://blog.andrei.rinea.ro</link>
	<description>.NET, SQL Server and Java</description>
	<lastBuildDate>Wed, 18 Sep 2024 14:10:45 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.8.3</generator>
	<item>
		<title>Career change</title>
		<link>https://blog.andrei.rinea.ro/2024/09/18/career-change/</link>
					<comments>https://blog.andrei.rinea.ro/2024/09/18/career-change/#respond</comments>
		
		<dc:creator><![CDATA[Andrei Rinea]]></dc:creator>
		<pubDate>Wed, 18 Sep 2024 14:09:35 +0000</pubDate>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[application-security]]></category>
		<category><![CDATA[career]]></category>
		<category><![CDATA[change]]></category>
		<guid isPermaLink="false">https://blog.andrei.rinea.ro/?p=607</guid>

					<description><![CDATA[It&#8217;s been quite a well since I&#8217;ve written so I should start somewhere. In July 2019 I&#8217;ve transitioned to Security Engineering from Software Development. I&#8217;m an Application Security Engineer since then. It&#8217;s been, and still is, a fun ride. Why &#8230;<p class="read-more"><a href="https://blog.andrei.rinea.ro/2024/09/18/career-change/">Read more &#187;</a></p>]]></description>
										<content:encoded><![CDATA[
<p>It&#8217;s been quite a well since I&#8217;ve written so I should start somewhere.</p>



<p>In July 2019 I&#8217;ve transitioned to Security Engineering from Software Development. I&#8217;m an Application Security Engineer since then. It&#8217;s been, and still is, a fun ride.</p>



<p>Why did I switch from development? Honestly there&#8217;s a mix of reasons: I&#8217;ve wanted to try something different, I&#8217;ve grown dissatisfied with the position I was holding and there was this opportunity to remain at my current employer under a new manager that I&#8217;ve respected more.</p>



<p>What is Application Security Engineering? Although I&#8217;ve been in this new field for 5+ years now I still feel like a total n00b. Therefore I&#8217;ll try to explain as best as I can&#8230;</p>



<p>Application Security is the sub-field of Information Security which aims to measure and improve the security posture (level) of software applications. There are several components:</p>



<ul class="wp-block-list"><li>Secure Design: thinking how to properly build the piece of software from a security standpoint</li><li>Threat Modeling: analyzing the actors, interactions and trust boundaries, in order to identify and mitigate risks</li><li>Secure Coding: using tools and practices to prevent, identify common security vulnerabilities in code</li><li>Vulnerability Management: monitoring and patching 3rd party software included</li><li>Incident Response: preparing plans to properly handle security incidents (sometimes, but not always &#8220;hacks&#8221;)</li><li>Compliance: ensuring that the application meets industry security standards, legal requirements, and best practices</li></ul>



<p>There&#8217;s many new tools and techniques that complement the ones used in software development. Some are FOSS (Free Open Source Software), some are not, some are reliable and mature, some not really.. Sometimes you build your own security tools because of monetary reasons (yes, the cost to build still is cheaper in some areas).</p>



<p>I used to think Security Engineering is just a small area, well defined, right next to Software Development. Boy was I wrong&#8230;</p>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.andrei.rinea.ro/2024/09/18/career-change/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Having fun with HTML 5 History API – part three</title>
		<link>https://blog.andrei.rinea.ro/2016/07/22/having-fun-with-html-5-history-api-part-three/</link>
					<comments>https://blog.andrei.rinea.ro/2016/07/22/having-fun-with-html-5-history-api-part-three/#comments</comments>
		
		<dc:creator><![CDATA[Andrei Rinea]]></dc:creator>
		<pubDate>Fri, 22 Jul 2016 16:38:43 +0000</pubDate>
				<category><![CDATA[CodeProject]]></category>
		<category><![CDATA[HTML5]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[ajax]]></category>
		<category><![CDATA[api]]></category>
		<category><![CDATA[asp.net-mvc]]></category>
		<category><![CDATA[back-button]]></category>
		<category><![CDATA[cascading]]></category>
		<category><![CDATA[dropdown]]></category>
		<category><![CDATA[fields]]></category>
		<category><![CDATA[history]]></category>
		<category><![CDATA[html5]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[jquery]]></category>
		<category><![CDATA[pushstate]]></category>
		<category><![CDATA[usability]]></category>
		<guid isPermaLink="false">http://blog.andrei.rinea.ro/?p=536</guid>

					<description><![CDATA[Part 1 &#8211; Description of the problem Part 2 &#8211; simple history replacement Part 3 – additional history items &#8211; this article As we&#8217;ve seen in the previous parts, we can alter the history of the current page navigation by &#8230;<p class="read-more"><a href="https://blog.andrei.rinea.ro/2016/07/22/having-fun-with-html-5-history-api-part-three/">Read more &#187;</a></p>]]></description>
										<content:encoded><![CDATA[<p><a href="http://blog.andrei.rinea.ro/2016/07/18/having-fun-with-html-5-history-api-part-one/">Part 1 &#8211; Description of the problem</a><br />
<a href="http://blog.andrei.rinea.ro/2016/07/18/having-fun-with-html-5-history-api-part-two/">Part 2 &#8211; simple history replacement</a><br />
Part 3 – additional history items &#8211; this article</p>
<p>As we&#8217;ve seen in the previous parts, we can alter the history of the current page navigation by replacing the current URL with a new one (this freedom has limits, of course, and we can&#8217;t alter the protocol or the host). For women is very important to show off a nice makeup. You can get a <a href="https://etspeaksfromhome.co.uk/2018/12/how-to-make-makeup-look-smooth-on-your-face.html">smooth makeup</a> with advises from makeup professionals.</p>
<p>What we&#8217;ll explore in this part is creating new history items while not leaving the page. In order to achieve this, we&#8217;ll make use of</p>
<pre>history.pushState( ... )
</pre>
<p>and an event called popstate :</p>
<pre>window.addEventListener('popstate', function () { /* ... */ });
</pre>
<p>First we&#8217;ll need to replace all replaceState calls to pushState calls. The parameters stay the same:</p>
<pre><pre class="brush: jscript; highlight: [9,33,35]; title: ; notranslate">
function loadModels(make, pushState, onSuccess) {
    $.ajax({
        cache: true,
        type: 'GET',
        url: '@Url.Action("GetModelsByMake")',
        data: { 'makeId': make },
        success: function (data) {
            if (pushState)
                history.pushState(null, null, "/Home/Selector?mkId=" + make);
            var models = $("#SelectedModel");
            models.empty();
            models.append($("&amp;lt;option&amp;gt;&amp;lt;/option&amp;gt;").attr("value", "").text(" -- please select a model -- "));
            $.each(data, function (key, val) {
                models.append($("&amp;lt;option&amp;gt;&amp;lt;/option&amp;gt;").attr("value", val.Id).text(val.Text));
            });
            $('#divModel').show();
            if (onSuccess)
                onSuccess();
        },
        error: function (xhr, ajaxOptions, error) {
            alert(error);
            $('#divModel').hide();
        }
    });
}

// ...

function modelChanged() {
    var makeId = getParameterByName("mkId", document.location.href);
    var modelId = $("#SelectedModel").val();
    if (!modelId)
        history.pushState(null, null, "/Home/Selector?mkId=" + makeId);
    else
        history.pushState(null, null, "/Home/Selector?mkId=" + makeId + "&amp;amp;mdId=" + modelId);
}
</pre>
<p><span id="more-536"></span></p>
<p>At this point we can run the app and see how changing the make and / or the model alters the URL but also the back button can take us to the previous URL on the page. However, restoration of the selection doesn&#8217;t happen upon going back. This is because we didn&#8217;t add the event listener yet.</p>
<p>So let&#8217;s do that. Add the following piece of code:</p>
<pre><pre class="brush: jscript; title: ; notranslate">
window.addEventListener('popstate', function () {
    $("#SelectedMake").off("change");
    $("#SelectedModel").off("change");
    init(function () {
        $("#SelectedMake").change(makeChanged);
        $("#SelectedModel").change(modelChanged);
    });
});
</pre>
<p>In this event handler we&#8217;ll capture the situation when the user hit the back button and the URL is on the same page, practically a synthetical location has been navigated to.</p>
<p>Because the URL changed we need to re-init the page, hence the call to the init function. However, the init function will tend to indirectly alter the URL again because it would change the make or model. This would happen because the change event handlers of the drop downs would fire. To prevent this we&#8217;re unsubscribing them first. This is done using the .off(&#8220;change&#8221;) jquery shortcuts.</p>
<p>We, then, need to call the init function which has an asynchronous part, the AJAX call, and only after the call has successfully ended we need to re-subscribe the event handlers. This is why we call init with a new parameter, a function containing the re-subscription to the change events. Therefore we&#8217;ll need to change the init function too:</p>
<pre><pre class="brush: jscript; highlight: [3,4,5,6,7,8,9,10,14,15]; title: ; notranslate">
function init(afterInit) {
    var makeId = getParameterByName("mkId", document.location.href);
    if (!makeId) {
        $("#SelectedMake").val("");
        $('#divModel').hide();
        if (afterInit)
            afterInit();
        return;
    }
    $("#SelectedMake").val(makeId);
    var modelId = getParameterByName("mdId", document.location.href);
    loadModels(makeId, false, function () {
        $("#SelectedModel").val(modelId);
        if (afterInit)
            afterInit();
    });
</pre>
<p>the changes in the function add some extra functionality:</p>
<p>&#8211; clears the selection in the make dropdown if the navigated state does not contain one (line 4)<br />
&#8211; hides the model selector if no make is selected (line 5)<br />
&#8211; selects a make if the navigated state contains one (line 10)</p>
<p>The navigation works forward too, the popState event will fire in this case also.<br />
At this point the app should function well, handling all navigation states.</p>
<p>This concludes this short series on HTML 5 History API.</p>
<p>You can check out <a href="https://github.com/Andrei-Rinea/HistoryApiSample/blob/1_Add_PushStateForDDLs/HistoryApiSample/Views/Home/Selector.cshtml">the final stage of the HTML code here</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.andrei.rinea.ro/2016/07/22/having-fun-with-html-5-history-api-part-three/feed/</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
			</item>
		<item>
		<title>Having fun with HTML 5 History API – part two</title>
		<link>https://blog.andrei.rinea.ro/2016/07/18/having-fun-with-html-5-history-api-part-two/</link>
					<comments>https://blog.andrei.rinea.ro/2016/07/18/having-fun-with-html-5-history-api-part-two/#comments</comments>
		
		<dc:creator><![CDATA[Andrei Rinea]]></dc:creator>
		<pubDate>Mon, 18 Jul 2016 18:00:32 +0000</pubDate>
				<category><![CDATA[CodeProject]]></category>
		<category><![CDATA[HTML5]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[ajax]]></category>
		<category><![CDATA[api]]></category>
		<category><![CDATA[asp.net-mvc]]></category>
		<category><![CDATA[back-button]]></category>
		<category><![CDATA[cascading]]></category>
		<category><![CDATA[dropdown]]></category>
		<category><![CDATA[fields]]></category>
		<category><![CDATA[history]]></category>
		<category><![CDATA[html5]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[jquery]]></category>
		<category><![CDATA[usability]]></category>
		<guid isPermaLink="false">http://blog.andrei.rinea.ro/?p=524</guid>

					<description><![CDATA[Part 1 &#8211; Description of the problem Part 2 &#8211; this article (simple history replacement) Part 3 – additional history items As we saw earlier in part 1, hitting the back button into a page with filled in fields will &#8230;<p class="read-more"><a href="https://blog.andrei.rinea.ro/2016/07/18/having-fun-with-html-5-history-api-part-two/">Read more &#187;</a></p>]]></description>
										<content:encoded><![CDATA[<p><a href="http://blog.andrei.rinea.ro/2016/07/18/having-fun-with-html-5-history-api-part-one/">Part 1 &#8211; Description of the problem</a><br />
Part 2 &#8211; this article (simple history replacement)<br />
<a href="http://blog.andrei.rinea.ro/2016/07/22/having-fun-with-html-5-history-api-part-three/">Part 3 – additional history items</a></p>
<p>As we saw earlier in part 1, hitting the back button into a page with filled in fields will not restore (all) the values, but merely the ones that exist at the time of the page loading. In some cases, for example cascading dropdowns, will not be shown or exist at all at the time of the page load.</p>
<p>What we will accomplish in this part is to push into the query string (without reloading the page!) the selected make and the selected model (where applicable).</p>
<p>We are going to make use of</p>
<pre>history.replaceState(...)</pre>
<p>function. There is a <a href="https://www.w3.org/TR/2011/WD-html5-20110113/history.html#the-history-interface">W3C standard</a> available for this function (and others).  Note that this is supported on all browsers, but <a href="http://caniuse.com/#feat=history">only the recent versions</a>.</p>
<p>To do so we need a few things:</p>
<ul>
<li>A function to parse (a) query string; sadly JavaScript does not have anything built in, not even jQuery is of much help..</li>
<li>Change the URL upon changing of selection</li>
<li>Restore selection from the URL &#8211; including cascading</li>
</ul>
<p>Great! Let&#8217;s start.</p>
<p>Upon a bit of searching around which turned into stackoverflowing, I reached the most voted question on this matter called &#8216;<a href="http://stackoverflow.com/q/901115/1796">How can I get query string values in JavaScript?</a>&#8216;.</p>
<p>I really looked for a quick-simple-and-standards-compliant-and-so-on solution but the best I could scavenge was this:</p>
<pre class="brush: jscript; title: ; notranslate">
function getParameterByName(name, url) {
    if (!url) url = window.location.href;
    name = name.replace(/&#x5B;\&#x5B;\]]/g, &quot;\\$&amp;&quot;);
    var regex = new RegExp(&quot;&#x5B;?&amp;]&quot; + name + &quot;(=(&#x5B;^&amp;#]*)|&amp;|#|$)&quot;),
        results = regex.exec(url);
    if (!results) return null;
    if (!results&#x5B;2]) return '';
    return decodeURIComponent(results&#x5B;2].replace(/\+/g, &quot; &quot;));
}
</pre>
<p>Ugly but it works.</p>
<p><span id="more-524"></span></p>
<p>We already have a bit of initialization ( quick tip/reminder : in jQuery you can write a function that will execute upon document &#8216;ready&#8217; just like so: $(function() { /* &#8230; */ }); ) :</p>
<pre class="brush: jscript; title: ; notranslate">
$(function () {
    $(&quot;#SelectedMake&quot;).change(makeChanged);
    makeChanged(); // &lt;- this wasn't really necessary
});
</pre>
<p>Let&#8217;s add an event handler for the change of the selected model in order to change the URL from there, too:</p>
<pre class="brush: jscript; title: ; notranslate">
$(function () {
    $(&quot;#SelectedMake&quot;).change(makeChanged);
    $(&quot;#SelectedModel&quot;).change(modelChanged);
});

// ...

function modelChanged() {
    var makeId = getParameterByName(&quot;mkId&quot;, document.location.href);
    var modelId = $(&quot;#SelectedModel&quot;).val();
    if (!modelId)
        history.replaceState(null, null, &quot;/Home/Selector?mkId=&quot; + makeId);
    else
        history.replaceState(null, null, &quot;/Home/Selector?mkId=&quot; + makeId + &quot;&amp;mdId=&quot; + modelId);
}
</pre>
<p>We also need to change the makeChanged logic in order to simplify the function and allow future reuse of the ajax populating call (changed lines are highlighted) :</p>
<pre class="brush: jscript; highlight: [1,8,9,17,18]; title: ; notranslate">
function loadModels(make, pushState, onSuccess) {
    $.ajax({
        cache: true,
        type: 'GET',
        url: '@Url.Action(&quot;GetModelsByMake&quot;)',
        data: { 'makeId': make },
        success: function (data) {
            if (pushState)
                history.replaceState(null, null, &quot;/Home/Selector?mkId=&quot; + make);
            var models = $(&quot;#SelectedModel&quot;);
            models.empty();
            models.append($(&quot;&lt;option&gt;&lt;/option&gt;&quot;).attr(&quot;value&quot;, &quot;&quot;).text(&quot; -- please select a model -- &quot;));
            $.each(data, function (key, val) {
                models.append($(&quot;&lt;option&gt;&lt;/option&gt;&quot;).attr(&quot;value&quot;, val.Id).text(val.Text));
            });
            $('#divModel').show();
            if (onSuccess)
                onSuccess();
        },
        error: function (xhr, ajaxOptions, error) {
            alert(error);
            $('#divModel').hide();
        }
    });
}

function makeChanged() {
    var selectedMake = $(&quot;#SelectedMake&quot;).val();
    if (selectedMake === &quot;&quot;) {
        $('#divModel').hide();
    } else {
        loadModels(selectedMake, true);
    }
}
</pre>
<p>We refactored out the ajax call into the loadModels function and added two parameters:</p>
<ul>
<li>pushState &#8211; this would control whether after successfully loading the models the URL should be changed or not</li>
<li>onSuccess &#8211; an option callback to be executed after successfully loading the models</li>
</ul>
<p>At this point, if we run the sample, we should have URL changing functionality fully implemented but if we submit into the next page and go back to the selector page only the make dropdown will have its selection restored and that isn&#8217;t our work but the browser&#8217;s (this worked from the beginning).</p>
<p>Finally, in order to restore selection from the URL, a bit of initialization is necessary:</p>
<pre class="brush: jscript; highlight: [2]; title: ; notranslate">
$(function () {
    init();
    $(&quot;#SelectedMake&quot;).change(makeChanged);
    $(&quot;#SelectedModel&quot;).change(modelChanged);
});

// ... 

function init() {
    var makeId = getParameterByName(&quot;mkId&quot;, document.location.href);
    if (!makeId) return;
    var modelId = getParameterByName(&quot;mdId&quot;, document.location.href);
    loadModels(makeId, false, function () {
        $(&quot;#SelectedModel&quot;).val(modelId);
    });
}
</pre>
<p>.. and now all should work smooth! 🙂</p>
<p>You can check out <a href="https://github.com/Andrei-Rinea/HistoryApiSample">the code on Github</a>. For this particular step of development here&#8217;s <a href="https://github.com/Andrei-Rinea/HistoryApiSample/blob/1'replace_history/HistoryApiSample/Views/Home/Selector.cshtml">the link to the HTML code</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.andrei.rinea.ro/2016/07/18/having-fun-with-html-5-history-api-part-two/feed/</wfw:commentRss>
			<slash:comments>3</slash:comments>
		
		
			</item>
		<item>
		<title>Having fun with HTML 5 History API &#8211; part one</title>
		<link>https://blog.andrei.rinea.ro/2016/07/18/having-fun-with-html-5-history-api-part-one/</link>
					<comments>https://blog.andrei.rinea.ro/2016/07/18/having-fun-with-html-5-history-api-part-one/#comments</comments>
		
		<dc:creator><![CDATA[Andrei Rinea]]></dc:creator>
		<pubDate>Mon, 18 Jul 2016 14:11:52 +0000</pubDate>
				<category><![CDATA[CodeProject]]></category>
		<category><![CDATA[HTML5]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[ajax]]></category>
		<category><![CDATA[api]]></category>
		<category><![CDATA[asp.net-mvc]]></category>
		<category><![CDATA[back-button]]></category>
		<category><![CDATA[cascading]]></category>
		<category><![CDATA[dropdown]]></category>
		<category><![CDATA[fields]]></category>
		<category><![CDATA[history]]></category>
		<category><![CDATA[html5]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[jquery]]></category>
		<category><![CDATA[usability]]></category>
		<guid isPermaLink="false">http://blog.andrei.rinea.ro/?p=508</guid>

					<description><![CDATA[Part 1 &#8211; this article Part 2 &#8211; simple history replacement Part 3 &#8211; additional history items Have you ever come across a web page with a few fields, let&#8217;s say cascading drop downs, you know like these: &#8230; and &#8230;<p class="read-more"><a href="https://blog.andrei.rinea.ro/2016/07/18/having-fun-with-html-5-history-api-part-one/">Read more &#187;</a></p>]]></description>
										<content:encoded><![CDATA[<p>Part 1 &#8211; this article<br />
<a href="https://blog.andrei.rinea.ro/2016/07/18/having-fun-with-html-5-history-api-part-two/">Part 2 &#8211; simple history replacement</a><br />
<a href="https://blog.andrei.rinea.ro/2016/07/22/having-fun-with-html-5-history-api-part-three/">Part 3 &#8211; additional history items</a></p>
<p>Have you ever come across a web page with a few fields, let&#8217;s say cascading drop downs, you know like these:</p>
<p><img fetchpriority="high" decoding="async" class="alignnone size-full" src="https://1.bp.blogspot.com/-1ae0LU_rAJI/TmRbwOQytLI/AAAAAAAAAAU/xzabHgSNGlU/s1600/3.jpg" width="387" height="258"></p>
<p>&#8230; and after carefully filling in the fields you submit, and you are taken to the next page. Only to find out that you made a mistake and you push the back button in your browser. Guess what, now (almost) all your fields are reset and you have to begin all over again. Frustrating.</p>
<p>Apart from that, I have noticed that &#8220;infinite scrolling&#8221; has really taken off in a lot of sites, some news site (for example <a href="https://www.lifesitenews.com/news/breaking-now-23-states-have-sued-obama-admin-over-transgender-bathroom-regu">this one</a> &#8211; at least at the time of the writing) even change the URL as you scroll down into the next article.</p>
<p>And then I wondered, how could I use this gimmick into solving the first issue (i.e. losing fields information after pressing back) and I came up with two possible solutions to this. I will showcase a small PoC for each one in the next two parts.</p>
<p>First let&#8217;s consider the following minimal web project (ASP.NET MVC but since this is about JavaScript, the back end doesn&#8217;t really matter) with two drop-downs. The first dropdown will let you choose a make of automobiles and the second one will let you choose a model from that particular make. In the end you press continue and you are directed to a new page:</p>
<p><a href="https://blog.andrei.rinea.ro/wp-content/uploads/2016/07/01.png"><img decoding="async" class="aligncenter wp-image-509 size-full" src="https://blog.andrei.rinea.ro/wp-content/uploads/2016/07/01.png" alt="01" width="669" height="388" srcset="https://blog.andrei.rinea.ro/wp-content/uploads/2016/07/01.png 669w, https://blog.andrei.rinea.ro/wp-content/uploads/2016/07/01-300x173.png 300w" sizes="(max-width: 669px) 100vw, 669px" /></a></p>
<p><span id="more-508"></span></p>
<p><a href="https://blog.andrei.rinea.ro/wp-content/uploads/2016/07/02.png"><img decoding="async" class="aligncenter wp-image-510 size-full" src="https://blog.andrei.rinea.ro/wp-content/uploads/2016/07/02.png" alt="02" width="669" height="388" srcset="https://blog.andrei.rinea.ro/wp-content/uploads/2016/07/02.png 669w, https://blog.andrei.rinea.ro/wp-content/uploads/2016/07/02-300x173.png 300w" sizes="(max-width: 669px) 100vw, 669px" /></a><a href="https://blog.andrei.rinea.ro/wp-content/uploads/2016/07/03.png"><img loading="lazy" decoding="async" class="aligncenter wp-image-511 size-full" src="https://blog.andrei.rinea.ro/wp-content/uploads/2016/07/03.png" alt="03" width="669" height="388" srcset="https://blog.andrei.rinea.ro/wp-content/uploads/2016/07/03.png 669w, https://blog.andrei.rinea.ro/wp-content/uploads/2016/07/03-300x173.png 300w" sizes="auto, (max-width: 669px) 100vw, 669px" /></a></p>
<p>Things start to go sideways if you press back in the last stage. You will be taken back to the selector page, the browser will do its best to restore the values but it will only succeed in setting back the make, the model restoration will not work:</p>
<p><a href="https://blog.andrei.rinea.ro/wp-content/uploads/2016/07/04.png"><img loading="lazy" decoding="async" class="aligncenter wp-image-512 size-full" src="https://blog.andrei.rinea.ro/wp-content/uploads/2016/07/04.png" alt="04" width="669" height="388" srcset="https://blog.andrei.rinea.ro/wp-content/uploads/2016/07/04.png 669w, https://blog.andrei.rinea.ro/wp-content/uploads/2016/07/04-300x173.png 300w" sizes="auto, (max-width: 669px) 100vw, 669px" /></a></p>
<p>The client side (HTML markup, CSS and JavaScript lumped together in one file :P) looks like so:</p>
<pre><pre class="brush: jscript; title: ; notranslate">
@model HistoryApiSample.Models.SelectorViewModel
@{
    ViewBag.Title = "Selector";
}

&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;lt;style&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;gt;
    .lbl {
        display: inline-block;
        width: 210px;
        text-align: right;
    }
&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;lt;/style&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;gt;
&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;lt;h2&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;gt;Car select&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;lt;/h2&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;gt;

@using (Html.BeginForm())
{
    &amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;lt;div id="divMake"&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;gt;
        @Html.LabelFor(m =&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;gt; m.SelectedMake, new { @class = "lbl" })
        @Html.DropDownListFor(m =&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;gt; m.SelectedMake, Model.Makes, " -- please select a make -- ")
    &amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;lt;/div&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;gt;

    &amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;lt;div id="divModel" style="display: none;"&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;gt;
        @Html.LabelFor(m =&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;gt; m.SelectedModel, new { @class = "lbl" })
        @Html.DropDownListFor(m =&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;gt; m.SelectedModel, Model.Models, " -- please select a model -- ")
    &amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;lt;/div&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;gt;

    &amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;lt;input type="submit" value="Continue" /&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;gt;
}

@section scripts
{

    &amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;lt;script type="text/javascript"&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;gt;
        $(function () {
            $("#SelectedMake").change(makeChanged);
            makeChanged();
        });

        function makeChanged() {
            var selectedMake = $("#SelectedMake").val();
            if (selectedMake === "") {
                $('#divModel').hide();

            } else {
                $.ajax({
                    cache: true,
                    type: 'GET',
                    url: '@Url.Action("GetModelsByMake")',
                    data: { 'makeId': selectedMake },
                    success: function (data) {
                        var models = $("#SelectedModel");
                        models.empty();
                        models.append($("&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;lt;option&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;gt;&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;lt;/option&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;gt;").attr("value", "").text(" -- please select a model -- "));
                        $.each(data, function (key, val) {
                            models.append($("&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;lt;option&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;gt;&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;lt;/option&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;gt;").attr("value", val.Id).text(val.Text));
                        });
                        $('#divModel').show();
                    },
                    error: function (xhr, ajaxOptions, error) {
                        alert(error);
                        $('#divModel').hide();
                    }
                });
            }
        }
    &amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;lt;/script&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;gt;

}
</pre>
<p>The controller code:</p>
<pre><pre class="brush: csharp; title: ; notranslate">

        // ...
        &#x5B;HttpGet]
        public ActionResult Selector()
        {
            var model = new SelectorViewModel
            {
                Makes = new&#x5B;]
                {
                    new SelectListItem { Value = "VW",  Text = "Volkswagen" },
                    new SelectListItem { Value = "AUD", Text = "Audi"       },
                    new SelectListItem { Value = "SEA", Text = "Seat"       },
                    new SelectListItem { Value = "SKD", Text = "Skoda"      }
                },
                Models = Enumerable.Empty&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;lt;SelectListItem&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;gt;()
            };
            return View(model);
        }

        &#x5B;HttpPost]
        public ActionResult Selector(SelectorViewModel viewModel)
        {
            return RedirectToAction("ShowSelection", new
            {
                makeId = viewModel.SelectedMake,
                modelId = viewModel.SelectedModel
            });
        }

        &#x5B;HttpGet]
        public ActionResult ShowSelection(string makeId, string modelId)
        {
            string makeName = null;
            string modelName = null;
            switch (makeId)
            {
                case "VW": makeName = "Volkswagen"; break;
                case "AUD": makeName = "Audi"; break;
                case "SEA": makeName = "Seat"; break;
                case "SKD": makeName = "Skoda"; break;
            }
            switch (modelId)
            {
                case "TIG": modelName = "Tiguan"; break;
                case "TRG": modelName = "Touareg"; break;
                case "A4": modelName = "A4"; break;
                case "A6": modelName = "A6"; break;
                case "LEO": modelName = "Leon"; break;
                case "IBZ": modelName = "Ibiza"; break;
                case "FAB": modelName = "Fabia"; break;
                case "OCT": modelName = "Octavia"; break;
            }
            var viewModel = new SelectionViewModel
            {
                Make = makeName,
                Model = modelName
            };
            return View(viewModel);
        }

        &#x5B;HttpGet]
        public ActionResult GetModelsByMake(string makeId)
        {
            object data;
            switch (makeId)
            {
                case "VW":
                    data = new&#x5B;]
                    {
                        new DataItem { Id = "TIG", Text = "Tiguan"  },
                        new DataItem { Id = "TRG", Text = "Touareg" }
                    };
                    break;
                case "AUD":
                    data = new&#x5B;]
                    {
                        new DataItem { Id = "A4", Text = "A4"  },
                        new DataItem { Id = "A6", Text = "A6" }
                    };
                    break;
                case "SEA":
                    data = new&#x5B;]
                    {
                        new DataItem { Id = "LEO", Text = "Leon"  },
                        new DataItem { Id = "IBZ", Text = "Ibiza" }
                    };
                    break;
                case "SKD":
                    data = new&#x5B;]
                    {
                        new DataItem { Id = "FAB", Text = "Fabia"  },
                        new DataItem { Id = "OCT", Text = "Octavia" }
                    };
                    break;
                default:
                    return HttpNotFound();
            }
            return Json(data, JsonRequestBehavior.AllowGet);
        }

        private class DataItem
        {
            public string Id { get; set; }
            public string Text { get; set; }
        }

</pre>
<p>Finally the viewmodels:</p>
<pre><pre class="brush: csharp; title: ; notranslate">

    public class SelectorViewModel
    {
        &#x5B;Display(Name = "select a make")]
        public string SelectedMake { get; set; }
        public IEnumerable&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;lt;SelectListItem&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;gt; Makes { get; set; }

        &#x5B;Display(Name = "select a model")]
        public string SelectedModel { get; set; }
        public IEnumerable&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;lt;SelectListItem&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;gt; Models { get; set; }
    }

    public class SelectionViewModel
    {
        public string Make { get; set; }
        public string Model { get; set; }
    }

</pre>
<p>In <a href="http://blog.andrei.rinea.ro/2016/07/18/having-fun-with-html-5-history-api-part-two/">the next part</a> we&#8217;ll explore the simplest way to fix this issue, rewriting history (sounds dramatic but it isn&#8217;t :P).</p>
<p>You can check out the code of the HTML view for this stage of development <a href="https://github.com/Andrei-Rinea/HistoryApiSample/blob/master/HistoryApiSample/Views/Home/Selector.cshtml">here</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.andrei.rinea.ro/2016/07/18/having-fun-with-html-5-history-api-part-one/feed/</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
			</item>
		<item>
		<title>When Stackoverflow goes looney like a leftie</title>
		<link>https://blog.andrei.rinea.ro/2016/06/21/when-stackoverflow-goes-looney-like-a-lefty/</link>
					<comments>https://blog.andrei.rinea.ro/2016/06/21/when-stackoverflow-goes-looney-like-a-lefty/#comments</comments>
		
		<dc:creator><![CDATA[Andrei Rinea]]></dc:creator>
		<pubDate>Mon, 20 Jun 2016 22:25:42 +0000</pubDate>
				<category><![CDATA[Communities]]></category>
		<category><![CDATA[blooper]]></category>
		<category><![CDATA[questions]]></category>
		<category><![CDATA[review]]></category>
		<category><![CDATA[speeding]]></category>
		<category><![CDATA[StackOverflow]]></category>
		<category><![CDATA[test]]></category>
		<guid isPermaLink="false">http://blog.andrei.rinea.ro/?p=503</guid>

					<description><![CDATA[I was recently doing reviews on Stackoverflow when a &#8216;go home you&#8217;re drunk&#8217; page &#8216;caught&#8217; me. Lookie here: This was supposed to be a test to catch &#8216;speeding&#8217; reviewers. I admit that C/C++ are not my strongest points but I &#8230;<p class="read-more"><a href="https://blog.andrei.rinea.ro/2016/06/21/when-stackoverflow-goes-looney-like-a-lefty/">Read more &#187;</a></p>]]></description>
										<content:encoded><![CDATA[<p>I was recently doing reviews on Stackoverflow when a &#8216;go home you&#8217;re drunk&#8217; page &#8216;caught&#8217; me. Lookie here:</p>
<p><a href="https://blog.andrei.rinea.ro/wp-content/uploads/2016/06/stacko.png"><img loading="lazy" decoding="async" class="aligncenter size-full wp-image-504" src="https://blog.andrei.rinea.ro/wp-content/uploads/2016/06/stacko.png" alt="stacko" width="1132" height="1002" srcset="https://blog.andrei.rinea.ro/wp-content/uploads/2016/06/stacko.png 1132w, https://blog.andrei.rinea.ro/wp-content/uploads/2016/06/stacko-300x265.png 300w, https://blog.andrei.rinea.ro/wp-content/uploads/2016/06/stacko-1024x906.png 1024w" sizes="auto, (max-width: 1132px) 100vw, 1132px" /></a>This was supposed to be a test to catch &#8216;speeding&#8217; reviewers. I admit that C/C++ are not my strongest points but I can understand code in C/C++ and rarely even write in them.</p>
<p>I guess they went overboard this time.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.andrei.rinea.ro/2016/06/21/when-stackoverflow-goes-looney-like-a-lefty/feed/</wfw:commentRss>
			<slash:comments>4</slash:comments>
		
		
			</item>
		<item>
		<title>Local meetup &#8211; AngularJS intro</title>
		<link>https://blog.andrei.rinea.ro/2015/11/18/local-meetup-angularjs-intro/</link>
					<comments>https://blog.andrei.rinea.ro/2015/11/18/local-meetup-angularjs-intro/#comments</comments>
		
		<dc:creator><![CDATA[Andrei Rinea]]></dc:creator>
		<pubDate>Wed, 18 Nov 2015 21:54:48 +0000</pubDate>
				<category><![CDATA[Presentations]]></category>
		<category><![CDATA[ADCES]]></category>
		<category><![CDATA[AngularJS]]></category>
		<category><![CDATA[beer]]></category>
		<category><![CDATA[bucharest]]></category>
		<category><![CDATA[Electronic Arts]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[presentation]]></category>
		<guid isPermaLink="false">http://blog.andrei.rinea.ro/?p=497</guid>

					<description><![CDATA[Lately I&#8217;ve been toying with AngularJS and I wanted to share my findings in a short practical presentation. I will be building a small SPA (single page application) with AngularJS and run through the most commonly used directives and features &#8230;<p class="read-more"><a href="https://blog.andrei.rinea.ro/2015/11/18/local-meetup-angularjs-intro/">Read more &#187;</a></p>]]></description>
										<content:encoded><![CDATA[<p>Lately I&#8217;ve been toying with <a href="https://angularjs.org/">AngularJS</a> and I wanted to share my findings in a short practical presentation. I will be building a small SPA (single page application) with AngularJS and run through the most commonly used directives and features of the framework.</p>
<p>If you are in <em><strong>Bucharest</strong></em> on <em><strong>8th of December</strong></em>, after work (19:00) drop by and have a look <img src="https://s.w.org/images/core/emoji/16.0.1/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /> The presentation will be in the <a href="http://www.adces.ro/">ADCES</a> group, the location being <a href="https://www.google.ro/maps/place/Electronic+Arts+Rom%C3%A2nia/@44.4304496,26.0517096,17z/data=!3m1!4b1!4m2!3m1!1s0x40b20195a7c65059:0xcc742dfea6fca46b">Electronic Arts</a> (AFI Park 2).</p>
<p>Entrance is free, just register on this event either via <a href="https://www.facebook.com/events/635079933298895/">Facebook</a> or via <a href="http://www.meetup.com/Bucharest-A-D-C-E-S-Meetup/events/226695597/">Meetup</a>. Hope to see you there <img src="https://s.w.org/images/core/emoji/16.0.1/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<p>PS: Did I tell you that we&#8217;re having <strong>beers</strong> afterwards? <img src="https://s.w.org/images/core/emoji/16.0.1/72x72/1f609.png" alt="😉" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.andrei.rinea.ro/2015/11/18/local-meetup-angularjs-intro/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
			</item>
		<item>
		<title>Visual Studio smart replace</title>
		<link>https://blog.andrei.rinea.ro/2015/11/04/visual-studio-smart-replace/</link>
					<comments>https://blog.andrei.rinea.ro/2015/11/04/visual-studio-smart-replace/#respond</comments>
		
		<dc:creator><![CDATA[Andrei Rinea]]></dc:creator>
		<pubDate>Wed, 04 Nov 2015 10:57:23 +0000</pubDate>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Visual Studio]]></category>
		<category><![CDATA[All]]></category>
		<category><![CDATA[C# 6]]></category>
		<category><![CDATA[CTRL-SHIFT-H]]></category>
		<category><![CDATA[nameof]]></category>
		<category><![CDATA[regex]]></category>
		<category><![CDATA[replace]]></category>
		<category><![CDATA[Visual-Studio]]></category>
		<guid isPermaLink="false">http://blog.andrei.rinea.ro/?p=494</guid>

					<description><![CDATA[Let&#8217;s say you need to replace an expression in many files in Visual Studio with another expression. The case in question is replacing nameof(someVariable) to "someVariable" Sure you can try to replace nameof( to " but this will leave the &#8230;<p class="read-more"><a href="https://blog.andrei.rinea.ro/2015/11/04/visual-studio-smart-replace/">Read more &#187;</a></p>]]></description>
										<content:encoded><![CDATA[<p>Let&#8217;s say you need to replace an expression in many files in Visual Studio with another expression. The case in question is replacing</p>
<p><code>nameof(someVariable)</code><br /> to<br /> <code>"someVariable"</code></p>
<p>Sure you can try to replace</p>
<p><code>nameof(</code><br /> to<br /> <code>"</code></p>
<p>but this will leave the double quote open and we don&#8217;t want this. Searching on the internetz and finding <a href="http://stackoverflow.com/q/3147096/1796">some stackoverflow solution</a> and with the help of a second pair of eyes from <a href="http://daemoohn.com/">a colleague</a> we managed to find a solution like so:</p>
<p>Hit CTRL-SHIFT-H in Visual Studio and check &#8220;Use Regular Expressions&#8221;. Then select your scope, for example &#8220;Entire solution&#8221; and use the following expressions:</p>
<p>Find what:<br /> <code>nameof\(([a-zA-z]+)\)</code></p>
<p>Replace with:<br /> <code>"$1"</code></p>
<p>This will do the job. Let&#8217;s analyze the expressions a bit. The &#8220;Find what:&#8221; one, first. &#8216;nameof&#8217; is the literal occurence of &#8216;nameof&#8217;. The first round bracket is preceded by backslash because we need to escape it. This is because the round bracket is used in the regular expressions syntax while in our case we need to literally find it. This was the &#8216;\(&#8216; part.</p>
<p>Now there is the &#8216;([a-zA-z]+)&#8217; part. This has several sub-parts. The round brackets mean that the whole segment should be captured. We&#8217;ll later see why and what this is. Next, the square bracket part means that this should match any letter be it uppercase or lowercase (yes, I didn&#8217;t handle digits or underscores etc. which may be used in parameter/variable names, that is left as an exercise to the reader :P). The plus sign means the square bracket part may occur multiple times. This means that a parameter/variable name may have more than one such character. Finally we close this part with the round bracket.</p>
<p>The final part in the &#8220;Find what:&#8221; expression is a literal closing round bracket which, again, is escaped by being prefixed with a backslash.</p>
<p>In the &#8220;Replace with:&#8221; expression, the captured part in the previous expression (what is enclosed in the regular-expression-syntax round brackets) is expressed as $1, as first numbered. Finally we enclose this in double quotes because that is what we need.</p>
<p>As for why I had to rollback from C# 6 nameof expression to a stringly-typed version, that&#8217;s a story for another time, I guess.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.andrei.rinea.ro/2015/11/04/visual-studio-smart-replace/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Cross-platform browser keyboard shortcuts</title>
		<link>https://blog.andrei.rinea.ro/2015/04/09/cross-platform-browser-keyboard-shortcuts/</link>
					<comments>https://blog.andrei.rinea.ro/2015/04/09/cross-platform-browser-keyboard-shortcuts/#respond</comments>
		
		<dc:creator><![CDATA[Andrei Rinea]]></dc:creator>
		<pubDate>Thu, 09 Apr 2015 15:20:35 +0000</pubDate>
				<category><![CDATA[Operating Systems]]></category>
		<category><![CDATA[Tips & tricks]]></category>
		<category><![CDATA[Chrome]]></category>
		<category><![CDATA[Internet-Explorer]]></category>
		<category><![CDATA[keyboard]]></category>
		<category><![CDATA[Opera]]></category>
		<category><![CDATA[OSX]]></category>
		<category><![CDATA[productivity]]></category>
		<category><![CDATA[shortcut-keys]]></category>
		<category><![CDATA[Windows]]></category>
		<guid isPermaLink="false">http://blog.andrei.rinea.ro/?p=481</guid>

					<description><![CDATA[As of recently I began working on a Mac-book pro and I have to get used to a keyboard with different keys and different layout. One of the most used piece of software today is a browser. I routinely use &#8230;<p class="read-more"><a href="https://blog.andrei.rinea.ro/2015/04/09/cross-platform-browser-keyboard-shortcuts/">Read more &#187;</a></p>]]></description>
										<content:encoded><![CDATA[<p>As of recently I began working on a Mac-book pro and I have to get used to a keyboard with different keys and different layout. One of the most used piece of software today is a browser. I routinely use <a href="http://www.opera.com/">Opera</a> but there are still sites that don&#8217;t work well with it, although it uses pretty much the same rendering engine like <a href="https://www.google.com/chrome">Chrome</a>.</p>
<p>I suspect these issues arise from the fact that Chrome tends to become the new IE 6 for many web developers (i.e. : write a page, test it in Chrome, it works, the rest of browsers doesn&#8217;t matter to me, continue to next page etc.).</p>
<p>I consider, just like <a href="http://www.hanselman.com/blog">Scott Hanselman</a>, that using the keyboard is the most efficient way to command a computer (and not the mouse / touchpad) therefore I strive to use it to the max. However, switching from OS X to the Windows virtual machine back and forth can be confusing since there are different shortcuts. For example F5 in Windows refreshes the window while in OS X it doesn&#8217;t (be it because by default you have to press Fn and then F5 in order to send F5 otherwise a media function will be sent or because this key does not do this function).</p>
<p>Therefore I gathered a few useful shortcut keys that work in both Windows and OS X so I can use them. Many of them work across all major browsers (IE, Firefox, Chrome, Opera and Safari). Use Command (Cmd) key in OS X and Control (Ctrl) in Windows. I&#8217;ll include only the secondary key(s) in the table below since the primary key should be held down. I am planning to update this table several times.</p>
<table>
<thead>
<tr>
<td>Function</td>
<td>Second key</td>
<td>Internet Explorer</td>
<td>Opera for Windows</td>
<td>Opera for Mac</td>
<td>Chrome for Windows</td>
<td>Chrome for Mac</td>
</tr>
</thead>
<tbody>
<tr>
<td><strong>Q</strong>uit (Close) app</td>
<td>Q</td>
<td></td>
<td></td>
<td>✓</td>
<td> x</td>
<td>✓</td>
</tr>
<tr>
<td>Close tab (<strong>w</strong>indow)</td>
<td>W</td>
<td></td>
<td></td>
<td>✓</td>
<td> ✓</td>
<td>✓</td>
</tr>
<tr>
<td><strong>R</strong>efresh tab</td>
<td>R</td>
<td></td>
<td></td>
<td>✓</td>
<td> ✓</td>
<td>✓</td>
</tr>
<tr>
<td>Open a new <strong>t</strong>ab</td>
<td>T</td>
<td></td>
<td></td>
<td>✓</td>
<td> ✓</td>
<td>✓</td>
</tr>
<tr>
<td>Open last closed <strong>t</strong>ab</td>
<td>SHIFT-T</td>
<td></td>
<td></td>
<td>✓</td>
<td> ✓</td>
<td>✓</td>
</tr>
<tr>
<td>View so<strong>u</strong>rce</td>
<td>U</td>
<td></td>
<td></td>
<td>✓</td>
<td> ✓</td>
<td> x</td>
</tr>
<tr>
<td><strong>P</strong>rint page</td>
<td>P</td>
<td></td>
<td></td>
<td>✓</td>
<td> ✓</td>
<td>✓</td>
</tr>
<tr>
<td>Select <strong>a</strong>ll page content</td>
<td>A</td>
<td></td>
<td></td>
<td>✓</td>
<td> ✓</td>
<td>✓</td>
</tr>
<tr>
<td><strong>S</strong>ave current page to computer</td>
<td>S</td>
<td></td>
<td></td>
<td>✓</td>
<td> ✓</td>
<td>✓</td>
</tr>
<tr>
<td>A<strong>d</strong>d to favorites / bookmark</td>
<td>D</td>
<td></td>
<td></td>
<td>✓</td>
<td> ✓</td>
<td>✓</td>
</tr>
<tr>
<td><strong>F</strong>ind in page</td>
<td>F</td>
<td></td>
<td></td>
<td>✓</td>
<td> ✓</td>
<td>✓</td>
</tr>
<tr>
<td>Find a<strong>g</strong>ain</td>
<td>G</td>
<td></td>
<td></td>
<td>✓</td>
<td> ✓</td>
<td>✓</td>
</tr>
<tr>
<td>Show <strong>h</strong>istory</td>
<td>H</td>
<td></td>
<td></td>
<td></td>
<td> ✓</td>
<td> x</td>
</tr>
<tr>
<td>View downloads</td>
<td>J</td>
<td></td>
<td></td>
<td>✓</td>
<td> ✓</td>
<td> x</td>
</tr>
<tr>
<td>Focus the address bar</td>
<td>L</td>
<td></td>
<td></td>
<td>✓</td>
<td> ✓</td>
<td>✓</td>
</tr>
<tr>
<td>Undo</td>
<td>Z</td>
<td></td>
<td></td>
<td>✓</td>
<td> ✓</td>
<td>✓</td>
</tr>
<tr>
<td>Cut</td>
<td>X</td>
<td></td>
<td></td>
<td>✓</td>
<td> ✓</td>
<td>✓</td>
</tr>
<tr>
<td><strong>C</strong>opy</td>
<td>C</td>
<td></td>
<td></td>
<td>✓</td>
<td> ✓</td>
<td>✓</td>
</tr>
<tr>
<td>Paste</td>
<td>V</td>
<td></td>
<td></td>
<td>✓</td>
<td> ✓</td>
<td>✓</td>
</tr>
<tr>
<td>Open a <strong>n</strong>ew window</td>
<td>N</td>
<td></td>
<td></td>
<td>✓</td>
<td> ✓</td>
<td>✓</td>
</tr>
<tr>
<td>Open a new private window</td>
<td>SHIFT-N</td>
<td></td>
<td></td>
<td>✓</td>
<td> ✓</td>
<td>✓</td>
</tr>
</tbody>
</table>
<p>✓ = available<br />
x = unavailable<br />
[white_space] = not yet verified</p>
<p>(work in progress)</p>
<p>Dear readers, what other useful shortcuts is this table missing?</p>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.andrei.rinea.ro/2015/04/09/cross-platform-browser-keyboard-shortcuts/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Quick trick : Copy file path</title>
		<link>https://blog.andrei.rinea.ro/2015/02/04/quick-trick-copy-file-path/</link>
					<comments>https://blog.andrei.rinea.ro/2015/02/04/quick-trick-copy-file-path/#respond</comments>
		
		<dc:creator><![CDATA[Andrei Rinea]]></dc:creator>
		<pubDate>Wed, 04 Feb 2015 13:38:44 +0000</pubDate>
				<category><![CDATA[Utility]]></category>
		<category><![CDATA[Context-menu]]></category>
		<category><![CDATA[file]]></category>
		<category><![CDATA[path]]></category>
		<category><![CDATA[Windows]]></category>
		<guid isPermaLink="false">http://blog.andrei.rinea.ro/?p=477</guid>

					<description><![CDATA[Are you in a command line prompt and you need the full path of the file as an argument? You don&#8217;t need to type all of the path manually, not even pre-complete it using TABs. Just navigate to the file. &#8230;<p class="read-more"><a href="https://blog.andrei.rinea.ro/2015/02/04/quick-trick-copy-file-path/">Read more &#187;</a></p>]]></description>
										<content:encoded><![CDATA[<p>Are you in a command line prompt and you need the full path of the file as an argument? You don&#8217;t need to type all of the path manually, not even pre-complete it using TABs. Just navigate to the file.<br />
Here comes the trick part : hold SHIFT while right-clicking it. The context menu will look like so :</p>
<p><a href="https://blog.andrei.rinea.ro/wp-content/uploads/2015/02/SHIFT-right-click-copy-as-path-contextual-menu-command.png"><img loading="lazy" decoding="async" src="https://blog.andrei.rinea.ro/wp-content/uploads/2015/02/SHIFT-right-click-copy-as-path-contextual-menu-command.png" alt="SHIFT-right-click-copy-as-path-contextual-menu-command" class="aligncenter size-full wp-image-478" width="355" height="493" srcset="https://blog.andrei.rinea.ro/wp-content/uploads/2015/02/SHIFT-right-click-copy-as-path-contextual-menu-command.png 355w, https://blog.andrei.rinea.ro/wp-content/uploads/2015/02/SHIFT-right-click-copy-as-path-contextual-menu-command-216x300.png 216w" sizes="auto, (max-width: 355px) 100vw, 355px" /></a></p>
<p>I wrote before about <a href="https://blog.andrei.rinea.ro/2013/03/08/windows-explorer-contextual-menu-gotcha/">the SHIFT-right click</a> so this is somehow connected.</p>
<p>You will then have the full path of the file in the clipboard ready to be pasted wherever you need.</p>
<p>Hope this helps someone! <img src="https://s.w.org/images/core/emoji/16.0.1/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.andrei.rinea.ro/2015/02/04/quick-trick-copy-file-path/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Overriding and overloading in Java and .NET &#8211; differences, changes and gotchas</title>
		<link>https://blog.andrei.rinea.ro/2013/12/04/overriding-and-overloading-in-java-and-dot-net-differences-changes-and-gotchas/</link>
					<comments>https://blog.andrei.rinea.ro/2013/12/04/overriding-and-overloading-in-java-and-dot-net-differences-changes-and-gotchas/#respond</comments>
		
		<dc:creator><![CDATA[Andrei Rinea]]></dc:creator>
		<pubDate>Wed, 04 Dec 2013 09:15:46 +0000</pubDate>
				<category><![CDATA[Basics]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[CodeProject]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[.net]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[fundamentals]]></category>
		<category><![CDATA[Java SE 5]]></category>
		<category><![CDATA[OOP]]></category>
		<category><![CDATA[overloading]]></category>
		<category><![CDATA[overriding]]></category>
		<guid isPermaLink="false">http://blog.andrei.rinea.ro/?p=460</guid>

					<description><![CDATA[Foraying even more in the fundamentals of Java (coming from a .NET background) I&#8217;ve come across some interesting things, along with changes in Java SE 5. But first let&#8217;s clear up a bit these two notions (overloading and overriding). Overriding &#8230;<p class="read-more"><a href="https://blog.andrei.rinea.ro/2013/12/04/overriding-and-overloading-in-java-and-dot-net-differences-changes-and-gotchas/">Read more &#187;</a></p>]]></description>
										<content:encoded><![CDATA[<p>Foraying even more in the fundamentals of Java (coming from a .NET background) I&#8217;ve come across some interesting things, along with changes in Java SE 5. But first let&#8217;s clear up a bit these two notions (overloading and overriding).</p>
<h3>Overriding</h3>
<p><em>Is a language feature that allows a subclass/inheriting class to have a method identical (we&#8217;ll later see a slight exception to this) to the one in the base class/superclass in every way except the implementation. That is, to have the same return type, the same name, same paramater types, same parameter order, just the code (and the parameter names) can differ. </em></p>
<p>This is by no means a definitive definition, Wikipedia, .NET CLS&#8217;s and JLS may very well differ slightly.</p>
<p>A typical C# overriding example (yes, I also dislike animal examples but they are so eaaaasyyyy to come up with) :</p>
<pre class="brush: csharp; title: ; notranslate">
public class Dog 
{
    public virtual void MakeSound()
    {
         Console.WriteLine(&quot;Bark.&quot;);
    }
}

public class Hound : Dog
{
    public override void MakeSound()
    {
         Console.WriteLine(&quot;Wooofff!!!&quot;);
    }
}
</pre>
<p>Java developers unaware of the intricacies of C# will wonder what is that &#8220;virtual&#8221; thing. In C# all methods are &#8220;final&#8221; (sealed) by default unlike Java where methods are &#8220;virtual&#8221; (non-final / non-sealed) by default. This is a profound difference which we&#8217;ll discuss later. The &#8220;:&#8221; stands for &#8220;extends&#8221;. We&#8217;ll discuss the &#8220;override&#8221; keyword soon, also.</p>
<p>The equivalent piece of code in Java would look like :</p>
<pre class="brush: java; title: ; notranslate">
public class Dog {
    public void makeSound() {
        System.out.println(&quot;Bark.&quot;);
    }
}

public class Hound extends Dog {
    public void makeSound() {
        System.out.println(&quot;Woofff!!!&quot;);
    }
}
</pre>
<p><span id="more-460"></span><br />
Method overriding makes the platform select the method implementation at runtime. What does this mean? It means that having an instance of a Dog (be it effectively a Dog instance or an instance of a Hound which is also a Dog) and calling the MakeSound method will make the JVM / CLR select the appropiate implementation irrespective of the type of the reference to that instance. Here&#8217;s a code sample that illustrates it (perfectly equivalent for both C# and Java &#8211; except the casing of the MakeSound method) :</p>
<pre class="brush: csharp; title: ; notranslate">
Dog d = new Dog();
Hound h1 = new Hound();
Dog h2 = new Hound();

d.MakeSound();
h1.MakeSound();
h2.MakeSound();
</pre>
<p>The output will be</p>
<pre>
Bark.
Wooofff!!!
Wooofff!!!
</pre>
<p>For the d instance it is expected to have &#8220;Bark.&#8221; printed but notice how for the h2 instance, although the reference is of type Dog, the Hound implementation is used. This is because, just as I was saying above, the runtime will select the implementation for that exact instance type irrespective of the reference type.</p>
<p>As I promised earlier, let&#8217;s discuss a bit about the override keyword (C#) and the @Override annotation (Java). C# enforces you to use the override keyword when overriding (otherwise you would be using &#8220;method hiding&#8221; &#8211; a feature that we&#8217;ll discuss later) while Java does not. Since Java 5 the optional @Override annotation has been introduced, that you should use whenever you do overriding.</p>
<p>The main reason this @Override annotation is useful is that when doing an override, if you mistake the signature, the return type or even the method name the compiler will emit an error, stopping you from a potential overload instead of override. <a href="http://blog.andrei.rinea.ro/2013/01/29/java-vs-csharp-differences-part-1-of/">I&#8217;ve written about this before</a> but I&#8217;ll extend the older example :</p>
<p>Let&#8217;s say you have a `Person` class that has an ID and a name and you want two different instances that have the same ID and name to be semantically equal. So you write the class :</p>
<pre class="brush: java; title: ; notranslate">
public class Person {
    private int id;
    private String name;

    public int getId() { return id; }
    public void setId(int id) { this.id = id; }

    public String getName() { return name; }
    public void setName(String name) { this.name = name; }

    public int hashCode() { return id; }
    public boolean equals(Person other) { return this.id == other.id; }
}
</pre>
<p>Seems legit. We even took the time to override the hashCode function along with equals, as it is a good practice (in both Java and C#) to override these as a pair. Then we go ahead and write some code that exercises this class :</p>
<pre class="brush: java; title: ; notranslate">
Person john = new Person();
john.setId(1);
john.setName(&quot;John&quot;);
List&lt;Person&gt; persons = new ArrayList&lt;&gt;();
persons.add(john);
//...
Person johnnyBoy = new Person();
johnnyBoy.setId(1);
johnnyBoy.setName(&quot;John&quot;);

System.out.println(persons.contains(johnnyBoy));
</pre>
<p>Guess what, this will print &#8220;false&#8221; in spite of what some people might expect. The Object class (from which all class inherit directly or indirectly) contains the equals method which has a single argument of type Object and not Person. So the equals method on the Person class is not overriding but overloading. The contains method above uses the equals(Object) method which is NOT the one provided by us, which, by default, compares instances.</p>
<p>Let&#8217;s correct things :</p>
<pre class="brush: java; highlight: [12]; title: ; notranslate">
public class Person {
    private int id;
    private String name;

    public int getId() { return id; }
    public void setId(int id) { this.id = id; }

    public String getName() { return name; }
    public void setName(String name) { this.name = name; }

    public int hashCode() { return id; }
    @Override public boolean equals(Object other) { return this.id == ((Person)other).id; } // In production make sure to also check for a null argument.
}
</pre>
<p>Now the &#8220;testing code&#8221; will correctly print &#8220;true&#8221;. By applying @Override to equals (or any overriden method) the Java compiler will check that the provided method matches a base class overridable (non-final) method and triggers an error if the signature, name, parameter types differ or the base class method is final (&#8220;sealed&#8221; in C#).</p>
<p>This type of error will be less likely to appear in C# since C# developers were accustomed since the very first version to use the override keyword. They still can omit the keyword resulting in overload, but, again, it&#8217;s less likely.</p>
<p>A peculiar difference between Java and C# is that C# allows method hiding. This is a feature allows the inheriting class/subclass to declare a method with an identical return type, name and signature like a base class/superclass method which is sealed/final.<br />
Such a &#8220;hiding&#8221; method will require the new keyword or else the compiler will emit a warning (not an error!). Let&#8217;s revisit our mutts :</p>
<pre class="brush: csharp; highlight: [3]; title: ; notranslate">
public class Dog 
{
    public void MakeSound() // note that lacking the &quot;virtual&quot; keyword is equivalent to &quot;final&quot; in Java
    {
         Console.WriteLine(&quot;Bark.&quot;);
    }
}

public class Hound : Dog
{
    public void MakeSound()
    {
         Console.WriteLine(&quot;Wooofff!!!&quot;);
    }
}

// ...

Dog d = new Dog();
Hound h1 = new Hound();
Dog h2 = h1;

d.MakeSound();
h1.MakeSound();
h2.MakeSound();
</pre>
<p>Running this will output :</p>
<pre>
Bark.
Woofff!!!
Bark.
</pre>
<p>The surprise is that calling MakeSound on the h2 reference (which is of the Dog type) will invoke the Dog implementation rather than the Hound implementation <strong>even if the instance is of type Hound</strong>. Method hiding is a kind of overloading, which, we&#8217;ll see later uses early (method) binding and not late binding.</p>
<h3>Overloading</h3>
<p><em>Overloading is a language feature allowing two or more methods two have the same name but different parameter types, or a different number of parameters and maybe a different return type, be it in the same actual class or in the class hierarchy.</em></p>
<p>As we saw earlier the Person class had an equals method that accepted a single Person parameter while its base class (Object) had another method called also equals but having a single parameter of type Object.</p>
<p>Overloading is quite subtle both for the class producer and for the class consumer and should be used, in my opinion, with care and moderation.</p>
<p>Here&#8217;s another peculiarity between C# and Java, in the context of overloading. Let&#8217;s say you have a params/varargs overload along another method(s) :</p>
<p>C# version :</p>
<pre class="brush: csharp; title: ; notranslate">
class Program
{
    static void Main()
    {
        DoStuff(23);
    }

    public static void DoStuff(object obj)
    {
        Console.WriteLine(&quot;Single object parameter overload&quot;);
    }

    public static void DoStuff(params int&#x5B;] numbers)
    {
        Console.WriteLine(&quot;params integer array overload&quot;);
    }
}
</pre>
<p>Java version :</p>
<pre class="brush: java; title: ; notranslate">
public static void main(String&#x5B;] args) {
    doStuff(23);
}

public static void doStuff(Object obj)
{
    System.out.println(&quot;Single object parameter overload&quot;);
}

public static void doStuff(int... numbers)
{
    System.out.println(&quot;params integer array overload&quot;);
}
</pre>
<p>What do you think each of the version will print upon execution? This is <strong>not</strong> intuitive. The C# will select the params (probably because the params type is closer to the type of the value passed in?) while Java will select the overload with the closest &#8220;number&#8221; of parameters, the Object overload. Take care if you port code from one language to another</p>
<p>Another interesting situation is when you have to lump together two or more types, part of the same hierarchy like this :</p>
<pre class="brush: java; highlight: [14]; title: ; notranslate">
public void MakeSound(Dog dog) {
    System.out.println(&quot;Bark.&quot;);
}

public void MakeSound(Hound hound) {
    System.out.println(&quot;Wooofff!!!&quot;);
}

Dog&#x5B;] canides = new Dog&#x5B;2];
canides&#x5B;0] = new Dog();
canides&#x5B;1] = new Hound();

for(Dog canide : canides) {
    MakeSound(canide);
}
</pre>
<p>The compiler will make an early binding from the call at line 14 to the first overload of MakeSound (the one with the Dog parameter) irrespective of the actual type passed in. This &#8220;issue&#8221; happens irresepective of the platform (Java / .NET)</p>
<p>Enough for overloading and overriding for now, till the next time,</p>
<p>Take care and be (type)safe! 😛</p>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.andrei.rinea.ro/2013/12/04/overriding-and-overloading-in-java-and-dot-net-differences-changes-and-gotchas/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Numeric literals in Java 7 and in C#</title>
		<link>https://blog.andrei.rinea.ro/2013/11/27/numeric-literals-in-java-7-and-in-c-sharp/</link>
					<comments>https://blog.andrei.rinea.ro/2013/11/27/numeric-literals-in-java-7-and-in-c-sharp/#comments</comments>
		
		<dc:creator><![CDATA[Andrei Rinea]]></dc:creator>
		<pubDate>Wed, 27 Nov 2013 19:58:33 +0000</pubDate>
				<category><![CDATA[Basics]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[CodeProject]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[binary]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[DECIMAL]]></category>
		<category><![CDATA[hexa]]></category>
		<category><![CDATA[hexadecimal]]></category>
		<category><![CDATA[Integer]]></category>
		<category><![CDATA[Java 7]]></category>
		<category><![CDATA[long]]></category>
		<category><![CDATA[new features]]></category>
		<category><![CDATA[unsigned]]></category>
		<guid isPermaLink="false">http://blog.andrei.rinea.ro/?p=453</guid>

					<description><![CDATA[In both Java and C# it&#8217;s quite easy to express integer numerical literals. You can use both decimal and hexadecimal base to represent the value. Only for the hexadecimal base you need to prefix the value with 0x. For decimal &#8230;<p class="read-more"><a href="https://blog.andrei.rinea.ro/2013/11/27/numeric-literals-in-java-7-and-in-c-sharp/">Read more &#187;</a></p>]]></description>
										<content:encoded><![CDATA[<p>In both Java and C# it&#8217;s quite easy to express integer numerical literals. You can use both decimal and hexadecimal base to represent the value. Only for the hexadecimal base you need to prefix the value with 0x. For decimal base values that exceed 2^31-1 you need to provide a suffix (typically L) specifying this fact so the compiler will treat it like a long integer value. C# also provides unsigned long values (U prefix). In both languages the casing of the suffix does not matter.</p>
<p>Java : (notice, there are no unsigned primitives in Java)</p>
<pre class="brush: java; title: ; notranslate">
int i1 = 23; // integer, decimal
int h1 = 0x17; // integer, hexadecimal
long i2 = 12345678900L; // long integer (64 bit signed integer)
</pre>
<p>C# :</p>
<pre class="brush: csharp; title: ; notranslate">
int i1 = 23;
int h1 = 0x17;
ulong u1 = 12345678900U;
long i2 = 12345678900L;
</pre>
<p>As you might have read in <a href="http://blog.andrei.rinea.ro/2013/11/15/beginning-java-for-dot-net-developers/">Beginning Java for .NET developers</a> on slide 14, beginning in Java 7 you can also use two more features, that are not present in C# (at least at the time of this writing) :</p>
<p><em><strong>Binary base :</strong></em></p>
<pre class="brush: java; title: ; notranslate">
int b1 = 0b11001010;
</pre>
<p><em><strong>Underscores in literals (no matter which base) :</strong></em></p>
<pre class="brush: java; title: ; notranslate">
int b1 = 0b1100_1010;
long myCardNumber = 2315_2432_2111_1110;
int thousandsSeparated = 123_456_000;
</pre>
<p>The restrictions on the underscore placing is that you may not place it at the beginning of the value (prefix) or at the end (suffix). Also, for non-integer literals, you may not place it adjacent to the decimal separator.</p>
<p>For floating-point literals you must use the dot as decimal separator (if you need to specify a fraction, if not, you&#8217;re not required). You must use F for float-single-precision (32 bit) and D for float-double-precision (64 bit). Moreover in C# you have also the M suffix corresponding to the decimal (128 bit) value type.</p>
<p>C# :</p>
<pre class="brush: csharp; title: ; notranslate">
float x1 = 0.001F;
double x2 = 12.33D;
decimal x3 = 111.2M;
float x4 = 33F;
</pre>
<p>Java :</p>
<pre class="brush: java; title: ; notranslate">
float f1 = 0.001F;
double f2 = 12.31D;
float f3 = 123F;
</pre>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.andrei.rinea.ro/2013/11/27/numeric-literals-in-java-7-and-in-c-sharp/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
			</item>
		<item>
		<title>Enum &#8211; comparison of Java and .NET</title>
		<link>https://blog.andrei.rinea.ro/2013/11/26/enum-comparison-of-java-and-dot-net/</link>
					<comments>https://blog.andrei.rinea.ro/2013/11/26/enum-comparison-of-java-and-dot-net/#comments</comments>
		
		<dc:creator><![CDATA[Andrei Rinea]]></dc:creator>
		<pubDate>Tue, 26 Nov 2013 09:41:00 +0000</pubDate>
				<category><![CDATA[Basics]]></category>
		<category><![CDATA[Best practices]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[CodeProject]]></category>
		<category><![CDATA[Java]]></category>
		<guid isPermaLink="false">http://blog.andrei.rinea.ro/?p=437</guid>

					<description><![CDATA[A useful feature added in Java 1.5 (also known as J2SE 5.0, 2004) is the enum. In .NET enums have been present since the very first version (2002, and as a beta since 2000) but the engineers at Sun managed &#8230;<p class="read-more"><a href="https://blog.andrei.rinea.ro/2013/11/26/enum-comparison-of-java-and-dot-net/">Read more &#187;</a></p>]]></description>
										<content:encoded><![CDATA[<p>A useful feature added in Java 1.5 (also known as J2SE 5.0, 2004) is the enum. In .NET enums have been present since the very first version (2002, and as a beta since 2000) but the engineers at Sun managed to learn something from the shortcomings of the enums in .NET and provided more flexibility.</p>
<p>Let&#8217;s start with the simplest, the .NET implementation. In .NET all data types, including value types (equivalent of the primitive types) are part of the type hierarchy, being, indirectly inherited from System.Object (equiv. of java.lang.Object). The enums are just a specialization on top of exact numeric types, by default int (System.Int32). A typical declaration :</p>
<pre class="brush: csharp; highlight: [14]; light: false; title: ; notranslate">
public enum Month
{
    January,
    February,
    March,
    April,
    May,
    June,
    July,
    August,
    September,
    October,
    November,
    December,
}
</pre>
<p>Notice that the compiler is forgiving and doesn&#8217;t complain that after the last element we forgot to not place a comma. It will also work, of course, if we don&#8217;t place a comma after the last element. Behind the scenes the compiler will generate a value-type inheriting from System.Enum that will have 12 constants. By default these constants we&#8217;ll be of type Int32 and their value, again, by default, will start from 0 and increase by 1 for each member. January will be 0 and December will  be 11. Casts between the backing type (Int32 in this case) and the Months type will be allowed both at design time and at runtime.</p>
<p>You can also force individual values for each member</p>
<pre class="brush: csharp; light: false; title: ; notranslate">
public enum Month
{
    January = 3,
    February = 33,
    March = 222,
    April = 14,
    May = 20,
    June = 23,
    July,
    August,
    September,
    October,
    November,
    December,
}
</pre>
<p>In this case January will be equal to 3, February 33, &#8230;, June 23, July 24 (not specified but after a value-specified member, the next member will be the last value + 1 if specific value is not present. You can even force things into a bad situation like so : </p>
<pre class="brush: csharp; light: false; title: ; notranslate">
public enum Months
{
    January = 1,
    February,
    March,
    April,
    May,
    June,
    July = 1,
    August,
    September,
    October,
    November,
    December,
}
</pre>
<p>Guess what, not only this is completely valid, but there won&#8217;t be just two duplicate values (January and July being equal to themselves, and equal to 1) but also February will be 2, just like August and so on. Of course, this is not recommended. The compiler and the runtime will happily apply your stupid scheme but the humans will be confused. This excess of freedom is not to my liking but I can&#8217;t do much about it except counter-recommend it. Ideally you should not have to specify values for typical enums. Except for&#8230;<br />
<span id="more-437"></span><br />
Flag-value enums (these are akin to Java&#8217;s EnumSet)</p>
<pre class="brush: csharp; highlight: [15]; light: false; title: ; notranslate">
&#x5B;Flags]
public enum PizzaToppings
{
    None = 0,
    Mozzarella = 1,
    Pepperoni = 2,
    Anchovies = 4,
    Mushrooms = 8,
    Corn = 16
}

//...

PizzaToppings myFavs = PizzaToppings.Pepperoni | PizzaToppings.Anchovies;
Console.WriteLine(myFavs);
</pre>
<p>This will not print &#8220;6&#8221; although this will be the int value of myFavs. It will print &#8220;Pepperoni, Anchovies&#8221;.<br />
You&#8217;ll use the | (bitwise OR) to combine flags into a certain PizzaToppings instance. To detect a certain flag exists you can use any of these two ways :</p>
<pre class="brush: csharp; light: false; title: ; notranslate">
bool hasAnchovies1 = (myFavs &amp;amp; PizzaToppings.Anchovies) != PizzaToppings.None;
bool hasAnchovies2 = myFavs.HasFlag(PizzaToppings.Anchovies);
</pre>
<p>The first one is uglier, old-school (pre .NET 4.0) but it&#8217;s completely type-safe. The second one is cleaner, more elegant but you can place an instance of another enum in there. The compiler will not complain. Just the runtime which will throw an ArgumentException.</p>
<p>Converting strings into enum instances and vice-versa is trivial also :</p>
<pre class="brush: csharp; highlight: [5]; title: ; notranslate">
string s1 = &amp;quot;Anchovies&amp;quot;;
string s2 = &amp;quot;AnCHOviES&amp;quot;;

PizzaToppings pt1 = (PizzaToppings)Enum.Parse(typeof(PizzaToppings), s1);
PizzaToppings pt2 = (PizzaToppings)Enum.Parse(typeof(PizzaToppings), s2, ignoreCase: true);
PizzaToppings pt3 = (PizzaToppings)Enum.Parse(typeof(PizzaToppings), s2); // ArgumentException - by default the parsing does not ignore casing
</pre>
<p>(note : typeof(PizzaToppings) in C# is equivalent to PizzaToppings.class in Java; the strange third parameter in pt2 is a named parameter. Optionally you can include the parameter name followed by a colon before its value in order to improve the readability of the code. The compiler will &#8220;remove&#8221; this before compiling)</p>
<p>Being seen like the backing-value-type by the runtime you can very well use enums in a switch :</p>
<pre class="brush: csharp; title: ; notranslate">
switch(month) 
{
    case Month.January : 
        Console.WriteLine(&amp;quot;Cold, brrr....&amp;quot;); 
        break;
    case Month.February : 
        Console.WriteLine(&amp;quot;Still cold, brrr....&amp;quot;); 
        break;
// ...
}
</pre>
<p>Being value-types take in account boxing and unboxing performance implications when assigning instances to object fields or variables and vice-versa (this is similar to the autoboxing issues with primitives in Java).</p>
<p>A few best practices :</p>
<ul>
<li>Consider singular names for simple enums. For flagged enums consider plural forms.</li>
<li>Include a &#8220;Unknown&#8221;, &#8220;None&#8221;, &#8220;NotApplicable&#8221; etc. default value for each enum. This will help you in case you forget to initialize a field of that enum type, for example. You&#8217;ll be surprised by the default value and you&#8217;ll know (by a warning, exception etc.) that the initialization did not take place.</li>
<li>Do not abuse them. If you find yourself having an instance of enum in a class and in most of the methods switching or if&#8217;ing over that field then it might be a sign of a poor OOP design. Inheritance might be the key. <a href="http://blog.andrei.rinea.ro/2012/07/24/beware-of-switch/">Beware of switch</a>!</li>
<li>In switches based on enums consider including a default clause throwing an out of range exception in order to detect unhandled newly-added enum values.</li>
</ul>
<p>Finally, let&#8217;s metion that you can also use byte, short (Int16) and long (Int64) as backing type for your enums :</p>
<pre class="brush: csharp; highlight: [1]; title: ; notranslate">
public enum Mood : byte
{
    Happy,
    Bored,
    Sad,
    Angry,
    Ecstatic,
    Sleepy
}
</pre>
<p>Let&#8217;s consider this enough, for now, in the .NET world and let&#8217;s take a look in Java.</p>
<p>Before Java SE 5 there was no support for enums. People were cramming static final public fields (&#8220;constants&#8221; as seen in .NET, or more precisely public static readonly) in classes. There were and still are no static classes so they were forced to create a private constructor and even throw an exception in that private constructor like so :</p>
<pre class="brush: java; title: ; notranslate">
public class Mood {
    private Mood() {
        throw new IllegalOperationException(); // prevent accidental instantiation even within the class
    }

    public static final int HAPPY = 0;
    public static final int BORED = 1;
    public static final int SAD = 2;
    public static final int ANGRY = 3;
    public static final int ECSTATIC = 4;
    public static final int SLEEPY = 5;
}
</pre>
<p>It, obviously sucked and the only improvement was to move all these (except the constructor) in an interface. Yes, in Java you may declare final fields (&#8220;constants&#8221;) in an interface. Not much better&#8230; just a tiny bit.</p>
<p>This was lousy since there was no kind of type safety. There was no printing support either. Switching on an int and casing on these fields was a nightmare since you had no easy way to enumerate them and many more problems.</p>
<p>Final-ly (:P) Java SE 5 came out and the enum support with it. This was quite impressing (note, my background is .NET development) &#8211; the enum support. Here&#8217;s why :</p>
<ul>
<li>The enum types are reference types. This simplifies the null management (yes, in .NET there is nullable types support but it&#8217;s a bit less intuitive than a reference type).</li>
<li>Because of the previous point the enums can be treated like any class. This means you can implement interfaces, add methods, override (non-final / virtual) methods. We&#8217;ll later see some interesting things on this.</li>
<li>We still get the same support for switching, parsing from strings, converting to strings and all others. EnumSet helps with flagged enums.</li>
<li>You can have custom constructor(s) for your enum values</li>
</ul>
<p>There is no primitive type backing but that&#8217;s no loss. All enums inherit from java.lang.Enum and can override toString(). Each enum value is a different instance of the enum class, instantiated either with the default constructor either with a custom one. Here&#8217;s a full-fledged Java enum sample :</p>
<pre class="brush: java; title: ; notranslate">
public enum Planet {
    MERCURY (3.303e+23, 2.4397e6),
    VENUS   (4.869e+24, 6.0518e6),
    EARTH   (5.976e+24, 6.37814e6),
    MARS    (6.421e+23, 3.3972e6),
    JUPITER (1.9e+27,   7.1492e7),
    SATURN  (5.688e+26, 6.0268e7),
    URANUS  (8.686e+25, 2.5559e7),
    NEPTUNE (1.024e+26, 2.4746e7),
    PLUTO   (1.27e+22,  1.137e6);

    private final double mass;   // in kilograms
    private final double radius; // in meters
    Planet(double mass, double radius) {
        this.mass = mass;
        this.radius = radius;
    }
    public double mass()   { return mass; }
    public double radius() { return radius; }

    // universal gravitational constant  (m3 kg-1 s-2)
    public static final double G = 6.67300E-11;

    public double surfaceGravity() {
        return G * mass / (radius * radius);
    }
    public double surfaceWeight(double otherMass) {
        return otherMass * surfaceGravity();
    }
}
</pre>
<p>By default toString() returns the same value as name() but, as told earlier, it can be overriden. You can also obtain the ordinal of an enum instance within the enum with the ordinal() instance method.</p>
<p>Although it&#8217;s a reference type you can very well switch on an enum in Java, without any problem :</p>
<pre class="brush: java; title: ; notranslate">
switch(myPlanet) {
    case EARTH :
       System.out.println(&quot;Home&quot;);
       break;
</pre>
<p>Note that switch, in Java, does not require break (or any other control mechanism) for each branch. So you can easily (accidentally) fall-through and no compiler or runtime will save you.</p>
<p>Implementing interfaces in an enum can be done in two ways : on each member or at the enum level :</p>
<pre class="brush: java; title: ; notranslate">
// at member level
public enum Chores implements Runnable {
    TAKE_OUT_THE_TRASH {
        @Override
        public void run() { // ...
        }
    },
    DO_THE_LAUNDRY {
        @Override
        public void run() { // ...
        }
    }
}

public enum FunStuff implements Runnable {
    GO_OUT,
    VISIT_NEW_PLACES,
    // ...

    @Override
    public void run() { // ...
    }
}
</pre>
<p>All in all, I admire the better implementation of enums in Java and hope all platforms will have a better support in the future.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.andrei.rinea.ro/2013/11/26/enum-comparison-of-java-and-dot-net/feed/</wfw:commentRss>
			<slash:comments>4</slash:comments>
		
		
			</item>
		<item>
		<title>Beware of primitive wrappers in Java</title>
		<link>https://blog.andrei.rinea.ro/2013/11/20/beware-of-primitive-wrappers-in-java/</link>
					<comments>https://blog.andrei.rinea.ro/2013/11/20/beware-of-primitive-wrappers-in-java/#comments</comments>
		
		<dc:creator><![CDATA[Andrei Rinea]]></dc:creator>
		<pubDate>Wed, 20 Nov 2013 20:06:53 +0000</pubDate>
				<category><![CDATA[Basics]]></category>
		<category><![CDATA[CodeProject]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[autoboxing]]></category>
		<category><![CDATA[boxing]]></category>
		<category><![CDATA[data-type]]></category>
		<category><![CDATA[INT]]></category>
		<category><![CDATA[Integer]]></category>
		<category><![CDATA[nullable]]></category>
		<category><![CDATA[primitive]]></category>
		<category><![CDATA[value]]></category>
		<category><![CDATA[wrapper]]></category>
		<guid isPermaLink="false">http://blog.andrei.rinea.ro/?p=432</guid>

					<description><![CDATA[A .NET developer can be tricked into thinking that, for example, Integer is the same with int in Java. This is dangerous, in particular for a C# developer, because in C# System.Int32 is absolutely equivalent to int. &#8220;int&#8221; is just &#8230;<p class="read-more"><a href="https://blog.andrei.rinea.ro/2013/11/20/beware-of-primitive-wrappers-in-java/">Read more &#187;</a></p>]]></description>
										<content:encoded><![CDATA[<p>A .NET developer can be tricked into thinking that, for example, Integer is the same with int in Java. This is dangerous, in particular for a C# developer, because in C# System.Int32 is absolutely equivalent to int. &#8220;int&#8221; is just an alias.</p>
<p>In Java there are 8 primitive data types :</p>
<ul>
<li>byte (this is equivalent to sbyte in C#)</li>
<li>short (just like short / Int16 in C#)</li>
<li>int (just like int / Int32 in C#)</li>
<li>long (equivalent to long / Int64)</li>
<li>float (similar to float / Single)</li>
<li>double (similar to double / Double)</li>
<li>boolean (equivalent to bool / Boolean)</li>
<li>char (equivalent to char / Char)</li>
</ul>
<p>Now, these primitive types are not part of the Java Type System, as you might have seen in <a href="http://blog.andrei.rinea.ro/2013/11/15/beginning-java-for-dot-net-developers/">Beginning Java for .NET developers</a> in the slides, at page 21. These primitives (&#8220;value types&#8221;) have reference-type peers that are typically spelled the same (except int/Integer, char/Character) and just have the first letter capitalized. </p>
<p>Just like you should <a href="http://blog.andrei.rinea.ro/2013/11/19/avoid-comparing-strings-with-equals-equals-in-java/">avoid comparing strings with == in Java</a>, you should avoid declaring variables and fields of the reference-type peers, unless for a good reason.<br />
The main danger lies in the fact that being reference types and Java not having operator overloading (see <a href="http://blog.andrei.rinea.ro/2013/11/15/beginning-java-for-dot-net-developers/">Beginning Java for .NET developers</a>, slide 15) comparing two instances with the == operator will compare the instances and not the values.</p>
<p>&#8220;Oh, but you&#8217;re wrong!&#8221;, some of you might say, &#8220;I&#8217;ve written code like this and it worked!&#8221;. Code like this :</p>
<pre class="brush: java; title: ; notranslate">
public class Main {

    public static void main(String&#x5B;] args) {
        Integer i1 = 23;
        Integer i2 = 23;

        System.out.println(&quot;i1 == i2 -&gt; &quot; + (i1 == i2));
    }
}
</pre>
<p>Yes, it does print </p>
<pre>
i1 == i2 -> true
</pre>
<p>It will work to values up to 127 inclusive. Just replace 23 with 128 (or higher) and see how things go. I&#8217;ll wait here.<br />
Surprised? You shouldn&#8217;t be. This thing works because of a reason called integer caching (and there are ways to extend the interval on which it works &#8211; by default -128 up to 127 inclusive) but you shouldn&#8217;t rely on it.</p>
<p>Just use int where available or at least use the .intValue() method. </p>
<p>You might wonder what is the Integer (and the rest of the reference-type wrappers) there for? For a few things where they are needed. Once, because the generics in Java are lacking and you can&#8217;t define a generic type with primitive type(s) as type arguments. That&#8217;s right, you can&#8217;t have List<int>. Scary? Yes, especially when coming from .NET where generics are not implemented with type erasure. So you need to say List<Integer> and then watch out for reference comparison instead of value comparison, autoboxing performance loss and so on.</p>
<p>The other reason why you need these wrappers is because there is no nullable-types support in Java. So if you need to have a variable or a field that can store a primitive type but might also have to store a null then Integer will be better for you than int.</p>
<p>Just make sure you understand these implications and &#8230; be (type :P) safe!</p>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.andrei.rinea.ro/2013/11/20/beware-of-primitive-wrappers-in-java/feed/</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
			</item>
		<item>
		<title>Avoid comparing strings with == in Java</title>
		<link>https://blog.andrei.rinea.ro/2013/11/19/avoid-comparing-strings-with-equals-equals-in-java/</link>
					<comments>https://blog.andrei.rinea.ro/2013/11/19/avoid-comparing-strings-with-equals-equals-in-java/#comments</comments>
		
		<dc:creator><![CDATA[Andrei Rinea]]></dc:creator>
		<pubDate>Tue, 19 Nov 2013 18:00:46 +0000</pubDate>
				<category><![CDATA[Basics]]></category>
		<category><![CDATA[CodeProject]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[equals]]></category>
		<category><![CDATA[equals-equals]]></category>
		<category><![CDATA[gotcha]]></category>
		<category><![CDATA[string]]></category>
		<category><![CDATA[string-interning]]></category>
		<guid isPermaLink="false">http://blog.andrei.rinea.ro/?p=427</guid>

					<description><![CDATA[While beginning development in Java, especially if coming from a .NET background (but not necessarily) you might do string comparison with == in Java. Don&#8217;t do it. It will compare the string instances and not their effective value. You might &#8230;<p class="read-more"><a href="https://blog.andrei.rinea.ro/2013/11/19/avoid-comparing-strings-with-equals-equals-in-java/">Read more &#187;</a></p>]]></description>
										<content:encoded><![CDATA[<p>While beginning development in Java, especially if coming from a .NET background (but not necessarily) you might do string comparison with == in Java. Don&#8217;t do it. It will compare the string instances and not their effective value.<br />
You might even try it first to check if == really works, testing it in a wrong manner like so :</p>
<pre class="brush: java; title: ; notranslate">
public static void main(String&#x5B;] args) {

    String s1 = &quot;Abc&quot;;
    String s2 = &quot;Abc&quot;;

    System.out.println(&quot;s1 == s2 -&gt; &quot; + (s1 == s2));
}
</pre>
<p>This will output </p>
<pre>
s1 == s2 -> true
</pre>
<p>.. which might <a href="http://stackoverflow.com/q/4033625/1796">lead you to believe this works</a>. This does return the correct value because of a feature present in Java and .NET called <a href="http://en.wikipedia.org/wiki/String_interning">string interning</a> (not specific to Java or .NET).</p>
<p>Try to obtain a string instance dynamically like concatenating two existing instances and see how things don&#8217;t work anymore :</p>
<pre class="brush: java; title: ; notranslate">
public static void main(String&#x5B;] args) {

    String s1 = &quot;Abc&quot;;
    String s2 = &quot;Abc&quot;;

    // new lines :
    String capitalA = &quot;A&quot;;
    String bc = &quot;bc&quot;;
    String s3 = capitalA + bc;

    System.out.println(&quot;s1 == s2 -&gt; &quot; + (s1 == s2));
    // new line :
    System.out.println(&quot;s1 == s3 -&gt; &quot; + (s1 == s3));
}
</pre>
<pre>
s1 == s2 -> true
s1 == s3 -> false
</pre>
<p>Weird, huh? That&#8217;s because at compile time there are four distinct strings generated : &#8220;Abc&#8221; (once, even if referred twice), &#8220;A&#8221; and &#8220;bc&#8221;. The &#8220;Abc&#8221; instance obtained by joining &#8220;A&#8221; and &#8220;bc&#8221; will be generated at runtime and, of course, it will be a different instance than the first &#8220;Abc&#8221; instance. That&#8217;s why the result of the == operator comparison will be false.<br />
<span id="more-427"></span><br />
But the compiler can be smarter than you might expect. How&#8217;s that? Here&#8217;s how :</p>
<pre class="brush: java; title: ; notranslate">
public static void main(String&#x5B;] args) {

    String s1 = &quot;Abc&quot;;
    String s2 = &quot;Abc&quot;;

    String capitalA = &quot;A&quot;;
    String bc = &quot;bc&quot;;
    String s3 = capitalA + bc;

    // new line
    String s4 = &quot;A&quot; + &quot;bc&quot;;

    System.out.println(&quot;s1 == s2 -&gt; &quot; + (s1 == s2));
    System.out.println(&quot;s1 == s3 -&gt; &quot; + (s1 == s3));
    // new line
    System.out.println(&quot;s1 == s4 -&gt; &quot; + (s1 == s4));
}
</pre>
<p>.. resulting in :</p>
<pre>
s1 == s2 -> true
s1 == s3 -> false
s1 == s4 -> true
</pre>
<p>The compiler inferred the result of the string concatenation in the s4 initialization and then interned the resulted string, detected the already existing &#8220;Abc&#8221; instance and reused it.</p>
<p>Alright, that&#8217;s not the right way to do it, the correct way to do it is to use the .equals(String s) instance method of the String class. Like so :</p>
<pre class="brush: java; title: ; notranslate">
public static void main(String&#x5B;] args) {

    String s1 = &quot;Abc&quot;;

    String capitalA = &quot;A&quot;;
    String bc = &quot;bc&quot;;
    String s2 = capitalA + bc;

    System.out.println(&quot;s1.equals(s2) -&gt; &quot; +  s1.equals(s2));
}
</pre>
<p>This works nice :</p>
<pre>
s1.equals(s2) -> true
</pre>
<p>All&#8217;s well until we teak things a bit :</p>
<pre class="brush: java; title: ; notranslate">
public static void main(String&#x5B;] args) {

    String s1 = null;
    String s2 = null;

    System.out.println(&quot;s1.equals(s2) -&gt; &quot; +  s1.equals(s2));
}
</pre>
<p>Guess what, it&#8217;s not &#8220;true&#8221; that&#8217;s being displayed but the stack trace of a NullPointerException. Your solution might be <a href="http://stackoverflow.com/q/8336856/1796">some weird ternary expression</a> (yuck) that looks like so :</p>
<pre class="brush: java; title: ; notranslate">
public static void main(String&#x5B;] args) {

    String s1 = null;
    String s2 = null;

    boolean b = s1 == null ? s2 == s1 : s1.equals(s2);
    System.out.println(b);
}
</pre>
<p>You can extract this expression into a static method in a helper class if you find yourself doing this often.</p>
<p>As a final aspect to consider, if one of the two strings is a constant value you can still use equals on that one like so : </p>
<pre class="brush: java; title: ; notranslate">
public static void main(String&#x5B;] args) {

    String s1 = getData();
    String s2 = &quot;someValue&quot;;

    System.out.println(s2.equals(s1));
    System.out.println(&quot;someOtherValue&quot;.equals(s1));
}
</pre>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.andrei.rinea.ro/2013/11/19/avoid-comparing-strings-with-equals-equals-in-java/feed/</wfw:commentRss>
			<slash:comments>5</slash:comments>
		
		
			</item>
		<item>
		<title>Simulating C# ref parameter in Java</title>
		<link>https://blog.andrei.rinea.ro/2013/11/17/simulating-csharp-ref-parameter-in-java/</link>
					<comments>https://blog.andrei.rinea.ro/2013/11/17/simulating-csharp-ref-parameter-in-java/#comments</comments>
		
		<dc:creator><![CDATA[Andrei Rinea]]></dc:creator>
		<pubDate>Sun, 17 Nov 2013 20:13:48 +0000</pubDate>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[CodeProject]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[out]]></category>
		<category><![CDATA[parameter]]></category>
		<category><![CDATA[pass-by-reference]]></category>
		<category><![CDATA[ref]]></category>
		<guid isPermaLink="false">http://blog.andrei.rinea.ro/?p=415</guid>

					<description><![CDATA[As I was saying a few posts ago (Beginning Java for .NET Developers), on the 8th slide, there are no ref and no out method parameter modifiers. These are rarely used in .NET anyway so you can&#8217;t really complain of &#8230;<p class="read-more"><a href="https://blog.andrei.rinea.ro/2013/11/17/simulating-csharp-ref-parameter-in-java/">Read more &#187;</a></p>]]></description>
										<content:encoded><![CDATA[<p>As I was saying a few posts ago (<a href="http://blog.andrei.rinea.ro/2013/11/15/beginning-java-for-dot-net-developers/">Beginning Java for .NET Developers</a>), on the 8th slide, there are no <strong>ref</strong> and no <strong>out</strong> method parameter modifiers.</p>
<p>These are rarely used in .NET anyway so you can&#8217;t really complain of their lack in Java. Furthermore, some of their legitimate uses, such as the static <strong>TryParse</strong> methods on value types are not applicable in Java. Why? Because in Java the primitives (int, long, byte etc. &#8211; the equivalent of the basic value types in .NET) are not part of the type hierarchy and they have reference-type wrappers (Integer etc.) which would solve the issue of returning the result in case of &#8216;TryParse&#8217; style of parsing. How&#8217;s that? It&#8217;s like :</p>
<pre class="brush: java; title: ; notranslate">
public static Integer tryParseInt(String intString) {
    try {
        return Integer.parseInt(intString);
    } catch (NumberFormatException e) {
        return null;
    }
}
</pre>
<p>No need for a &#8216;out&#8217; parameter or &#8216;ref&#8217;. But! Let&#8217;s try and simulate &#8216;ref&#8217; using a generic class written this way :</p>
<pre class="brush: java; title: ; notranslate">
public class Ref&lt;T&gt; {
    private T value;

    public Ref() {
    }

    public Ref(T value) {
        this.value = value;
    }

    public T getValue() {
        return value;
    }

    public void setValue(T value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return value == null ? null : value.toString();
    }
}
</pre>
<p><span id="more-415"></span><br />
Now, suppose we have a class PhoneNumber that expects a number as [firstPart]-[secondPart] (both being integer, positive numbers). This class could look like :</p>
<pre class="brush: java; title: ; notranslate">
public class PhoneNumber {

    private final int firstPart;
    private final int secondPart;

    private final static int NOT_FOUND = -1;

    public PhoneNumber(int firstPart, int secondPart) {
        this.firstPart = firstPart;
        this.secondPart = secondPart;
    }

    public int getFirstPart() {
        return firstPart;
    }

    public int getSecondPart() {
        return secondPart;
    }

    @Override
    public String toString() {
        return Integer.toString(firstPart) + &quot;-&quot; + Integer.toString(secondPart);
    }
}
</pre>
<p>We will also suppose that another allowed string representation of a phone number would be &#8220;private&#8221; (irrespective of the casing). We want to create a static tryParse method on that class. If the given string is not a valid phone number we could return null. But in case of the &#8220;private&#8221; value we would be also forced to return null. There would be an ambiguity. Therefore we would need some kind of disambiguation. One way would be to use the Ref<T> class defined above like so :</p>
<pre class="brush: java; title: ; notranslate">
public static boolean tryParse(String phoneNumberString, Ref&lt;PhoneNumber&gt; phoneNumber) {
    if (phoneNumberString == null || phoneNumberString.isEmpty()) return false;
    if (phoneNumber == null) throw new IllegalArgumentException();

    phoneNumber.setValue(null);
    if (phoneNumberString.toLowerCase().equals(&quot;private&quot;)) {
        return true;
    }
    int dashIndex = phoneNumberString.indexOf('-');
    if (dashIndex == NOT_FOUND || dashIndex == 0 || dashIndex == phoneNumberString.length() - 1) {
        return false;
    }

    String firstPartString = phoneNumberString.substring(0, dashIndex);
    String secondPartString = phoneNumberString.substring(dashIndex + 1, phoneNumberString.length());
    int firstPart;
    int secondPart;

    try {
        firstPart = Integer.parseInt(firstPartString);
        secondPart = Integer.parseInt(secondPartString);
    } catch (NumberFormatException e) {
        return false;
    }

    phoneNumber.setValue(new PhoneNumber(firstPart, secondPart));
    return true;
}
</pre>
<p>An example of using that code could be</p>
<pre class="brush: java; title: ; notranslate">
    public static void main(String&#x5B;] args) {
        String s1 = &quot;555-1234&quot;;
        String s2 = &quot;555&quot;;
        String s3 = &quot;saldkfjasdf&quot;;
        String s4 = &quot;PRIVATE&quot;;
        String s5 = &quot;&quot;;
        String s6 = null;

        Ref&lt;PhoneNumber&gt; pn1 = new Ref&lt;PhoneNumber&gt;();
        Ref&lt;PhoneNumber&gt; pn2 = new Ref&lt;PhoneNumber&gt;();
        Ref&lt;PhoneNumber&gt; pn3 = new Ref&lt;PhoneNumber&gt;();
        Ref&lt;PhoneNumber&gt; pn4 = new Ref&lt;PhoneNumber&gt;();
        Ref&lt;PhoneNumber&gt; pn5 = new Ref&lt;PhoneNumber&gt;();
        Ref&lt;PhoneNumber&gt; pn6 = new Ref&lt;PhoneNumber&gt;();

        boolean b1 = PhoneNumber.tryParse(s1, pn1);
        boolean b2 = PhoneNumber.tryParse(s2, pn2);
        boolean b3 = PhoneNumber.tryParse(s3, pn3);
        boolean b4 = PhoneNumber.tryParse(s4, pn4);
        boolean b5 = PhoneNumber.tryParse(s5, pn5);
        boolean b6 = PhoneNumber.tryParse(s6, pn6);

        System.out.println(&quot;Parsing '&quot; + s1 + &quot;' : &quot; + b1 + &quot;, Ph# : &quot; + pn1);
        System.out.println(&quot;Parsing '&quot; + s2 + &quot;' : &quot; + b2 + &quot;, Ph# : &quot; + pn2);
        System.out.println(&quot;Parsing '&quot; + s3 + &quot;' : &quot; + b3 + &quot;, Ph# : &quot; + pn3);
        System.out.println(&quot;Parsing '&quot; + s4 + &quot;' : &quot; + b4 + &quot;, Ph# : &quot; + pn4);
        System.out.println(&quot;Parsing '&quot; + s5 + &quot;' : &quot; + b5 + &quot;, Ph# : &quot; + pn5);
        System.out.println(&quot;Parsing '&quot; + s6 + &quot;' : &quot; + b6 + &quot;, Ph# : &quot; + pn6);
    }
</pre>
<p>Upon running this piece of code we would receive :</p>
<pre>
Parsing '555-1234' : true, Ph# : 555-1234
Parsing '555' : false, Ph# : null
Parsing 'saldkfjasdf' : false, Ph# : null
Parsing 'PRIVATE' : true, Ph# : null
Parsing '' : false, Ph# : null
Parsing 'null' : false, Ph# : null
</pre>
<p>This way we were able to simulate a ref parameter. However some might argue that this is not the only solution and we could have defined another class called ParseResult<T> encapsulating a boolean representing the success of parsing and a T representing the parsed value (in case the parsing succeeded). Of course we could do this, it would be a good alternative. However, for the C# / .NET developers the Ref<T> would be closer to their existing knowledge.</p>
<p>Regarding the out parameter things are not so bright. That&#8217;s because of two things : first, the called method should be enforced to set at least once a value to the out parameter on each execution path and in C# this is enforced by the compiler while in Java I see no way to enforce it. Second, the solution (if one would exist) should restrict the called method to only set the value but not read it while the method caller should be able to read and write.</p>
<p>In conclusion at least we can simulate ref with Ref<T>. This pattern is also used in EventArgs and other derived classes, in .NET.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.andrei.rinea.ro/2013/11/17/simulating-csharp-ref-parameter-in-java/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
			</item>
		<item>
		<title>Preparing the development environment for Java &#8211; Windows and Ubuntu</title>
		<link>https://blog.andrei.rinea.ro/2013/11/16/preparing-the-development-environment-for-java-windows-and-ubuntu/</link>
					<comments>https://blog.andrei.rinea.ro/2013/11/16/preparing-the-development-environment-for-java-windows-and-ubuntu/#respond</comments>
		
		<dc:creator><![CDATA[Andrei Rinea]]></dc:creator>
		<pubDate>Sat, 16 Nov 2013 19:49:16 +0000</pubDate>
				<category><![CDATA[Basics]]></category>
		<category><![CDATA[CodeProject]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[IDE]]></category>
		<category><![CDATA[IntelliJ IDEA]]></category>
		<category><![CDATA[JDK]]></category>
		<category><![CDATA[JRE]]></category>
		<category><![CDATA[Oracle]]></category>
		<category><![CDATA[Ubuntu]]></category>
		<category><![CDATA[Windows]]></category>
		<guid isPermaLink="false">http://blog.andrei.rinea.ro/?p=398</guid>

					<description><![CDATA[Unlike .NET development where everything is streamlined and well-aligned, starting from the OS, the framework, the tools, the IDE and all others being written by one company, in Java development you&#8217;ll experience &#8220;freedom&#8221;(1) of choice. I&#8217;ll start with a gentle &#8230;<p class="read-more"><a href="https://blog.andrei.rinea.ro/2013/11/16/preparing-the-development-environment-for-java-windows-and-ubuntu/">Read more &#187;</a></p>]]></description>
										<content:encoded><![CDATA[<p>Unlike .NET development where everything is streamlined and well-aligned, starting from the OS, the framework, the tools, the IDE and all others being written by one company, in Java development you&#8217;ll experience &#8220;freedom&#8221;(1) of choice. I&#8217;ll start with a gentle introduction which the experienced may very well skip to avoid getting bored.</p>
<p>In order to get started developing in Java we&#8217;ll need the following :</p>
<ol>
<li>An <strong>OS</strong>. I&#8217;ll showcase Windows and Ubuntu (Linux).</li>
<li>A Java <em>JRE</em>. This is the most basic component required to run Java programs.</li>
<li>A Java <strong>JDK</strong>. The JDK or Java SDK (IBM calls it that way) typically includes the JRE plus a compiler, tools for running various types of Java programs, packaging tools, extra class libraries and many more.</li>
<li>An <strong>IDE</strong> &#8211; <a href="http://en.wikipedia.org/wiki/Integrated_development_environment">Integrated Development Environment</a>. This is typically an MDI (<a href="http://en.wikipedia.org/wiki/Multiple_document_interface">Multi-Document Interface</a>) application which provides certain convenience features for the developer :
<ul>
<li>Syntax highlighting &#8211; keywords are displayed in a certain color, local variables in another etc.</li>
<li>Code completion &#8211; instead of having to type the whole keyword, or class identifier, a member and so on, an autocompletion prompt will appear (usually triggered by the user typing a dot or other notable event) easing your typing and avoiding typos.</li>
<li>Interactive debugging &#8211; Allowing the user to control the execution of the program by inserting breakpoints, stepping over, into or out of code, watching expressions (variables, fields etc.), modifying internal data or even (very few IDEs allow) stepping back.</li>
<li>Tracing &#8211; in case you need to inspect internal data but breaking into the debugger cancels the bug or triggers other unwanted condition or the data changes too fast, you can watch expressions in a specially designed tool window without interrupting the flow of the debugged program</li>
<li>Source control integration &#8211; allows the user to send/push/checkin/etc changes to file(s) into a repository, obtaining the latest version, comparing versions, merging, branching and many more operations</li>
<li>Visual designers &#8211; For UI modules or elements most IDEs offer some kind of preview of the developed interface, showing the developer pretty much how things will look and behave without needing to recompile, run and browsing to that particular interface</li>
<li>Packaging and deployment &#8211; Features for creating a package of the application, be it JAR, WAR, DLL, ZIP, APK etc. Furthermore many IDEs will help you push a site to a webhosting provider, cloud service and so on.</li>
<li>.. and a whole lot more but let&#8217;s try to keep things shorter</li>
</ul>
</li>
</ol>
<p><span id="more-398"></span></p>
<h3>The OS</h3>
<p>There&#8217;s not much to cover, in my opinion, here. I guess if you reached the level of developer you&#8217;ll be able to install an OS. In fact just reading this article on a PC usually means that you already have an OS installed. Both Windows and Ubuntu have a simple install process, ship as a CD or ISO image that you can boot from a USB drive, a DVD, or insert into a Virtual Machine.</p>
<p>In my experience I&#8217;ve used Windows 8.1 64 bit and Ubuntu 13 in a VMware virtual machine. Recommended hardware specs, IMHO would be :</p>
<ul>
<li>1.5GHz+ Quad-core CPU</li>
<li>4 GB RAM</li>
<li>a decent SSD</li>
</ul>
<p>Sure, these aren&#8217;t the bare minimum requirements. All presented here could run on a single-core 1GHz CPU with 1GB RAM and 5400rpm HDD. The recommended specs are here to tell you where the comfort zone begins.</p>
<p>Java 7 (the latest at the time of this writing) supports Windows down to XP SP3 and Ubuntu since 10. <a href="http://www.java.com/en/download/help/sysreq.xml">The details of the system requirements</a> are quite interesting, the minimum amount of RAM being 64 MB.</p>
<p>Since Java has this promise of Write Once Run Everywhere (contradicted in practice by almost all my Java fellow developers but let&#8217;s skip that part) I&#8217;ve had installed both OS&#8217;es so I can see how well this goes.</p>
<p>One notable part is that Ubuntu (like most of the *NIX platforms) is not so friendly when installing certain pieces of software even with the advent of apg-get, rpm and so on.</p>
<h3>JRE</h3>
<p>Windows does not come by default with any JRE or JDK, the java support being null. Ubuntu 13 comes pre-loaded with OpenJDK JRE. This is just the JRE and not a JDK in spite of its name. Furthermore it will not support JavaFX and IntelliJ IDEA IDE will pretty much reject it. So, IMHO, Ubuntu has, at least for me, no Java support out-of-the-box either.</p>
<h3>JDK</h3>
<p>Since we have to install a JDK anyway (which typically includes a JRE) I chose the &#8216;original&#8217; vendor, Oracle (former being Sun but acquired a few years ago by Oracle). Typically the Oracle JDK has the widest support for Java technologies (such as JavaFX) and it&#8217;s well maintained. Others, such as IBM, does not even support the #1 OS on the market, Microsoft Windows. The Ubuntu Software Center, which simplifies installing of software, having a graphical interface, does not encourage the installing of the Oracle JDK. More on this shortly.</p>
<p>Windows has a clean experience, you just go to the <a href="http://www.oracle.com/technetwork/java/javase/downloads/jdk7-downloads-1880260.html">JDK downloads page</a> (you don&#8217;t need to bookmark this link, just type &#8216;download jdk&#8217; in your favorite search engine, such as <a href="https://www.collectiveray.com/wd/hosting/wpengine-review">WPEngine review</a>, get the first Oracle link and choose JDK when confronted with JDK, JREs and others). Select your platform (Windows x64 in my case), download the .EXE file, run it, next -&gt; next -&gt; finish.<br />
Be careful that recently Oracle has <a href="http://news.kynosarges.org/2013/01/23/windows-crapware-flourishes/">started to bundle some crapware &#8211; like Ask Toolbar extension</a> along with the JDK, uncheck the necessary boxes :</p>
<p><img loading="lazy" decoding="async" class="aligncenter size-full wp-image-402" alt="OracleIsLame" src="http://blog.andrei.rinea.ro/wp-content/uploads/2013/11/OracleIsLame.png" width="506" height="383" srcset="https://blog.andrei.rinea.ro/wp-content/uploads/2013/11/OracleIsLame.png 506w, https://blog.andrei.rinea.ro/wp-content/uploads/2013/11/OracleIsLame-300x227.png 300w" sizes="auto, (max-width: 506px) 100vw, 506px" /></p>
<p>Let&#8217;s get back to Ubuntu now. There are two ways to install the Oracle JDK on Ubuntu, that I know of and tried : the hard one and the easy one. The hard one means doing it manually all the way, by downloading the .tar.gz package from Oracle, unpacking it, placing the files in the right directories, editing the JAVA_HOME environment variable, setting up alternative aliases and many more manual steps that are prone to mistyping and hair pulling during and after the process. If for some reason you want to know the details or you are constrained to use this route, then follow <a href="http://www.wikihow.com/Install-Oracle-Java-on-Ubuntu-Linux">this link</a> (&#8220;don&#8217;t worry&#8221; there are &#8220;only&#8221; 17 steps).</p>
<p>The easy one is described at &#8216;<a href="http://www.blogs.digitalworlds.net/softwarenotes/?p=41">Install Java JDK 7 on Ubuntu 12.04 (JavaFX is included in the installation)</a>&#8216;. Basically you just open up a terminal window and :</p>
<pre>
<ul>
	<li>sudo add-apt-repository ppa:webupd8team/java</li>
	<li>sudo apt-get-update</li>
	<li>sudo apt-get install oracle-jdk7-installer</li>
</ul>
</pre>
<p>The first command adds a new APT repository so the third command will be able to get the Oracle JDK 7 Installer. The second command updates all APT packages so all dependencies will be up to date. Finally the third command will install the Oracle JDK 7 Installer. This will self-start after download and will display a text-GUI which will do all those 17 steps in the manual way described above. The bulk of the work will be downloading the .tar.gz from Oracle and will display a kind of progress bar. Finally the JDK will be installed and operational.</p>
<p>On both OS&#8217;es listed above the JDK will be operational without needing to restart the OS or do anything else. Regardless of the OS open up a terminal window (Win-R -> CMD [ENTER] for Windows) and type:</p>
<pre>java -version</pre>
<p>This will test that the java executable, part of the JRE is correctly installed, accessible in the PATH and if these conditions are met, it will display the exact version similar to :</p>
<p>[Windows]</p>
<pre>
java version "1.7.0_25"
Java(TM) SE Runtime Environment (build 1.7.0_25-b17)
Java HotSpot(TM) 64-Bit Server VM (build 23.25-b01, mixed mode)
</pre>
<p>[Ubuntu]</p>
<pre>
java version "1.7.0_45"
Java(TM) SE Runtime Environment (build 1.7.0_45-b18)
Java HotSpot(TM) 64-Bit Server VM (build 24.45-b08, mixed mode)
</pre>
<p>Notice that the versions differ slightly (update 25 vs update 45) but this is irrelevant. The same features are present, the newer one just has a few more bugfixes.</p>
<p>Do the same for </p>
<pre>javac -version</pre>
<p>This will test the same about the Java compiler (that&#8217;s what the final c stands for). The compiler will probably be less verbose but that&#8217;s not an issue.<br />
Having finished this, we&#8217;re left just with installing the IDE.</p>
<h3>IDE</h3>
<p>There are three popular Java IDEs available (and countless other less heard-of) :</p>
<ul>
<li><a href="http://www.eclipse.org/downloads/">Eclipse</a></li>
<li><a href="https://netbeans.org/downloads/">NetBeans</a></li>
<li><a href="http://www.jetbrains.com/idea/download/">IntelliJ IDEA</a></li>
</ul>
<p>Eclipse seems bloated to me and a bit alien, NetBeans ok-ish but coming from a .NET development background with many years of ReSharper (Visual Studio plug-in developed by JetBrains, makers of IntelliJ IDEA), I&#8217;ve chosen IntelliJ IDEA. Pretty much the same keyboard shortcuts, same behavior, feeling. Of course I&#8217;ve tried them all and there were a few advantages which NetBeans had over IntelliJ IDEA, mainly at JavaFX templates and JavaFX autocompletion support. But that&#8217;s pretty much from the fact that both JavaFX and NetBeans are being developed by the same company, Oracle.</p>
<p>On Windows NetBeans and IntelliJ IDEA provide smooth installers while Eclipse provides a simple archive that you just extract somewhere and just run eclipse.exe (you might create a shortcut somewhere to ease startup the next times).</p>
<p>On Ubuntu you can install any of the three main IDEs via Ubuntu Software Center but you&#8217;ll get old versions. For Eclipse it&#8217;s 3.8.1 vs 4.3.1 (significant differences, I assure you), for NetBeans it&#8217;s 7.0.1 vs 7.4 (this was quite touchy since 7.0.1 doesn&#8217;t include JavaFX support, and I played with JavaFX for a while) and finally, for IntelliJ IDEA it&#8217;s 12.1.0 vs 12.1.6</p>
<p>JetBrains had the most care of updating the Ubuntu Software Package and they have much better technical support for it. Therefore I just installed it using Ubuntu Software Center. For NetBeans I had to download it manually, tried to start the .sh file directly but there was a glitch, it seemed to require chmod-ing to make it executable. I thought you could just ship it executable directly from within the .tar.gz but my Linux skills are quite lacking so it could be either way. In the end it starts and works. Eclipse did not get tested.</p>
<p>Of course, subjectively, I had a lot of glitches and misunderstandings working on Ubuntu after 18 years of using Windows. Things ranging from having the control icons in the left side of the title bar (a la Mac), snapping windows to the edges of the monitor involves keeping them there for, what seems like, 500ms in order to stay snapped. At least the bash tab autocomplete works quite well.</p>
<p>All in all things went ok, I&#8217;ve developed a toy app on JavaFX (on Windows), JAR&#8217;d it and dragged it over in the Ubuntu machine and worked excellent. Maybe it&#8217;s because the app is extremely simple or maybe that promise of Write Once Run Everywhere is respected in the most cases&#8230;</p>
<p>While toying around in IntelliJ I&#8217;ve assembled the most common (at least for me) commands and their associated shortcuts. Most mature IDEs offer these features or similar ones. Here is my set :</p>
<ul>
<li>Force completion &#8211; CTRL-Space</li>
<li>Type lookup (independent of current imports) &#8211; CTRL-ALT-Space</li>
<li>Line-comment selection &#8211; CTRL-/</li>
<li>Increase / decrease indent &#8211; TAB / SHIFT-TAB</li>
<li>Quick-fix / Intent &#8211; ALT-ENTER. <strong><em>Really often used!</em></strong></li>
<li>Reformat file &#8211; CTRL-ALT-L</li>
<li>Duplicate line &#8211; CTRL-D</li>
<li>Cut current line (&#8220;delete to clipboard&#8221;) &#8211; SHIFT-DEL without selection</li>
<li>Debug project &#8211; SHIFT-F9</li>
<li>Step over &#8211; F8</li>
<li>Step into &#8211; F7</li>
<li>Step out &#8211; SHIFT-F8</li>
<li>Resume &#8211; F9</li>
<li>Go to type (class) &#8211; CTRL-N</li>
<li>Go to file &#8211; CTRL-SHIFT-N</li>
<li>Go to declaration &#8211; CTRL-B</li>
<li>Go to implementation &#8211; CTRL-ALT-B</li>
</ul>
<p>For more shortcuts consult <a href="http://www.jetbrains.com/idea/docs/IntelliJIDEA_ReferenceCard.pdf">the official &#8220;cheatsheet&#8221;</a> from JetBrains.</p>
<p>At this moment I consider to have at least two development environments set up and ready to run. In the next posts I&#8217;ll tackle some Java syntax and platform peculiarities with examples and cautionary tales.</p>
<p><strong>LATER UPDATE :</strong><br />
Regarding Ubuntu 13, there are two (or more?) clashing keyboard shortcuts : CTRL-ALT-L, which should reformat the current source file but instead is caught at the OS level and locks the OS prompting for the user&#8217;s password. The other clash is CTRL-ALT-T, which should surround the selection with a template (for example try-catch or try-finally etc) but it&#8217;s also caught at the OS level and starts a new terminal window instead.<br />
In order to disable this shortcuts in Ubuntu go to &#8220;Start&#8221; (press the Win key), type &#8220;System settings&#8221;, open it, then open the keyboard window, switch to &#8220;Shortcuts&#8221;. Here, select the &#8220;Launchers&#8221; category and &#8220;Launch terminal&#8221; command. Press backspace and the shortcut is cleared. Then do the same, in the &#8220;System&#8221; category at the &#8220;Lock screen&#8221; command.<br />
_________________________<br />
(1) &#8211; There&#8217;s enough freedom of choice on Windows / .NET too. What really bothered me is that this freedom means usually having a lot of components developed in every other imaginable way/style and assembling them together is sometimes harder than solving a murder mistery. Things get better over time with the help of Maven, Apache Software Foundation and even Oracle.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.andrei.rinea.ro/2013/11/16/preparing-the-development-environment-for-java-windows-and-ubuntu/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Beginning Java for .NET Developers</title>
		<link>https://blog.andrei.rinea.ro/2013/11/15/beginning-java-for-dot-net-developers/</link>
					<comments>https://blog.andrei.rinea.ro/2013/11/15/beginning-java-for-dot-net-developers/#comments</comments>
		
		<dc:creator><![CDATA[Andrei Rinea]]></dc:creator>
		<pubDate>Fri, 15 Nov 2013 11:12:07 +0000</pubDate>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[CodeProject]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[.net]]></category>
		<category><![CDATA[Android]]></category>
		<category><![CDATA[Eclipse]]></category>
		<category><![CDATA[IBM]]></category>
		<category><![CDATA[IntelliJ IDEA]]></category>
		<category><![CDATA[language]]></category>
		<category><![CDATA[Linux]]></category>
		<category><![CDATA[Netbeans]]></category>
		<category><![CDATA[OpenJDK]]></category>
		<category><![CDATA[Oracle]]></category>
		<category><![CDATA[platform]]></category>
		<category><![CDATA[syntax]]></category>
		<category><![CDATA[Windows]]></category>
		<guid isPermaLink="false">http://blog.andrei.rinea.ro/?p=391</guid>

					<description><![CDATA[I&#8217;ve always wanted to learn another language and platform and being a long-time .NET developer Java seemed the closest to my knowledge and one which would seem easy to learn based on what I already knew. I&#8217;ve put off this &#8230;<p class="read-more"><a href="https://blog.andrei.rinea.ro/2013/11/15/beginning-java-for-dot-net-developers/">Read more &#187;</a></p>]]></description>
										<content:encoded><![CDATA[<p>I&#8217;ve always wanted to learn another language and platform and being a long-time .NET developer Java seemed the closest to my knowledge and one which would seem easy to learn based on what I already knew.</p>
<p>I&#8217;ve put off this for various reason along the last 3-4 years, most of which laziness was chief. </p>
<p>Recently some colleagues moved from our project to another project that involves Java modules and since .NET is not a first-class citizen in my employer&#8217;s eyes I thought maybe it could serve me as a kind of an &#8216;insurance&#8217; &#8211; to learn Java.</p>
<p>I&#8217;ve obtained (..) some ebooks (<a href="http://amzn.com/0321356683">Effective Java</a> and <a href="http://amzn.com/0131872486">Thinking in Java</a>), downloaded JDK, a few IDEs (<a href="http://www.jetbrains.com/idea/">IntelliJ IDEA</a> and <a href="https://netbeans.org/">NetBeans</a>, no Eclipse for me, thanks) and started doing HelloWorld&#8217;s and stuff like that. I noticed JavaFX (which is quite <a href="http://stackoverflow.com/q/2016470/1796">similar</a> to WPF on which I currently work)</p>
<p>I&#8217;ve came across two nice comparisons of Java and .NET, written in a constructive manner (i.e. not &#8220;mine is better, na nanana&#8221;) :</p>
<ul>
<li><a href="http://www.harding.edu/fmccown/java_csharp_comparison.html">Java / C# comparision</a></li>
<li><a href="http://www.kynosarges.org/JavaCSharp.html">Java for C# Programmers</a> by Cristoph Nahr</li>
</ul>
<p>Using these two articles I compiled (yes, that&#8217;s the original meaning of the word :P) a PowerPoint slideshow.</p>
<p>Then I thought there might be other (.NET developer) colleagues that might be interested in my research and gave an internal presentation based on the slideshow and expanding each item by talk.</p>
<p>I thought I should share it with everyone so here it is (<a href="http://blog.andrei.rinea.ro/wp-content/uploads/2013/11/Beginning-Java-for-.NET-developers.pptx">download here</a>) :</p>
<p><iframe loading="lazy" src="http://www.slideshare.net/slideshow/embed_code/28276695" width="476" height="400" frameborder="0" marginwidth="0" marginheight="0" scrolling="no"></iframe></p>
<p>I&#8217;ve written about Java / C# differences <a href="http://blog.andrei.rinea.ro/2013/01/29/java-vs-csharp-differences-part-1-of/">before</a>, and I might continue that series in the near future, with practical examples and counter-examples.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.andrei.rinea.ro/2013/11/15/beginning-java-for-dot-net-developers/feed/</wfw:commentRss>
			<slash:comments>7</slash:comments>
		
		
			</item>
		<item>
		<title>Building Client (JavaScript) Custom Validation in ASP.NET MVC 4 using jQuery</title>
		<link>https://blog.andrei.rinea.ro/2013/06/28/building-client-javascript-custom-validation-in-asp-net-mvc-4-using-jquery/</link>
					<comments>https://blog.andrei.rinea.ro/2013/06/28/building-client-javascript-custom-validation-in-asp-net-mvc-4-using-jquery/#comments</comments>
		
		<dc:creator><![CDATA[Andrei Rinea]]></dc:creator>
		<pubDate>Fri, 28 Jun 2013 15:41:25 +0000</pubDate>
				<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[CodeProject]]></category>
		<category><![CDATA[Tips & tricks]]></category>
		<category><![CDATA[DataAnnotations]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[jquery]]></category>
		<category><![CDATA[mvc]]></category>
		<category><![CDATA[unobtrusive]]></category>
		<category><![CDATA[validation]]></category>
		<guid isPermaLink="false">http://blog.andrei.rinea.ro/?p=356</guid>

					<description><![CDATA[Introduction I was recently asked by some students of mine how exactly is client custom validation done in ASP.NET MVC (4). I did this once before unobtrusive validation and jQuery in ASP.NET MVC 2.0 but then I lost contact with &#8230;<p class="read-more"><a href="https://blog.andrei.rinea.ro/2013/06/28/building-client-javascript-custom-validation-in-asp-net-mvc-4-using-jquery/">Read more &#187;</a></p>]]></description>
										<content:encoded><![CDATA[<h3>Introduction</h3>
<p>I was recently asked by some students of mine how exactly is client custom validation done in ASP.NET MVC (4). I did this once before unobtrusive validation and jQuery in ASP.NET MVC 2.0 but then I lost contact with the implementation details.</p>
<p>In ASP.NET MVC 4 (this started in MVC 3) there is jQuery unobtrusive validation that works hand-in-hand with Data Annotations (a set of validation attributes that can decorate properties or even (view)model classes). I just remembered that you need to create a ValidationAttribute subclass and also implement IClientValidatable on it. Also you must decorate a property of the (View)Model with this attribute.</p>
<p>On the client side you need to write JavaScript code that provides a validation adapter and a validation function.</p>
<p>Let&#8217;s suppose we&#8217;d want to create an URL shortening service and on the &#8220;Add URL&#8221; page we&#8217;d have three fields :<br />
&#8211; Original URL (textbox)<br />
&#8211; Use custom slug (checkbox)<br />
&#8211; Custom slug (textbox)</p>
<p>The &#8220;Original URL&#8221; textbox would be mandatory and the input format should be of a fully-qualified URL (for example &#8220;http://blog.andrei.rinea.ro&#8221; :P)</p>
<p>The custom slug textbox would be mandatory ONLY if the &#8220;Use custom slug&#8221; checkbox would be checked. This is the tough part since validating this field requires knowledge of another field&#8217;s value (the checkbox in this case). And by tough I mean having to write actual code because there is no out-of-the-box validator for this (not on the server-side nor on the client-side).</p>
<p>This small tutorial will asume that you have knowledge of the ASP.NET MVC platform and C#. I will not go into detail on matters such as what is the MVC pattern, what is the controller, view etc.</p>
<p>&nbsp;</p>
<h3>Implementation &#8211; server side</h3>
<p>Let&#8217;s start by creating a new ASP.NET MVC 4 web project (select &#8220;Internet site&#8221; template).<br />
We&#8217;ll create a UrlController controller with an action called Add :</p>
<pre class="brush: csharp; title: ; notranslate">
using System.Web.Mvc;

namespace MVC4_jQuery_Unobtrusive_Custom_Validation.Controllers
{
    public class UrlController : Controller
    {
        &#x5B;HttpGet]
        public ActionResult Add()
        {
            return View();
        }

        &#x5B;HttpPost]
        public ActionResult Add(AddUrlViewModel userInput)
        {
            if (ModelState.IsValid)
            {
                // store the data
                // ...
                return RedirectToAction(&quot;Index&quot;, &quot;Home&quot;);
            }
            return View();
        }
    }
}
</pre>
<p><span id="more-356"></span><br />
I think the controller code is pretty straight-forward. So now let&#8217;s create the view and the viewmodel :</p>
<pre class="brush: xml; title: ; notranslate">
@model MVC4_jQuery_Unobtrusive_Custom_Validation.ViewModels.AddUrlViewModel


&lt;h2&gt;Add a new URL shortening&lt;/h2&gt;
@using (Html.BeginForm())
{
    &lt;table&gt;
        &lt;tr&gt;
            &lt;td&gt;Original URL : &lt;/td&gt;
            &lt;td&gt;
                @Html.TextBoxFor(m =&gt; m.OriginalUrl)
                @Html.ValidationMessageFor(m =&gt; m.OriginalUrl)
            &lt;/td&gt;
        &lt;/tr&gt;

        &lt;tr&gt;
            &lt;td&gt;@Html.LabelFor(m =&gt; m.UseCustomSlug, &quot;Use a custom slug&quot;)&lt;/td&gt;
            &lt;td&gt;@Html.CheckBoxFor(m =&gt; m.UseCustomSlug)&lt;/td&gt;
        &lt;/tr&gt;

        &lt;tr&gt;
            &lt;td&gt;Custom slug : &lt;/td&gt;
            &lt;td&gt;
                @Html.TextBoxFor(m =&gt; m.CustomSlug)
                @Html.ValidationMessageFor(m =&gt; m.CustomSlug)
            &lt;/td&gt;
        &lt;/tr&gt;
    &lt;/table&gt;
    
    &lt;input type=&quot;submit&quot; value=&quot;Save&quot;/&gt;   
}
</pre>
<pre class="brush: csharp; title: ; notranslate">
using System.ComponentModel.DataAnnotations;

namespace MVC4_jQuery_Unobtrusive_Custom_Validation.ViewModels
{
    public class AddUrlViewModel
    {
        &#x5B;Required]
        &#x5B;Url]
        public string OriginalUrl { get; set; }

        public bool UseCustomSlug { get; set; }
        
        public string CustomSlug { get; set; }
    }
}
</pre>
<p>We&#8217;ll need to create a validation attribute which will be used in decorating the &#8220;CustomSlug&#8221; property of the viewmodel. We&#8217;ll create another folder, called &#8216;Validation&#8217; and a new class that we&#8217;ll call &#8216;RequiredIfTrueAttribute&#8217; :</p>
<pre class="brush: csharp; title: ; notranslate">
using System;
using System.ComponentModel.DataAnnotations;

namespace MVC4_jQuery_Unobtrusive_Custom_Validation.Validation
{
    public class RequiredIfTrueAttribute : ValidationAttribute
    {
        public string BooleanPropertyName { get; set; }

        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            if (GetValue&lt;bool&gt;(validationContext.ObjectInstance, BooleanPropertyName))
            {
                return new RequiredAttribute().IsValid(value) ?
                    ValidationResult.Success :
                    new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
            }
            return ValidationResult.Success;
        }

        private static T GetValue&lt;T&gt;(object objectInstance, string propertyName)
        {
            if (objectInstance == null) throw new ArgumentNullException(&quot;objectInstance&quot;);
            if (string.IsNullOrWhiteSpace(propertyName)) throw new ArgumentNullException(&quot;propertyName&quot;);

            var propertyInfo = objectInstance.GetType().GetProperty(propertyName);
            return (T)propertyInfo.GetValue(objectInstance);
        }
    }
}
</pre>
<p>As we can see we made use of reflection in order to get the boolean property&#8217;s value. Since we can only specify the property as a string, we are stuck with using reflection. Don&#8217;t worry about the performance impact, it&#8217;s minimal. </p>
<p>In case that the propery is set to true we delegate the validation logic to a RequiredAttribute instance (I chose in this case aggregation over inheritance, which is the most flexible approach &#8211; inheriting would have meant deriving from the RequiredAttribute and overriding the IsValid method and then using the base.IsValid etc. etc.)</p>
<p>Let&#8217;s run the site and see how things go. Being lazy I haven&#8217;t included a link in the header of the page so we&#8217;ll just &#8216;hack&#8217; the address to point to http://localhost[:some-port]/Url/Add.</p>
<p><a href="http://blog.andrei.rinea.ro/wp-content/uploads/2013/06/1.png"><img loading="lazy" decoding="async" src="http://blog.andrei.rinea.ro/wp-content/uploads/2013/06/1.png" alt="" title="" width="902" height="573" class="aligncenter size-full wp-image-363" srcset="https://blog.andrei.rinea.ro/wp-content/uploads/2013/06/1.png 902w, https://blog.andrei.rinea.ro/wp-content/uploads/2013/06/1-300x190.png 300w" sizes="auto, (max-width: 902px) 100vw, 902px" /></a></p>
<p>If we try to submit the form as it is :</p>
<p><a href="http://blog.andrei.rinea.ro/wp-content/uploads/2013/06/2.png"><img loading="lazy" decoding="async" src="http://blog.andrei.rinea.ro/wp-content/uploads/2013/06/2.png" alt="" title="" width="902" height="573" class="aligncenter size-full wp-image-365" srcset="https://blog.andrei.rinea.ro/wp-content/uploads/2013/06/2.png 902w, https://blog.andrei.rinea.ro/wp-content/uploads/2013/06/2-300x190.png 300w" sizes="auto, (max-width: 902px) 100vw, 902px" /></a></p>
<p>As we can see the custom slug is not set as invalid since we did not opt in for a custom slug by checking the &#8220;Use a custom slug&#8221; checkbox. If we do check this checkbox and retry submitting the form we&#8217;ll get this :</p>
<p><a href="http://blog.andrei.rinea.ro/wp-content/uploads/2013/06/3.png"><img loading="lazy" decoding="async" src="http://blog.andrei.rinea.ro/wp-content/uploads/2013/06/3.png" alt="" title="" width="902" height="573" class="aligncenter size-full wp-image-366" srcset="https://blog.andrei.rinea.ro/wp-content/uploads/2013/06/3.png 902w, https://blog.andrei.rinea.ro/wp-content/uploads/2013/06/3-300x190.png 300w" sizes="auto, (max-width: 902px) 100vw, 902px" /></a></p>
<p>&nbsp;</p>
<h3>Implementation &#8211; client side</h3>
<p>Well this is fine, that is, the server-side validation. If you ran the sample you might have noticed that a full post is made for the validation errors to be displayed on the page. It works as we intended. Now it&#8217;s time to do the same for the client-side. In the case of the &#8216;Original URL&#8217; field things are handled out-of-the-box. For our new custom validation attribute we&#8217;ll need to write some javascript using jQuery.</p>
<p>First we&#8217;ll enable the client side validation by including the jQuery validation scripts at the view level (&#8220;at the top of the file, right beneath the @model directive) :</p>
<pre class="brush: xml; title: ; notranslate">
@section scripts
{
    @Scripts.Render(&quot;~/bundles/jqueryval&quot;)
}
</pre>
<p>Although the unobtrusive client-side validation is enabled at the web.config level : </p>
<pre class="brush: xml; title: ; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;configuration&gt;
  &lt;appSettings&gt;
    &lt;add key=&quot;webpages:Version&quot; value=&quot;2.0.0.0&quot; /&gt;
    &lt;add key=&quot;webpages:Enabled&quot; value=&quot;false&quot; /&gt;
    &lt;add key=&quot;PreserveLoginUrl&quot; value=&quot;true&quot; /&gt;

    &lt;!-- these two enables the validation --&gt;
    &lt;add key=&quot;ClientValidationEnabled&quot; value=&quot;true&quot; /&gt;
    &lt;add key=&quot;UnobtrusiveJavaScriptEnabled&quot; value=&quot;true&quot; /&gt;

  &lt;/appSettings&gt;
  &lt;!-- ... --&gt;
&lt;configuration&gt;
</pre>
<p>Well, running the app now, yields basically the same results but at least for the &#8216;Original URL&#8217; field the validation is done at the client-side first (never ever rely only on the client-side validation and not doing the same on the server! Javascript can be turned off or a malicious user could bypass it one way or the other). If we do check the checkbox and hit &#8216;Save&#8217; then only the server-side validation is being run. Let&#8217;s add some client-side validation for this too.</p>
<p>Next we&#8217;ll have to implement IClientValidatable on the RequiredIfTrueAttribute class. This means adding a &#8216;GetClientValidationRules&#8217; method to the class which will provide the metadata for the client-side script to run with :</p>
<pre class="brush: csharp; title: ; notranslate">
public IEnumerable&lt;ModelClientValidationRule&gt; GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
    var modelClientValidationRule = new ModelClientValidationRule
    {
        ValidationType = &quot;requirediftrue&quot;,
        ErrorMessage = FormatErrorMessage(metadata.DisplayName)
    };
    modelClientValidationRule.ValidationParameters.Add(&quot;boolprop&quot;, BooleanPropertyName);
    yield return modelClientValidationRule;
}
</pre>
<p>In case you haven&#8217;t stumbled upon the yield keyword before have a look on its <a href="http://msdn.microsoft.com/en-us/library/vstudio/9k7k7cf0.aspx">MSDN page</a>. Basically it creates an inner class that is an enumerator and returns an instance of it, which will enumerate all the values you specify, in this case one value, that instance of the ModelClientValidationRule.</p>
<p>We should take note of two things at this step :</p>
<ol>
<li>the validation type property allows only lowered case letters because of a limitation in the HTML 5 specifications, this will be rendered as an attribute on the HTML input element</li>
<li>We should provide the error message value as a result of the FormatErrorMessage method call and not provide the ErrorMessage property&#8217;s value because in this (current) way we give the validation rendering mechanism a chance to include the property name as part of the validation message. In our case we haven&#8217;t included &#8220;{0}&#8221; in the error message at the attribute decoration level but we could have done it.</li>
</ol>
<p>This is not all but let&#8217;s run the site now just to inspect the html page source code. Notice the data-val-requirediftrue and data-val-requirediftrue-boolprop on line 59 :</p>
<p><a href="http://blog.andrei.rinea.ro/wp-content/uploads/2013/06/4.png"><img loading="lazy" decoding="async" src="http://blog.andrei.rinea.ro/wp-content/uploads/2013/06/4.png" alt="" title="" width="661" height="655" class="aligncenter size-full wp-image-370" srcset="https://blog.andrei.rinea.ro/wp-content/uploads/2013/06/4.png 661w, https://blog.andrei.rinea.ro/wp-content/uploads/2013/06/4-150x150.png 150w, https://blog.andrei.rinea.ro/wp-content/uploads/2013/06/4-300x297.png 300w" sizes="auto, (max-width: 661px) 100vw, 661px" /></a></p>
<p>These two new attributes hold the error message for this rule and the validation parameter. Now we will implement javascript code to make use of these attributes. We will add a new javascript file in the Scripts folder, file called &#8216;RequiredIfTrueValidation.js&#8217;. We will also inclued this file in the view :</p>
<pre class="brush: xml; title: ; notranslate">
@section scripts
{
    @Scripts.Render(&quot;~/bundles/jqueryval&quot;)
    @Scripts.Render(&quot;~/Scripts/RequiredIfTrueValidation.js&quot;)
}
</pre>
<p>&#8230; and the javascript file contents :</p>
<pre class="brush: jscript; title: ; notranslate">
jQuery.validator.addMethod('requirediftrue', function (value, element, params) {
    var checkboxId = $(element).attr('data-val-requirediftrue-boolprop');
    var checkboxValue = $('#' + checkboxId).first().is(&quot;:checked&quot;);
    return !checkboxValue || value;
}, '');

jQuery.validator.unobtrusive.adapters.add('requirediftrue', {}, function (options) {
    options.rules&#x5B;'requirediftrue'] = true;
    options.messages&#x5B;'requirediftrue'] = options.message;
});
</pre>
<p>&nbsp;</p>
<h3>Javascript analysis</h3>
<p>Let&#8217;s have a deeper look on the javascript file.  In the first chunk of code there is the validation function and in the second chunk we wire up an &#8216;adaptor&#8217; for the jQuery unobtrusive validation engine. </p>
<p>Line 8 adds the rule and sets its parameter to the &#8216;true&#8217; value. This true value is useless in our case (it will be passed as the &#8216;params&#8217; parameter value on line 1 later) but the line is required in order for the rule to be added to the rules collection.</p>
<p>Line 9 sets the error message for this rule (in case it&#8217;s going to be broken). </p>
<p>Line 2 gets the checkbox id from the validated textbox. Notice the attribute name that I was telling you earlier. This validating function (defined on line 1, inline) will be called by the validation engine with the validated textbox value as the &#8216;value&#8217; parameter value, the textbox instance itself as the &#8216;element&#8217; parameter value and the value from line 8 as the &#8216;params&#8217; parameter value. Now, after we get the checkbox id, on line 2, we proceed on line 3 to get the checkbox element and read its checked state. The &#8220;first()&#8221; function call is necessary because <a href="http://stackoverflow.com/a/307509/1796">jQuery will always return an array regardless</a> if you use a (unique) id selector &#8211; which in fact can only result in one or zero element(s).</p>
<p>Finally on line 4 we return the validation result (true meaning &#8216;is valid&#8217; and false otherwise). We decide this value either by the fact that the checkbox is not checked (&#8220;!checkboxValue&#8221;) or, the checkbox is checked and the &#8216;value&#8217; &#8211; that is the text in the textbox &#8211; is not empty (empty string is evaluated as &#8216;false&#8217; and non-empty, non-null string is evaluated as &#8216;true&#8217; in javascript).</p>
<p>Let&#8217;s run the site and find out things run as they should. (no screenshot necessary for this, I can&#8217;t show how the server is NOT called 😉 &#8211; maybe a video but for now I feel lazy). You can place a breakpoint at the action level and see how the server is not called.</p>
<p>Finally let&#8217;s add a finishing touch, by toggling the display of the &#8216;custom slug&#8217; field through the checkbox :</p>
<pre class="brush: xml; title: ; notranslate">
@model MVC4_jQuery_Unobtrusive_Custom_Validation.ViewModels.AddUrlViewModel

@section scripts
{
    @Scripts.Render(&quot;~/bundles/jqueryval&quot;)
    @Scripts.Render(&quot;~/Scripts/RequiredIfTrueValidation.js&quot;)

    &lt;script type=&quot;text/javascript&quot;&gt;
        $('#customSlugRow').toggle($($('#@Html.IdFor(m =&gt; m.UseCustomSlug)')).is(':checked'));
        $('#@Html.IdFor(m =&gt; m.UseCustomSlug)').click(function () {
            $('#customSlugRow').toggle(this.checked);
        });
    &lt;/script&gt;
}

&lt;h2&gt;Add a new URL shortening&lt;/h2&gt;
@using (Html.BeginForm())
{
    &lt;table&gt;
        &lt;tr&gt;
            &lt;td&gt;Original URL : &lt;/td&gt;
            &lt;td&gt;
                @Html.TextBoxFor(m =&gt; m.OriginalUrl)
                @Html.ValidationMessageFor(m =&gt; m.OriginalUrl)
            &lt;/td&gt;
        &lt;/tr&gt;

        &lt;tr&gt;
            &lt;td&gt;@Html.LabelFor(m =&gt; m.UseCustomSlug, &quot;Use a custom slug&quot;)&lt;/td&gt;
            &lt;td&gt;@Html.CheckBoxFor(m =&gt; m.UseCustomSlug)&lt;/td&gt;
        &lt;/tr&gt;

        &lt;tr id=&quot;customSlugRow&quot;&gt;
            &lt;td&gt;Custom slug : &lt;/td&gt;
            &lt;td&gt;
                @Html.TextBoxFor(m =&gt; m.CustomSlug)
                @Html.ValidationMessageFor(m =&gt; m.CustomSlug)
            &lt;/td&gt;
        &lt;/tr&gt;
    &lt;/table&gt;
    
    &lt;input type=&quot;submit&quot; value=&quot;Save&quot; /&gt;   
}
</pre>
<p>Let&#8217;s start with line 10. This tells jQuery to get the checkbox and attach an event handler for the click event. This handler (line 11) will toggle the visibility of the &#8216;customSlugRow&#8217; table row (notice I&#8217;ve added an id to the tr element on line 33) based on the checked state of the checkbox. In jQuery the &#8216;this&#8217; reference will point to the element that has the event handler, in this case the checkbox.</p>
<p>Finally on line 9 we set the initial visibility of the row based on the value of the checkbox. Don&#8217;t assume that this will always be &#8216;unchecked&#8217;. If the viewmodel comes with the UseCustomSlug set to true (initially not) then the &#8216;CustomSlug&#8217; should not be hidden.</p>
<p>&nbsp;</p>
<h3>Summary</h3>
<p>In this tutorial we&#8217;ve seen how to create custom javascript/jQuery unobtrusive client-side validation. We&#8217;ve created a validation attribute class inheriting from (System.ComponentModel.DataAnnotations.)ValidationAttribute and we&#8217;ve implemented the IClientValidatable interface in order to send validation metadata to the view. We&#8217;ve, then, created a validator adapter (a javascript function that sets up the rule validation function) and the rule validation function.</p>
<p>Have fun jQuerying but don&#8217;t forget to check out the <a href="http://stackoverflow.com/questions/tagged/jquery">Stackoverflow jQuery-tagged question</a> and the <a href="http://learn.jquery.com/">jQuery Learning Center</a> because you&#8217;ll surely end up needing that information! m.CustomSlug)</p>
<p><strong>You can download the project <a href='http://blog.andrei.rinea.ro/wp-content/uploads/2013/06/MVC4_jQuery_Unobtrusive_Custom_Validation.rar'>code</a>.</strong></p>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.andrei.rinea.ro/2013/06/28/building-client-javascript-custom-validation-in-asp-net-mvc-4-using-jquery/feed/</wfw:commentRss>
			<slash:comments>3</slash:comments>
		
		
			</item>
		<item>
		<title>Bing it on, Reactive Extensions! &#8211; story, code and slides</title>
		<link>https://blog.andrei.rinea.ro/2013/06/01/bing-it-on-reactive-extensions-story-code-and-slides/</link>
					<comments>https://blog.andrei.rinea.ro/2013/06/01/bing-it-on-reactive-extensions-story-code-and-slides/#comments</comments>
		
		<dc:creator><![CDATA[Andrei Rinea]]></dc:creator>
		<pubDate>Sat, 01 Jun 2013 19:55:54 +0000</pubDate>
				<category><![CDATA[CodeProject]]></category>
		<category><![CDATA[Presentations]]></category>
		<category><![CDATA[WPF]]></category>
		<category><![CDATA[bing]]></category>
		<category><![CDATA[Reactive Extensions]]></category>
		<category><![CDATA[ReSharper]]></category>
		<category><![CDATA[sample]]></category>
		<category><![CDATA[wpf]]></category>
		<category><![CDATA[XAML]]></category>
		<guid isPermaLink="false">http://blog.andrei.rinea.ro/?p=323</guid>

					<description><![CDATA[I held a presentation at UBISOFT Buchares headquarters for the RONUA local programmers user group recently as I&#8217;ve announced earlier. Here&#8217;s the contents, step-by-step, final code and slides. &#8212;&#8212;&#8212;&#8212;- [scroll way down for the downloads] I was recently tasked with &#8230;<p class="read-more"><a href="https://blog.andrei.rinea.ro/2013/06/01/bing-it-on-reactive-extensions-story-code-and-slides/">Read more &#187;</a></p>]]></description>
										<content:encoded><![CDATA[<p>I held a presentation at UBISOFT Buchares headquarters for the RONUA local programmers user group recently as I&#8217;ve announced <a href="http://blog.andrei.rinea.ro/2013/05/10/bing-it-on-reactive-extensions/">earlier</a>.<br />
Here&#8217;s the contents, step-by-step, final code and slides.</p>
<p>&#8212;&#8212;&#8212;&#8212;- [scroll way down for the downloads]</p>
<p><img loading="lazy" decoding="async" src="http://blog.andrei.rinea.ro/wp-content/uploads/2013/06/BingItOn.png" alt="" title="BingItOn" width="450" height="379" class="aligncenter size-full wp-image-347" srcset="https://blog.andrei.rinea.ro/wp-content/uploads/2013/06/BingItOn.png 450w, https://blog.andrei.rinea.ro/wp-content/uploads/2013/06/BingItOn-300x252.png 300w" sizes="auto, (max-width: 450px) 100vw, 450px" /></p>
<p>I was recently tasked with rewriting an app component by leveraging <a href="http://msdn.microsoft.com/en-us/data/gg577609.aspx">Reactive Extensions</a>. I knew little about Rx (the short form of Reactive Extensions) and all I remembered was that it has two interfaces <a href="http://msdn.microsoft.com/en-us/library/dd990377.aspx">IObservable</a> and <a href="http://msdn.microsoft.com/en-us/library/dd783449.aspx">IObserver</a> and it seemed dull at that time.</p>
<p>Basically the component enables search without needing to hit ENTER or a &#8220;Go!&#8221; button, although provides for these. After the user finishes typing an async request goes to the data store and searches for the phrase entered and fetches the results. In the original implementation the component used a lot of timers, event handlers, private fields all making up a nice spaghetti bowl of code.</p>
<p>Let&#8217;s do this step by step and see how our little (demo) app develops. Fire up Visual Studio 2012 and start a new WPF project (.NET 4.5 preferrably). The very next thing we&#8217;ll install Rx. Right click on the project in the Solution Explorer and select &#8220;Manage NuGet Packages&#8221; (you can also use the Package Manager Console if you like it better). Search online for &#8220;Reactive Extensions&#8221;. </p>
<p>In the result lists (this requires a functional internet connection) select &#8216;<a href="https://www.nuget.org/packages/Rx-WPF">Reactive Extensions &#8211; WPF Helpers</a>&#8216; (the nice thing about NuGet packages is that it automatically resolves and installs all the dependencies). Accept the license(s) (you know what&#8217;s the most common lie told these days? &#8220;I have read and accepted the terms of the license&#8221; :P).</p>
<p>In our demo we will use Bing as the data store which we&#8217;ll target through our searches (sorry, Google was too difficult to setup, offered less search requests per month and no C# demo code. Thanks Google, thanks again.). In order to do this you will need a Microsoft Account (I guess we all have one these days). Go to <a href="http://www.bing.com/developers/">http://www.bing.com/developers/</a> and then select &#8220;Search API&#8221; -> Start now (this will lead you to <a href="https://datamarket.azure.com/dataset/5BA839F1-12CE-4CCE-BF57-A49D98D29A44">https://datamarket.azure.com/dataset/5BA839F1-12CE-4CCE-BF57-A49D98D29A44</a> ). There are paid subscriptions and a free subscription. Hit signup and go through the process (leave a comment if you are unable to go through this process).</p>
<p>In the end you will need to obtain the (Primary) Account Key and the Customer ID. These are available under &#8220;My Account&#8221; -> Account Information ( https://datamarket.azure.com/account ). We&#8217;ll use these later so save them. Also, don&#8217;t share them with other people because these are your credentials. Also visit &#8220;My Data&#8221; ( <a href="https://datamarket.azure.com/account/datasets">https://datamarket.azure.com/account/datasets</a> ) and click on &#8220;Bing Search API&#8221;&#8216;s &#8220;Use&#8221; link (far right, <a href="https://datamarket.azure.com/dataset/explore/bing/search">https://datamarket.azure.com/dataset/explore/bing/search</a> ). Capture the &#8220;URL for current expressed query&#8221; : &#8220;<a href="https://api.datamarket.azure.com/Bing/Search/v1/Web">https://api.datamarket.azure.com/Bing/Search/v1/Web</a>&#8220;. We&#8217;ll also need these later.</p>
<p><span id="more-323"></span></p>
<p>Finally just below the subscription list there is a &#8220;.NET C# Class library&#8221; link (<a href="https://datamarket.azure.com/dataset/explore/getproxy/5ba839f1-12ce-4cce-bf57-a49d98d29a44">https://datamarket.azure.com/dataset/explore/getproxy/5ba839f1-12ce-4cce-bf57-a49d98d29a44</a>) which will get you a &#8220;BingSearchContainer.cs&#8221; file. Download this file into the project&#8217;s folder and include it in your project. At this point the project will not compile as it is missing a reference to System.Data.Services.Client. Add this reference and compile the project.</p>
<p>Now let&#8217;s build the UI. I must say that for the sake of the demo we will not implement this little app by abiding to all good practices and patterns, such as MVVM. If you do end up implementing this for production purposes please take care to abide to all good practices. Getting back to our development, let&#8217;s open MainWindow.xaml and prepare a simple layout with a thin row above, on which we&#8217;ll place a textbox, two buttons and a &#8220;busy indicator&#8221;. On the second row (the most of the app space, we&#8217;ll place a listbox with results :</p>
<pre class="brush: xml; title: ; notranslate">

&lt;Window x:Class=&quot;BingItOn.MainWindow&quot;
        xmlns=&quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;
        xmlns:x=&quot;http://schemas.microsoft.com/winfx/2006/xaml&quot;
        xmlns:d=&quot;http://schemas.microsoft.com/expression/blend/2008&quot;
        xmlns:mc=&quot;http://schemas.openxmlformats.org/markup-compatibility/2006&quot; 
        xmlns:bing=&quot;clr-namespace:Bing&quot;
        mc:Ignorable=&quot;d&quot;
        Title=&quot;Bing it on!&quot; 
        Width=&quot;800&quot;
        Height=&quot;600&quot;
        FocusManager.FocusedElement=&quot;{Binding ElementName=TxtSearch}&quot;&gt;
    &lt;Grid&gt;
        &lt;Grid.RowDefinitions&gt;
            &lt;RowDefinition Height=&quot;Auto&quot;/&gt;
            &lt;RowDefinition /&gt;
        &lt;/Grid.RowDefinitions&gt;

        &lt;Grid.ColumnDefinitions&gt;
            &lt;ColumnDefinition /&gt;
            &lt;ColumnDefinition Width=&quot;Auto&quot;/&gt;
        &lt;/Grid.ColumnDefinitions&gt;

        &lt;TextBox x:Name=&quot;TxtSearch&quot; /&gt;
        &lt;StackPanel Orientation=&quot;Horizontal&quot; Grid.Column=&quot;1&quot;&gt;
            &lt;Button x:Name=&quot;BtnForceSearch&quot; IsDefault=&quot;True&quot;&gt;Go!&lt;/Button&gt;
            &lt;Button x:Name=&quot;BtnStopSearch&quot; IsCancel=&quot;True&quot;&gt;Stop&lt;/Button&gt;
            &lt;Grid   x:Name=&quot;GrdBusy&quot; Background=&quot;Red&quot; Visibility=&quot;Hidden&quot; 
                    Width=&quot;20&quot; /&gt;
        &lt;/StackPanel&gt;

        &lt;ListBox x:Name=&quot;LstResults&quot; Grid.Row=&quot;1&quot; Grid.ColumnSpan=&quot;2&quot;&gt;
            &lt;ListBox.ItemTemplate&gt;
                &lt;DataTemplate&gt;
                    &lt;StackPanel 
                        d:DataContext=&quot;{d:DesignInstance {x:Type bing:WebResult}}&quot;&gt;
                        &lt;TextBlock Text=&quot;{Binding Title}&quot;&gt;&lt;/TextBlock&gt;
                        &lt;TextBlock Text=&quot;{Binding Url}&quot;&gt;&lt;/TextBlock&gt;
                        &lt;TextBlock&gt;
                            &lt;Hyperlink NavigateUri=&quot;{Binding Url}&quot;
                                       RequestNavigate=&quot;OnUrlNavigate&quot;&gt;
                                &lt;TextBlock Text=&quot;{Binding DisplayUrl}&quot;/&gt;
                            &lt;/Hyperlink&gt;
                        &lt;/TextBlock&gt;
                    &lt;/StackPanel&gt;
                &lt;/DataTemplate&gt;
            &lt;/ListBox.ItemTemplate&gt;
        &lt;/ListBox&gt;
    &lt;/Grid&gt;
&lt;/Window&gt;

</pre>
<p>The Grid &#8220;GrdBusy&#8221; is set to <a href="http://stackoverflow.com/q/886742/1796">Hidden</a> and not &#8220;Collapsed&#8221; in order to avoid having the buttons shift left-right. It also requires a width in order to be drawn on the screen.<br />
The weird d:DataContext is an attached property that lets the IDE (ReSharper uses this) know what kind of objects will be fed into the &#8220;LstResults&#8221; listbox.</p>
<p>Now let&#8217;s go in the code behind (this sounds anti-pattern but remember it&#8217;s just a quick demo &#8211; otherwise we would have had a ViewModel and so on) and declare two private constants with the account key and customer id (we&#8217;ll need these to do the actual search).</p>
<p>Let&#8217;s also build a small method that takes in a string and returns an IEnumerable<WebResult> (WebResult is a class in the Bing namespace), let&#8217;s call it SearchBing. At this point the MainWindow class should look like :</p>
<pre class="brush: csharp; title: ; notranslate">

using System;
using System.Collections.Generic;
using System.Linq;

using Bing;

namespace BingItOn
{
    public partial class MainWindow
    {
        private const string AccountKey = @&quot;&lt;YOUR_ACTUAL_ACCOUNT_KEY&gt;&quot;;
        private const string CustomerId = @&quot;&lt;YOUR_ACTUAL_CUSTOMER_ID&gt;&quot;;

        public MainWindow()
        {
            InitializeComponent();
        }

        private IEnumerable&lt;WebResult&gt; SearchBing(string searchPhrase)
        {
            var uri = new Uri(@&quot;https://api.datamarket.azure.com/Bing/Search/v1/Web&quot;);
            var container = new BingSearchContainer(uri);
            container.Credentials = new NetworkCredential(CustomerId, AccountKey);
            var query = container.Web(searchPhrase, null, null, null, null, null, null, null);
            return query.Take(10).ToArray();
        }

        private void OnUrlNavigate(object sender, RequestNavigateEventArgs e)
        {
            Process.Start(e.Uri.ToString());
        }
    }
}

</pre>
<p><strong>Step 1 &#8211; let&#8217;s have the app search async and display results as we type.</strong></p>
<p>Let&#8217;s create a &#8220;SetupSubscriptions&#8221; void instance method that we&#8217;ll call from the constructor after InitializeComponent(); In this method we&#8217;ll create a new &#8216;Observable&#8217;. That is an instance of a class that implements IObservable<T>. This thin interface has one method : Subscribe. This enables us to subscribe with a method which will be called back (callback) whenever the sequence, because a sequence of data is what an IObservable models, produces a new item. In case of an event observable the item will be an encapsulation of the event sender and the event arguments (&#8216;object sender, EventArgs e&#8217; rings any bells?). We&#8217;ll select the new text and then we&#8217;ll subscribe to this observable like so :</p>
<pre class="brush: csharp; title: ; notranslate">

public MainWindow()
{
    InitializeComponent();
    SetupSubscriptions();
}

private void SetupSubscriptions()
{
    var textChangedObservable = Observable.FromEventPattern(TxtSearch, &quot;TextChanged&quot;);
    var textObservable = from evt in textChangedObservable select ((TextBox)evt.Sender).Text;
    textObservable.Subscribe(OnTextChanged);
}

private void OnTextChanged(string text)
{
    var data = SearchBing(text);
    LstResults.Items.Clear();
    foreach (var result in data)
    {
        LstResults.Items.Add(result);
    }
}

</pre>
<p>Run the app (if you have aggresive firewall software you&#8217;ll be prompted to accept this little app&#8217;s request to connect externally) and notice how things happen synchronously, sluggishly. Type a character, wait for the bing results, type another character and so on. This is not so nice. Let&#8217;s make it async. <img src="https://s.w.org/images/core/emoji/16.0.1/72x72/1f600.png" alt="😀" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<p>We do this by creating an observable of async web results and we&#8217;ll combine the text observable (with a &#8216;inner join&#8217;) with this new observable. We&#8217;ll also change the OnTextChanged method to OnResultsArrived and its contents. Sounds complicated but it&#8217;s not really. Let&#8217;s see how :</p>
<pre class="brush: csharp; title: ; notranslate">

private void SetupSubscriptions()
{
    var textChangedObservable = Observable.FromEventPattern(TxtSearch, &quot;TextChanged&quot;);
    var textObservable = from evt in textChangedObservable select ((TextBox)evt.Sender).Text;
    var searchBingFunc = new Func&lt;string, IEnumerable&lt;WebResult&gt;&gt;(SearchBing);
    var searchBingObservable = Observable.FromAsyncPattern&lt;string, IEnumerable&lt;WebResult&gt;&gt;(
        searchBingFunc.BeginInvoke, searchBingFunc.EndInvoke);
    var combinedObservable = from text in textObservable
                             from result in searchBingObservable(text)
                             select result;
    combinedObservable.Subscribe(OnResultsArrived);
}

private void OnResultsArrived(IEnumerable&lt;WebResult&gt; results)
{
    LstResults.Items.Clear();
    foreach (var result in results)
    {
        LstResults.Items.Add(result);
    }
}

</pre>
<p>Upon the first run we get hit with an InvalidOperationException at the first line of code of the OnResultsArrived because we&#8217;re not on the UI thread but on a worker thread. Resist the urge to Dispatcher.Invoke (or BeginInvoke) into this. We&#8217;ll change the Subscription code from combinedObservable.Subscribe(OnResultsArrived) to combinedObservable<strong>.<a href="http://msdn.microsoft.com/en-us/library/hh229634(v=vs.103).aspx">ObserveOn</a>(this)</strong>.Subscribe(OnResultsArrived).</p>
<p>Run the app again. Now things work a bit better but still sluggish (the results presentation is the culprit) and more than this, a search request is made for each keystroke (or at least any command that changes the text). We can easily prevent this with a little&#8230; Reactive Extension! Called <a href="http://msdn.microsoft.com/en-us/library/hh229298(v=vs.103).aspx">Throttle</a>.</p>
<p><strong>step 2 &#8211; let&#8217;s start the search only if the user stopped typing</strong></p>
<p>We&#8217;ll apply Throttle on the textObservable in the combinedObservable definition in SetupSubscriptions like so :</p>
<pre class="brush: csharp; title: ; notranslate">

var combinedObservable = from text in textObservable.Throttle(TimeSpan.FromSeconds(0.5))
                         from result in searchBingObservable(text)
                         select result;

</pre>
<p>Running the app again shows much better performance and less requests to the server(s). What Throttle essentially does is waiting for the sequence to calm down and if after 0.5 seconds no more changes have been made, it stops filtering and allows the item to pass out of the sequence. Neat, ha?</p>
<p>We have one more nice extension that we can chain after Throttle and that&#8217;s <a href="http://msdn.microsoft.com/en-us/library/hh229494(v=vs.103).aspx">DistinctUntilChanged</a>. This allows to pass only distinct results. So if we type &#8220;test&#8221; in the textbox and then quickly (in less than those 500 milliseconds) type another &#8220;t&#8221; and then quicly delete it there won&#8217;t be requests made for &#8220;testt&#8221; and then another one for &#8220;test&#8221; again.</p>
<pre class="brush: csharp; title: ; notranslate">

var combinedObservable = from text in textObservable
                                          .Throttle(TimeSpan.FromSeconds(0.5))
                                          .DistinctUntilChanged()
                         from result in searchBingObservable(text)
                         select result;

</pre>
<p><strong>step 3 &#8211; let&#8217;s drop an ongoing search if in the meantime we need to start another one</strong></p>
<p>Now we&#8217;re finally seeing the beauty of reactive extensions! By simply combining observable (either chaining them or joining them) and/or applying filters and modifiers we&#8217;re obtaining a lot of functionality with little code.<br />
It&#8217;s more elegant, easier to understand (after the learning curve albeit), easier to test and less prone to bugs since the functionality is outsourced to the Rx libs which are carefully written by the guys at Microsoft and thoroughly tested.</p>
<p>The searchBingObservable(text) in the combined observable definition is a single-value observable that &#8216;spits&#8217; out a single result at most once in its life, that is an &#8220;instance&#8221; of IEnumerable<WebResult>. (I used the quotes because a closer to the truth expression would have been an &#8220;instance of a class that implements IEnumerable<WebResult>, array of WebResult to be more precise&#8221;).</p>
<p>The .<a href="http://msdn.microsoft.com/en-us/library/hh229530(v=vs.103).aspx">TakeUntil</a>(anotherSequence) extension method found in Rx filters a sequence in a way that it lets pass everything until its parameter (&#8216;anotherSequence&#8217;) produces an item. This way we&#8217;d be ignoring the results when they&#8217;d came (effectively cancelling the request on the server(s) is not possible in a HTTP(S) system). We&#8217;ll just add TakeUntil in the mix like so :</p>
<pre class="brush: csharp; title: ; notranslate">
private void SetupSubscriptions()
{
    var textChangedObservable = Observable.FromEventPattern(TxtSearch, &quot;TextChanged&quot;);
    var textObservable = from evt in textChangedObservable select ((TextBox)evt.Sender).Text;
    var searchBingFunc = new Func&lt;string, IEnumerable&lt;WebResult&gt;&gt;(SearchBing);
    var searchBingObservable = Observable.FromAsyncPattern&lt;string, IEnumerable&lt;WebResult&gt;&gt;(
        searchBingFunc.BeginInvoke, searchBingFunc.EndInvoke);
    var tamedTextObservable = textObservable.Throttle(TimeSpan.FromSeconds(0.5)).DistinctUntilChanged();
    var combinedObservable = from text in tamedTextObservable
                                from result in searchBingObservable(text).TakeUntil(tamedTextObservable)
                                select result;
    combinedObservable.ObserveOn(this).Subscribe(OnResultsArrived);
}
</pre>
<p>Everything&#8217;s fine until someone trips over the wireless cable (kidding, the net goes down whatsoever). In that case the exception will take down the whole app although it shouldn&#8217;t.</p>
<p><strong>step 4 &#8211; Exception handling</strong></p>
<p>When a sequence (observable) encounters an error it calls <a href="http://msdn.microsoft.com/en-us/library/dd781657.aspx">OnError</a> on its subscriber(s) and then it terminates, i.e. it won&#8217;t produce anything anymore. It&#8217;s faulted. Therefore in such a case we&#8217;ll choose to present the error and redo the subscriptions :</p>
<pre class="brush: csharp; title: ; notranslate">
   //... 
   combinedObservable.ObserveOn(this).Subscribe(OnResultsArrived, OnError);
}

private void OnError(Exception obj)
{
    MessageBox.Show(&quot;An error has occured.&quot; + Environment.NewLine + Environment.NewLine + obj);
    SetupSubscriptions();
}
</pre>
<p><strong>step 5- let&#8217;s implement the busy indicator</strong></p>
<p>We&#8217;ll just define a helper method that toggles the busy indicator state and call it from SearchBing, OnResultsArrived and OnError methods (at their start) accordingly (true for SearchBing and false for the others) :</p>
<pre class="brush: csharp; title: ; notranslate">
private void SetBusyIndicatorState(bool state)
{
    Dispatcher.BeginInvoke(new Action(() =&gt; { GrdBusy.Visibility = state ? Visibility.Visible : Visibility.Hidden; }));
}
</pre>
<p>Let&#8217;s run. It works, not a state-of-the-art like an animated spinner or something but that would be beside the point of this demo anyway.</p>
<p><strong>step 6 &#8211; let&#8217;s implement the Go! button (the force search button)</strong></p>
<p>We&#8217;ll start by observing the button click event and then merging this observable with the tamed text input. We&#8217;ll also increase significantly the throttle timespan in order to &#8230; observe (pun intended) the effect of hitting ENTER (or mouse-clicking the button) : </p>
<pre class="brush: csharp; title: ; notranslate">
//...
var tamedTextObservable = textObservable.Throttle(TimeSpan.FromSeconds(3.5)).DistinctUntilChanged();
var forceSearchButtonObservable = from text in Observable.FromEventPattern(BtnForceSearch, &quot;Click&quot;) select TxtSearch.Text;
var combinedObservable = from text in tamedTextObservable.Merge(forceSearchButtonObservable)
                            from result in searchBingObservable(text).TakeUntil(tamedTextObservable)
                            select result;
//...
</pre>
<p>Running the application, typing &#8216;test&#8217; (for example) and quickly hitting ENTER we&#8217;ll see that the search commences instantly (or almost). However we&#8217;ll also observe that after we get the results another query is issued for the same text and, of course, has the same results.</p>
<p>The essence of the issue is that the expression &#8220;tamedTextObservable.Merge(forceSearchButtonObservable)&#8221; will produce an item (search text) at the ENTER keypress and another one later from the tamed observable. The quick fix is to add an &#8220;DistinctUntilChanged&#8221; at its end. This fixes it until&#8230;</p>
<p>The boss comes requesting that hitting ENTER even after the results have been loaded for the current expression will redo the search, just like a Refresh (F5) would do in a browser. Now we&#8217;re stuck we need to remove the &#8220;DistinctUntilChanged&#8221; but we&#8217;d then be back to the double search issue that we had later. It may seem we can&#8217;t outsmart this.</p>
<p>But after a few hours of headbanging it hit me : we&#8217;ll switch from string (the type produced by the sequences and accepted by the search method) to a custom type that we&#8217;ll call SearchRequest :</p>
<pre class="brush: csharp; title: ; notranslate">
public class SearchRequest
{
    public string Text { get; set; }
    public bool Force { get; set; }
}
</pre>
<p>Instead of just producing the TxtSearch&#8217;s .Text value we&#8217;ll be producing instances of this SearchRequest class filling the TextBox&#8217;s Text property value in the Text property and setting Force to true only if produced by the force button click. We&#8217;ll also use this opportunity to treat the case when the textbox becomes empty.</p>
<pre class="brush: csharp; title: ; notranslate">

private void SetupSubscriptions()
{
    var textChangedObservable = Observable.FromEventPattern(TxtSearch, &quot;TextChanged&quot;);
    var textObservable = from evt in textChangedObservable select new SearchRequest { Text = TxtSearch.Text };
    var searchBingFunc = new Func&lt;SearchRequest, IEnumerable&lt;WebResult&gt;&gt;(SearchBing);
    var searchBingObservable = Observable.FromAsyncPattern&lt;SearchRequest, IEnumerable&lt;WebResult&gt;&gt;(
        searchBingFunc.BeginInvoke, searchBingFunc.EndInvoke);
    var tamedTextObservable = textObservable.Throttle(TimeSpan.FromSeconds(3.5)).DistinctUntilChanged();
    var forceSearchButtonObservable = from text in Observable.FromEventPattern(BtnForceSearch, &quot;Click&quot;)
                                        select new SearchRequest { Text = TxtSearch.Text, Force = true };
    var combinedObservable = from request in tamedTextObservable.Merge(forceSearchButtonObservable).DistinctUntilChanged()
                                from result in searchBingObservable(request).TakeUntil(tamedTextObservable)
                                select result;
    combinedObservable.ObserveOn(this).Subscribe(OnResultsArrived, OnError);
}

//...

private IEnumerable&lt;WebResult&gt; SearchBing(SearchRequest searchRequest)
{
    if (string.IsNullOrWhiteSpace(searchRequest.Text)) return Enumerable.Empty&lt;WebResult&gt;();
    SetBusyIndicatorState(true);
    var container = new BingSearchContainer(new Uri(Url))
    {
        Credentials = new NetworkCredential(CustomerId, AccountKey)
    };
    var query = container.Web(searchRequest.Text, null, null, null, null, null, null, null);
    return query.Take(10).ToArray();
}

</pre>
<p>We&#8217;ll run the app and see that not much has changed. That&#8217;s because now the DistinctUntilChanged at the end of tamedTextObservable definition is using the Equals of the SearchRequest class and the default implementation of a class is to compare the reference values and not the semantic value. We&#8217;ll also override GetHashCode since this is a <a href="http://blogs.msdn.com/b/ericlippert/archive/2011/02/28/guidelines-and-rules-for-gethashcode.aspx">good practice</a> that can defend us from weird bugs. Let&#8217;s implement this cleverly placing priority for the case when the request is forced :</p>
<pre class="brush: csharp; title: ; notranslate">
internal class SearchRequest
{
    public string Text { get; set; }
    public bool Force { get; set; }

    public override bool Equals(object obj)
    {
        var older = this;
        var newer = (SearchRequest)obj;
        if (newer == null || newer.Text != older.Text) return false;
        return !newer.Force;
    }

    public override int GetHashCode()
    {
        return (Text ?? string.Empty).GetHashCode() ^ Force.GetHashCode();
    }
}
</pre>
<p>This reminds of a <a href="http://stackoverflow.com/a/2481017/1796">strange case</a> when &#8216;this&#8217; can be null in an instance context but I won&#8217;t treat it in the Equals overriding. Run the app. Problem fixed! This feels good.</p>
<p><strong>step 7 &#8211; let&#8217;s implement the stop button</strong></p>
<p>This will need to do several things : clear the textbox, clear the results and stop any ongoing search if any. Although there probably are many ways to implement this at this stage of development I will choose, what I think to be, a simple one : I will handle the click event and clear the textbox and, separately, I will observe the click event and use it (indirectly) in the TakeUntil of the async observable to stop an ongoing search. I will also use this opportunity to set the throttle time at a more decent value, such as 0.7 seconds.</p>
<pre class="brush: xml; title: ; notranslate">
&lt;Button x:Name=&quot;BtnStopSearch&quot; IsCancel=&quot;True&quot; Click=&quot;OnStopRequest&quot;&gt;Clear&lt;/Button&gt;
</pre>
<pre class="brush: csharp; title: ; notranslate">
private void SetupSubscriptions()
{
    var textChangedObservable = Observable.FromEventPattern(TxtSearch, &quot;TextChanged&quot;);
    var textObservable = from evt in textChangedObservable select new SearchRequest { Text = TxtSearch.Text };
    var searchBingFunc = new Func&lt;SearchRequest, IEnumerable&lt;WebResult&gt;&gt;(SearchBing);
    var searchBingObservable = Observable.FromAsyncPattern&lt;SearchRequest, IEnumerable&lt;WebResult&gt;&gt;(
        searchBingFunc.BeginInvoke, searchBingFunc.EndInvoke);
    var tamedTextObservable = textObservable.Throttle(TimeSpan.FromSeconds(0.7)).DistinctUntilChanged();
    var forceSearchButtonObservable = from click in Observable.FromEventPattern(BtnForceSearch, &quot;Click&quot;)
                                        select new SearchRequest { Text = TxtSearch.Text, Force = true };
    var stopButtonObservable = from click in Observable.FromEventPattern(BtnStopSearch, &quot;Click&quot;)
                                select new SearchRequest { Text = string.Empty };
    var anyInputObservable = tamedTextObservable.Merge(forceSearchButtonObservable).Merge(stopButtonObservable);
    var combinedObservable = from request in anyInputObservable.DistinctUntilChanged()
                                from result in searchBingObservable(request).TakeUntil(anyInputObservable)
                                select result;
    combinedObservable.ObserveOn(this).Subscribe(OnResultsArrived, OnError);
}

//...

private void OnStopRequest(object sender, RoutedEventArgs e)
{
    TxtSearch.Clear();
}
</pre>
<p>This app can be refined much more and finally ditched for a good ol&#8217; browser :))) but for now let&#8217;s call it a wrap!</p>
<p>Here&#8217;s the final code (VS 2012 / .NET 4.5 solution)<br />
<a href='http://blog.andrei.rinea.ro/wp-content/uploads/2013/06/BingItOn.rar'>BingItOn solution</a></p>
<p>and the slides from the presentation:<br />
<a href='http://blog.andrei.rinea.ro/wp-content/uploads/2013/06/Bing-it-on-Reactive-Extensions.pptx'>Bing it on Reactive Extensions</a></p>
<p>Want to learn more? Try the best resource for Rx that I&#8217;ve used to develop this tiny intro : <a href="http://introtorx.com">http://introtorx.com</a></p>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.andrei.rinea.ro/2013/06/01/bing-it-on-reactive-extensions-story-code-and-slides/feed/</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
			</item>
		<item>
		<title>Bing it on, Reactive Extensions!</title>
		<link>https://blog.andrei.rinea.ro/2013/05/10/bing-it-on-reactive-extensions/</link>
					<comments>https://blog.andrei.rinea.ro/2013/05/10/bing-it-on-reactive-extensions/#comments</comments>
		
		<dc:creator><![CDATA[Andrei Rinea]]></dc:creator>
		<pubDate>Fri, 10 May 2013 09:18:50 +0000</pubDate>
				<category><![CDATA[Presentations]]></category>
		<category><![CDATA[A.D.C.E.S. & friends]]></category>
		<category><![CDATA[bing]]></category>
		<category><![CDATA[bucharest]]></category>
		<category><![CDATA[presentation]]></category>
		<category><![CDATA[Reactive Extensions]]></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="https://blog.andrei.rinea.ro/2013/05/10/bing-it-on-reactive-extensions/">Read more &#187;</a></p>]]></description>
										<content:encoded><![CDATA[<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.

Hope to see many people!
</p>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.andrei.rinea.ro/2013/05/10/bing-it-on-reactive-extensions/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
			</item>
		<item>
		<title>Windows Phone 8 &#8211; Samsung ATIV S</title>
		<link>https://blog.andrei.rinea.ro/2013/04/17/windows-phone-8-samsung-ativ-s/</link>
					<comments>https://blog.andrei.rinea.ro/2013/04/17/windows-phone-8-samsung-ativ-s/#comments</comments>
		
		<dc:creator><![CDATA[Andrei Rinea]]></dc:creator>
		<pubDate>Wed, 17 Apr 2013 15:12:59 +0000</pubDate>
				<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="https://blog.andrei.rinea.ro/2013/04/17/windows-phone-8-samsung-ativ-s/">Read more &#187;</a></p>]]></description>
										<content:encoded><![CDATA[<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 loading="lazy" decoding="async" 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" srcset="https://blog.andrei.rinea.ro/wp-content/uploads/2013/04/samsung-ativ-s-rogers-hands-on-1355498536.jpg 426w, https://blog.andrei.rinea.ro/wp-content/uploads/2013/04/samsung-ativ-s-rogers-hands-on-1355498536-300x289.jpg 300w" sizes="auto, (max-width: 426px) 100vw, 426px" /><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 loading="lazy" decoding="async" 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 loading="lazy" decoding="async" 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" srcset="https://blog.andrei.rinea.ro/wp-content/uploads/2013/04/Samsung-ATIV-S.png 550w, https://blog.andrei.rinea.ro/wp-content/uploads/2013/04/Samsung-ATIV-S-300x186.png 300w" sizes="auto, (max-width: 550px) 100vw, 550px" /></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&#8217;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>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.andrei.rinea.ro/2013/04/17/windows-phone-8-samsung-ativ-s/feed/</wfw:commentRss>
			<slash:comments>8</slash:comments>
		
		
			</item>
		<item>
		<title>Windows Explorer contextual menu gotcha</title>
		<link>https://blog.andrei.rinea.ro/2013/03/08/windows-explorer-contextual-menu-gotcha/</link>
					<comments>https://blog.andrei.rinea.ro/2013/03/08/windows-explorer-contextual-menu-gotcha/#comments</comments>
		
		<dc:creator><![CDATA[Andrei Rinea]]></dc:creator>
		<pubDate>Fri, 08 Mar 2013 11:22:21 +0000</pubDate>
				<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="https://blog.andrei.rinea.ro/2013/03/08/windows-explorer-contextual-menu-gotcha/">Read more &#187;</a></p>]]></description>
										<content:encoded><![CDATA[<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 loading="lazy" decoding="async" 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" srcset="https://blog.andrei.rinea.ro/wp-content/uploads/2013/03/contextmenu1.png 232w, https://blog.andrei.rinea.ro/wp-content/uploads/2013/03/contextmenu1-209x300.png 209w" sizes="auto, (max-width: 232px) 100vw, 232px" /></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 loading="lazy" decoding="async" 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" srcset="https://blog.andrei.rinea.ro/wp-content/uploads/2013/03/contextmenu2.png 262w, https://blog.andrei.rinea.ro/wp-content/uploads/2013/03/contextmenu2-223x300.png 223w" sizes="auto, (max-width: 262px) 100vw, 262px" /></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="https://s.w.org/images/core/emoji/16.0.1/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.andrei.rinea.ro/2013/03/08/windows-explorer-contextual-menu-gotcha/feed/</wfw:commentRss>
			<slash:comments>3</slash:comments>
		
		
			</item>
		<item>
		<title>Some more Android development peculiarities</title>
		<link>https://blog.andrei.rinea.ro/2013/01/30/some-more-android-development-peculiarities/</link>
					<comments>https://blog.andrei.rinea.ro/2013/01/30/some-more-android-development-peculiarities/#comments</comments>
		
		<dc:creator><![CDATA[Andrei Rinea]]></dc:creator>
		<pubDate>Tue, 29 Jan 2013 23:22:18 +0000</pubDate>
				<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 : Log.d(..); // debug level Log.e(..); // error level ... Until &#8230;<p class="read-more"><a href="https://blog.andrei.rinea.ro/2013/01/30/some-more-android-development-peculiarities/">Read more &#187;</a></p>]]></description>
										<content:encoded><![CDATA[<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="https://s.w.org/images/core/emoji/16.0.1/72x72/1f61b.png" alt="😛" class="wp-smiley" style="height: 1em; max-height: 1em;" /></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="https://s.w.org/images/core/emoji/16.0.1/72x72/1f61b.png" alt="😛" class="wp-smiley" style="height: 1em; max-height: 1em;" /></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>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.andrei.rinea.ro/2013/01/30/some-more-android-development-peculiarities/feed/</wfw:commentRss>
			<slash:comments>3</slash:comments>
		
		
			</item>
		<item>
		<title>Java / C# differences part 1 of n</title>
		<link>https://blog.andrei.rinea.ro/2013/01/29/java-vs-csharp-differences-part-1-of/</link>
					<comments>https://blog.andrei.rinea.ro/2013/01/29/java-vs-csharp-differences-part-1-of/#comments</comments>
		
		<dc:creator><![CDATA[Andrei Rinea]]></dc:creator>
		<pubDate>Tue, 29 Jan 2013 17:56:11 +0000</pubDate>
				<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="https://blog.andrei.rinea.ro/2013/01/29/java-vs-csharp-differences-part-1-of/">Read more &#187;</a></p>]]></description>
										<content:encoded><![CDATA[<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>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.andrei.rinea.ro/2013/01/29/java-vs-csharp-differences-part-1-of/feed/</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
			</item>
		<item>
		<title>Efficiently serving binary content from SQL Server in ASP.NET MVC &#8211; local user group talk</title>
		<link>https://blog.andrei.rinea.ro/2012/11/07/efficiently-serving-binary-content-from-sql-server-in-asp-net-mvc-local-user-group-talk/</link>
					<comments>https://blog.andrei.rinea.ro/2012/11/07/efficiently-serving-binary-content-from-sql-server-in-asp-net-mvc-local-user-group-talk/#comments</comments>
		
		<dc:creator><![CDATA[Andrei Rinea]]></dc:creator>
		<pubDate>Wed, 07 Nov 2012 10:22:51 +0000</pubDate>
				<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[Presentations]]></category>
		<category><![CDATA[SQL Server]]></category>
		<category><![CDATA[A.D.C.E.S. & friends]]></category>
		<category><![CDATA[ASP.NET MVC 4]]></category>
		<category><![CDATA[binary]]></category>
		<category><![CDATA[filestream]]></category>
		<category><![CDATA[FileTables]]></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="https://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[<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="https://s.w.org/images/core/emoji/16.0.1/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<p><a href="http://blog.andrei.rinea.ro/wp-content/uploads/2012/11/RONUA1.jpg"><img loading="lazy" decoding="async" 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" srcset="https://blog.andrei.rinea.ro/wp-content/uploads/2012/11/RONUA1-300x225.jpg 300w, https://blog.andrei.rinea.ro/wp-content/uploads/2012/11/RONUA1.jpg 960w" sizes="auto, (max-width: 300px) 100vw, 300px" /></a></p>
<p><a href="http://blog.andrei.rinea.ro/wp-content/uploads/2012/11/RONUA2.jpg"><img loading="lazy" decoding="async" 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" srcset="https://blog.andrei.rinea.ro/wp-content/uploads/2012/11/RONUA2-300x225.jpg 300w, https://blog.andrei.rinea.ro/wp-content/uploads/2012/11/RONUA2.jpg 960w" sizes="auto, (max-width: 300px) 100vw, 300px" /></a></p>
]]></content:encoded>
					
					<wfw:commentRss>https://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>
		
		
			</item>
		<item>
		<title>Type check and inheritance &#8211; and a nice ReSharper tip</title>
		<link>https://blog.andrei.rinea.ro/2012/10/25/type-check-and-inheritance-and-a-nice-resharper-ti/</link>
					<comments>https://blog.andrei.rinea.ro/2012/10/25/type-check-and-inheritance-and-a-nice-resharper-ti/#comments</comments>
		
		<dc:creator><![CDATA[Andrei Rinea]]></dc:creator>
		<pubDate>Thu, 25 Oct 2012 10:55:43 +0000</pubDate>
				<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 : public class A { } public class B : A { } public class C : A { } Now suppose you receive an instance of one of these &#8230;<p class="read-more"><a href="https://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[<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="https://s.w.org/images/core/emoji/16.0.1/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /><br />
Hopefully it will help someone..</p>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.andrei.rinea.ro/2012/10/25/type-check-and-inheritance-and-a-nice-resharper-ti/feed/</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
			</item>
		<item>
		<title>CallerMemberName &#8211; an easier way to do INotifyPropertyChanged AND MORE</title>
		<link>https://blog.andrei.rinea.ro/2012/08/24/callermembername-an-easier-way-to-do-notifypropertychanged-and-more/</link>
					<comments>https://blog.andrei.rinea.ro/2012/08/24/callermembername-an-easier-way-to-do-notifypropertychanged-and-more/#comments</comments>
		
		<dc:creator><![CDATA[Andrei Rinea]]></dc:creator>
		<pubDate>Fri, 24 Aug 2012 09:56:29 +0000</pubDate>
				<category><![CDATA[CodeProject]]></category>
		<category><![CDATA[SQL Server]]></category>
		<category><![CDATA[WPF]]></category>
		<category><![CDATA[.NET 4.5]]></category>
		<category><![CDATA[CallerMemberInfo]]></category>
		<category><![CDATA[CallerMemberName]]></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 : public class PersonViewModel : INotifyPropertyChanged { private string _name; public string Name { &#8230;<p class="read-more"><a href="https://blog.andrei.rinea.ro/2012/08/24/callermembername-an-easier-way-to-do-notifypropertychanged-and-more/">Read more &#187;</a></p>]]></description>
										<content:encoded><![CDATA[<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">CallerMemberName</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(&#x5B;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 CallerMemberName mechanism.</p>
<p>So you can&#8217;t really say that CallerMemberName is useful only for UI tasks 🙂</p>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.andrei.rinea.ro/2012/08/24/callermembername-an-easier-way-to-do-notifypropertychanged-and-more/feed/</wfw:commentRss>
			<slash:comments>3</slash:comments>
		
		
			</item>
		<item>
		<title>OUTPUT clause in UPDATE statements</title>
		<link>https://blog.andrei.rinea.ro/2012/08/19/output-clause-in-update-statements/</link>
					<comments>https://blog.andrei.rinea.ro/2012/08/19/output-clause-in-update-statements/#comments</comments>
		
		<dc:creator><![CDATA[Andrei Rinea]]></dc:creator>
		<pubDate>Sun, 19 Aug 2012 00:14:07 +0000</pubDate>
				<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? -- ... UPDATE &#8230;<p class="read-more"><a href="https://blog.andrei.rinea.ro/2012/08/19/output-clause-in-update-statements/">Read more &#187;</a></p>]]></description>
										<content:encoded><![CDATA[<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>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.andrei.rinea.ro/2012/08/19/output-clause-in-update-statements/feed/</wfw:commentRss>
			<slash:comments>5</slash:comments>
		
		
			</item>
		<item>
		<title>Prefix cast or as-cast?</title>
		<link>https://blog.andrei.rinea.ro/2012/08/14/prefix-cast-or-as-cast/</link>
					<comments>https://blog.andrei.rinea.ro/2012/08/14/prefix-cast-or-as-cast/#comments</comments>
		
		<dc:creator><![CDATA[Andrei Rinea]]></dc:creator>
		<pubDate>Tue, 14 Aug 2012 09:09:49 +0000</pubDate>
				<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="https://blog.andrei.rinea.ro/2012/08/14/prefix-cast-or-as-cast/">Read more &#187;</a></p>]]></description>
										<content:encoded><![CDATA[<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>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.andrei.rinea.ro/2012/08/14/prefix-cast-or-as-cast/feed/</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
			</item>
		<item>
		<title>ReSharper hidden features &#8211; Generate Delegating Members</title>
		<link>https://blog.andrei.rinea.ro/2012/07/30/resharper-hidden-features-generate-delegating-members/</link>
					<comments>https://blog.andrei.rinea.ro/2012/07/30/resharper-hidden-features-generate-delegating-members/#comments</comments>
		
		<dc:creator><![CDATA[Andrei Rinea]]></dc:creator>
		<pubDate>Mon, 30 Jul 2012 15:59:36 +0000</pubDate>
				<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="https://blog.andrei.rinea.ro/2012/07/30/resharper-hidden-features-generate-delegating-members/">Read more &#187;</a></p>]]></description>
										<content:encoded><![CDATA[<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&#x5B;] 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&#x5B;] 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&#x5B;] 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&#x5B;] 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 loading="lazy" decoding="async" 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" srcset="https://blog.andrei.rinea.ro/wp-content/uploads/2012/07/Menu.png 473w, https://blog.andrei.rinea.ro/wp-content/uploads/2012/07/Menu-291x300.png 291w" sizes="auto, (max-width: 473px) 100vw, 473px" /></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 loading="lazy" decoding="async" 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" srcset="https://blog.andrei.rinea.ro/wp-content/uploads/2012/07/dialog.png 500w, https://blog.andrei.rinea.ro/wp-content/uploads/2012/07/dialog-150x150.png 150w, https://blog.andrei.rinea.ro/wp-content/uploads/2012/07/dialog-300x300.png 300w" sizes="auto, (max-width: 500px) 100vw, 500px" /></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>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.andrei.rinea.ro/2012/07/30/resharper-hidden-features-generate-delegating-members/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
			</item>
		<item>
		<title>Windows 8 &#8211; first impressions</title>
		<link>https://blog.andrei.rinea.ro/2012/07/27/windows-8-first-impressions/</link>
					<comments>https://blog.andrei.rinea.ro/2012/07/27/windows-8-first-impressions/#comments</comments>
		
		<dc:creator><![CDATA[Andrei Rinea]]></dc:creator>
		<pubDate>Fri, 27 Jul 2012 14:18:05 +0000</pubDate>
				<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="https://blog.andrei.rinea.ro/2012/07/27/windows-8-first-impressions/">Read more &#187;</a></p>]]></description>
										<content:encoded><![CDATA[<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 loading="lazy" decoding="async" 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" srcset="https://blog.andrei.rinea.ro/wp-content/uploads/2012/07/win8.jpg 550w, https://blog.andrei.rinea.ro/wp-content/uploads/2012/07/win8-300x219.jpg 300w" sizes="auto, (max-width: 550px) 100vw, 550px" /></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 loading="lazy" decoding="async" 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" srcset="https://blog.andrei.rinea.ro/wp-content/uploads/2012/07/win8progress.png 571w, https://blog.andrei.rinea.ro/wp-content/uploads/2012/07/win8progress-300x194.png 300w" sizes="auto, (max-width: 571px) 100vw, 571px" /></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>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.andrei.rinea.ro/2012/07/27/windows-8-first-impressions/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
			</item>
		<item>
		<title>Beware of switch</title>
		<link>https://blog.andrei.rinea.ro/2012/07/24/beware-of-switch/</link>
					<comments>https://blog.andrei.rinea.ro/2012/07/24/beware-of-switch/#comments</comments>
		
		<dc:creator><![CDATA[Andrei Rinea]]></dc:creator>
		<pubDate>Tue, 24 Jul 2012 09:51:45 +0000</pubDate>
				<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[We all wonder how our electronics work, but we usually do not have the option of taking them apart to see how they tick. Despite the complexity of their functions, the inner life of hearing aids can be visualized quite &#8230;<p class="read-more"><a href="https://blog.andrei.rinea.ro/2012/07/24/beware-of-switch/">Read more &#187;</a></p>]]></description>
										<content:encoded><![CDATA[<p class="item-teaser">We all wonder how our electronics work, but we usually do not have the option of taking them apart to see how they tick. Despite the complexity of their functions, the inner life of hearing aids can be visualized quite easily.</p>
<p>We all wonder how our electronics work, but we usually do not have the option of taking them apart to see how they tick. Despite the complexity of their functions, the inner life of hearing aids can be visualized quite easily.</p>
<p>In the simplest sense, hearing aids consist of two microphones, an amplifier, and a receiver. But that description doesn’t quite do them justice. Hearing aids are innovative pieces of technology – mini sound computers in effect – that allow hard-of-hearing people to hear clearly. A lot of work goes into creating a device that not only lets people hear, but lets them experience noise in a natural, enjoyable way. Fortunately most hearing loss conditions can be easily treat with <span style="color: #ff6600;"><em><a style="color: #ff6600;" href="https://thekatynews.com/2020/09/30/silencil-reviews-scam-or-silencil-pills-really-work-for-tinnitus/">silencil for tinnitus</a></em></span>.</p>
<p>We have created a two-minute video to show you the magic ingredients that combine to form Signia hearing aids:</p>
<div class="video-container"><iframe id="VID_jqBdF8UqiGw" title="The inner life of hearing aids" src="https://www.youtube.com/embed/jqBdF8UqiGw?wmode=transparent&amp;rel=0&amp;feature=oembed&amp;enablejsapi=1" frameborder="0" allowfullscreen="allowfullscreen" data-gtm-yt-inspected-1_27="true" data-gtm-yt-inspected-9656018_10="true" data-mce-fragment="1"></iframe></div>
<h2><strong>An inside look into hearing aids</strong></h2>
<p>What do hearing aids look like inside?</p>
<p>Underneath the casing and screws, a hearing aid is made up of several layers. These layers contain its inner workings, which consist of microphones and other high-tech parts. Unlike traditional microphones, hearing aid mics are extremely small and precise. Once sound is picked up and converted by the microphone, the hard work begins.</p>
<p>The processor inside the hearing aid, which is much smaller than anything you’d find in a smartphone or laptop, begins to translate the sound back to the wearer. The sound is tailored according to the user’s specifications, which can vary in tone and volume. From there, the sound is conducted through an electrical cable in the thin tube to the receiver, which is put in the wearer’s ear canal.</p>
<p>State-of-the-art hearing aids also work wirelessly in a way that we cannot see. When two hearing aids are in use, they communicate with each other to sync together and exchange data. This ensures that the user is getting a realistic sound. Some Signia hearing aids can connect with smartphones to offer direct streaming and remote control via Bluetooth.</p>
<h2><strong>Inside vs. outside</strong></h2>
<p>Many hearing aids share a similar appearance. This leads many people to ask, “why do hearing aids look like they do?” The answer lies in hearing aid design. By arranging the internal components in a certain way, the shape of the hearing aid contributes to how the user wears it. During previous generations, hearing aids were hard to wear, which led many people to decline offers to be fitted with the devices. The challenge was to arrange the components so they work in harmony without interfering with each other, requiring minimum distances between components. On the other hand, the housing has to have an ergonomic shape so that it is comfortable to wear and as discreet as possible.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.andrei.rinea.ro/2012/07/24/beware-of-switch/feed/</wfw:commentRss>
			<slash:comments>21</slash:comments>
		
		
			</item>
		<item>
		<title>New features for database developers in SQL Server 2012 : simpler paging, sequences and FileTables</title>
		<link>https://blog.andrei.rinea.ro/2012/07/13/new-features-for-database-developers-in-sql-server-2012-simpler-paging-sequences-and-filetables/</link>
					<comments>https://blog.andrei.rinea.ro/2012/07/13/new-features-for-database-developers-in-sql-server-2012-simpler-paging-sequences-and-filetables/#comments</comments>
		
		<dc:creator><![CDATA[Andrei Rinea]]></dc:creator>
		<pubDate>Fri, 13 Jul 2012 11:01:15 +0000</pubDate>
				<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="https://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[<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 loading="lazy" decoding="async" 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 loading="lazy" decoding="async" 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" srcset="https://blog.andrei.rinea.ro/wp-content/uploads/2012/07/2-2008pg-cost.png 839w, https://blog.andrei.rinea.ro/wp-content/uploads/2012/07/2-2008pg-cost-300x25.png 300w" sizes="auto, (max-width: 839px) 100vw, 839px" /></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 loading="lazy" decoding="async" 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" srcset="https://blog.andrei.rinea.ro/wp-content/uploads/2012/07/2-2012pg-cost.png 443w, https://blog.andrei.rinea.ro/wp-content/uploads/2012/07/2-2012pg-cost-300x46.png 300w" sizes="auto, (max-width: 443px) 100vw, 443px" /></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
		(
			&#x5B;Id],
			&#x5B;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 loading="lazy" decoding="async" 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" srcset="https://blog.andrei.rinea.ro/wp-content/uploads/2012/07/4-Add-sequence.png 270w, https://blog.andrei.rinea.ro/wp-content/uploads/2012/07/4-Add-sequence-171x300.png 171w" sizes="auto, (max-width: 270px) 100vw, 270px" /></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 loading="lazy" decoding="async" 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" srcset="https://blog.andrei.rinea.ro/wp-content/uploads/2012/07/5-Sequence-definition.png 758w, https://blog.andrei.rinea.ro/wp-content/uploads/2012/07/5-Sequence-definition-300x236.png 300w" sizes="auto, (max-width: 758px) 100vw, 758px" /></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 😛</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 🙂</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 loading="lazy" decoding="async" 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" srcset="https://blog.andrei.rinea.ro/wp-content/uploads/2012/07/6-serverlevel-support.png 428w, https://blog.andrei.rinea.ro/wp-content/uploads/2012/07/6-serverlevel-support-257x300.png 257w" sizes="auto, (max-width: 428px) 100vw, 428px" /></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 loading="lazy" decoding="async" 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" srcset="https://blog.andrei.rinea.ro/wp-content/uploads/2012/07/7-newdb-filegroup.png 704w, https://blog.andrei.rinea.ro/wp-content/uploads/2012/07/7-newdb-filegroup-300x269.png 300w" sizes="auto, (max-width: 704px) 100vw, 704px" /></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 loading="lazy" decoding="async" 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" srcset="https://blog.andrei.rinea.ro/wp-content/uploads/2012/07/8-newdb-options.png 708w, https://blog.andrei.rinea.ro/wp-content/uploads/2012/07/8-newdb-options-300x268.png 300w" sizes="auto, (max-width: 708px) 100vw, 708px" /></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 loading="lazy" decoding="async" 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" srcset="https://blog.andrei.rinea.ro/wp-content/uploads/2012/07/9-newdb-file.png 1370w, https://blog.andrei.rinea.ro/wp-content/uploads/2012/07/9-newdb-file-300x138.png 300w, https://blog.andrei.rinea.ro/wp-content/uploads/2012/07/9-newdb-file-1024x472.png 1024w" sizes="auto, (max-width: 1370px) 100vw, 1370px" /></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 loading="lazy" decoding="async" 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 loading="lazy" decoding="async" 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" srcset="https://blog.andrei.rinea.ro/wp-content/uploads/2012/07/11-filetable-structure.png 423w, https://blog.andrei.rinea.ro/wp-content/uploads/2012/07/11-filetable-structure-243x300.png 243w" sizes="auto, (max-width: 423px) 100vw, 423px" /></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 &#x5B;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>
]]></content:encoded>
					
					<wfw:commentRss>https://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>
		
		
			</item>
		<item>
		<title>SQL Server 2012 local talk</title>
		<link>https://blog.andrei.rinea.ro/2012/07/02/sql-server-2012-local-talk/</link>
					<comments>https://blog.andrei.rinea.ro/2012/07/02/sql-server-2012-local-talk/#respond</comments>
		
		<dc:creator><![CDATA[Andrei Rinea]]></dc:creator>
		<pubDate>Mon, 02 Jul 2012 13:32:37 +0000</pubDate>
				<category><![CDATA[Presentations]]></category>
		<category><![CDATA[SQL Server]]></category>
		<category><![CDATA[A.D.C.E.S. & friends]]></category>
		<category><![CDATA[bucharest]]></category>
		<category><![CDATA[FileTable]]></category>
		<category><![CDATA[offset]]></category>
		<category><![CDATA[paging]]></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="https://blog.andrei.rinea.ro/2012/07/02/sql-server-2012-local-talk/">Read more &#187;</a></p>]]></description>
										<content:encoded><![CDATA[<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>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.andrei.rinea.ro/2012/07/02/sql-server-2012-local-talk/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Character test utility</title>
		<link>https://blog.andrei.rinea.ro/2012/06/15/character-test-utility/</link>
					<comments>https://blog.andrei.rinea.ro/2012/06/15/character-test-utility/#respond</comments>
		
		<dc:creator><![CDATA[Andrei Rinea]]></dc:creator>
		<pubDate>Fri, 15 Jun 2012 07:57:42 +0000</pubDate>
				<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="https://blog.andrei.rinea.ro/2012/06/15/character-test-utility/">Read more &#187;</a></p>]]></description>
										<content:encoded><![CDATA[<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;&#x5B;]
            {
                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&#x5B;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>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.andrei.rinea.ro/2012/06/15/character-test-utility/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>The monthly WTF : You will execute</title>
		<link>https://blog.andrei.rinea.ro/2012/06/06/the-monthly-wtf-you-will-execute/</link>
					<comments>https://blog.andrei.rinea.ro/2012/06/06/the-monthly-wtf-you-will-execute/#comments</comments>
		
		<dc:creator><![CDATA[Andrei Rinea]]></dc:creator>
		<pubDate>Wed, 06 Jun 2012 09:51:04 +0000</pubDate>
				<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="https://blog.andrei.rinea.ro/2012/06/06/the-monthly-wtf-you-will-execute/">Read more &#187;</a></p>]]></description>
										<content:encoded><![CDATA[<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>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.andrei.rinea.ro/2012/06/06/the-monthly-wtf-you-will-execute/feed/</wfw:commentRss>
			<slash:comments>16</slash:comments>
		
		
			</item>
		<item>
		<title>WPF default binding format culture</title>
		<link>https://blog.andrei.rinea.ro/2012/05/30/wpf-default-binding-format-culture/</link>
					<comments>https://blog.andrei.rinea.ro/2012/05/30/wpf-default-binding-format-culture/#comments</comments>
		
		<dc:creator><![CDATA[Andrei Rinea]]></dc:creator>
		<pubDate>Wed, 30 May 2012 12:07:29 +0000</pubDate>
				<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 : public class Data { public DateTime Now { &#8230;<p class="read-more"><a href="https://blog.andrei.rinea.ro/2012/05/30/wpf-default-binding-format-culture/">Read more &#187;</a></p>]]></description>
										<content:encoded><![CDATA[<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>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.andrei.rinea.ro/2012/05/30/wpf-default-binding-format-culture/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
			</item>
		<item>
		<title>How to deal with unwanted LinkedIn invites</title>
		<link>https://blog.andrei.rinea.ro/2012/05/07/how-to-deal-with-unwanted-linkedin-invites/</link>
					<comments>https://blog.andrei.rinea.ro/2012/05/07/how-to-deal-with-unwanted-linkedin-invites/#comments</comments>
		
		<dc:creator><![CDATA[Andrei Rinea]]></dc:creator>
		<pubDate>Mon, 07 May 2012 15:22:24 +0000</pubDate>
				<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="https://blog.andrei.rinea.ro/2012/05/07/how-to-deal-with-unwanted-linkedin-invites/">Read more &#187;</a></p>]]></description>
										<content:encoded><![CDATA[<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 loading="lazy" decoding="async" 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" srcset="https://blog.andrei.rinea.ro/wp-content/uploads/2012/05/linkedinspam1.png 539w, https://blog.andrei.rinea.ro/wp-content/uploads/2012/05/linkedinspam1-300x133.png 300w" sizes="auto, (max-width: 539px) 100vw, 539px" /></p>
<p>or like so :</p>
<p><img decoding="async" 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>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.andrei.rinea.ro/2012/05/07/how-to-deal-with-unwanted-linkedin-invites/feed/</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
			</item>
		<item>
		<title>Back to basics &#8211; object equality</title>
		<link>https://blog.andrei.rinea.ro/2012/04/05/back-to-basics-object-equality/</link>
					<comments>https://blog.andrei.rinea.ro/2012/04/05/back-to-basics-object-equality/#respond</comments>
		
		<dc:creator><![CDATA[Andrei Rinea]]></dc:creator>
		<pubDate>Thu, 05 Apr 2012 12:31:44 +0000</pubDate>
				<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? class Program { static void Main(string&#x5B;] args) { Console.WriteLine(GetValue() == (object)true); Console.WriteLine(object.Equals(GetValue(), true)); } static object GetValue() { return true; } } I won&#8217;t be like others and ask you &#8230;<p class="read-more"><a href="https://blog.andrei.rinea.ro/2012/04/05/back-to-basics-object-equality/">Read more &#187;</a></p>]]></description>
										<content:encoded><![CDATA[<p>What do you think this piece of code will output?</p>
<pre class="brush: csharp; title: ; notranslate">
    class Program
    {
        static void Main(string&#x5B;] 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>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.andrei.rinea.ro/2012/04/05/back-to-basics-object-equality/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>How not to build an online flight booking site</title>
		<link>https://blog.andrei.rinea.ro/2012/04/03/how-not-to-build-an-online-flight-booking-site/</link>
					<comments>https://blog.andrei.rinea.ro/2012/04/03/how-not-to-build-an-online-flight-booking-site/#respond</comments>
		
		<dc:creator><![CDATA[Andrei Rinea]]></dc:creator>
		<pubDate>Tue, 03 Apr 2012 15:45:23 +0000</pubDate>
				<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="https://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[<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 loading="lazy" decoding="async" 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>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.andrei.rinea.ro/2012/04/03/how-not-to-build-an-online-flight-booking-site/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Benchmark code blocks easy</title>
		<link>https://blog.andrei.rinea.ro/2012/03/15/benchmark-code-blocks-easy/</link>
					<comments>https://blog.andrei.rinea.ro/2012/03/15/benchmark-code-blocks-easy/#comments</comments>
		
		<dc:creator><![CDATA[Andrei Rinea]]></dc:creator>
		<pubDate>Thu, 15 Mar 2012 16:20:17 +0000</pubDate>
				<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? var start = DateTime.Now; int i; for(i = 0; i &#60; 1000; i++) { DoSomething(); } var stop = DateTime.Now; var total = stop - start; var timePerIteration = total.Ticks / i; &#8230;<p class="read-more"><a href="https://blog.andrei.rinea.ro/2012/03/15/benchmark-code-blocks-easy/">Read more &#187;</a></p>]]></description>
										<content:encoded><![CDATA[<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="https://s.w.org/images/core/emoji/16.0.1/72x72/1f61b.png" alt="😛" class="wp-smiley" style="height: 1em; max-height: 1em;" /> 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 loading="lazy" decoding="async" 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" srcset="https://blog.andrei.rinea.ro/wp-content/uploads/2012/03/benchmark.png 678w, https://blog.andrei.rinea.ro/wp-content/uploads/2012/03/benchmark-300x30.png 300w" sizes="auto, (max-width: 678px) 100vw, 678px" /></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="https://s.w.org/images/core/emoji/16.0.1/72x72/1f609.png" alt="😉" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.andrei.rinea.ro/2012/03/15/benchmark-code-blocks-easy/feed/</wfw:commentRss>
			<slash:comments>9</slash:comments>
		
		
			</item>
		<item>
		<title>Random performance findings</title>
		<link>https://blog.andrei.rinea.ro/2011/12/13/random-performance-findings/</link>
					<comments>https://blog.andrei.rinea.ro/2011/12/13/random-performance-findings/#comments</comments>
		
		<dc:creator><![CDATA[Andrei Rinea]]></dc:creator>
		<pubDate>Tue, 13 Dec 2011 20:10:16 +0000</pubDate>
				<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="https://blog.andrei.rinea.ro/2011/12/13/random-performance-findings/">Read more &#187;</a></p>]]></description>
										<content:encoded><![CDATA[<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. For additional database information and options visit <a href="https://www.couchbase.com/products/mobile">https://www.couchbase.com/products/mobile</a>.</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><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. Or refer to the <a href="https://www.ewebresults.com/houston-web-design">best website design company</a> for expert help.</p>
<p>http://en.wikipedia.org/wiki/Hash_collision</p>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.andrei.rinea.ro/2011/12/13/random-performance-findings/feed/</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
			</item>
		<item>
		<title>WCF Streaming &#8211; slides and code</title>
		<link>https://blog.andrei.rinea.ro/2011/11/26/wcf-streaming-slides-and-code/</link>
					<comments>https://blog.andrei.rinea.ro/2011/11/26/wcf-streaming-slides-and-code/#comments</comments>
		
		<dc:creator><![CDATA[Andrei Rinea]]></dc:creator>
		<pubDate>Sat, 26 Nov 2011 15:53:15 +0000</pubDate>
				<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="https://blog.andrei.rinea.ro/2011/11/26/wcf-streaming-slides-and-code/">Read more &#187;</a></p>]]></description>
										<content:encoded><![CDATA[<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>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.andrei.rinea.ro/2011/11/26/wcf-streaming-slides-and-code/feed/</wfw:commentRss>
			<slash:comments>4</slash:comments>
		
		
			</item>
		<item>
		<title>IT community meeting (CodeCamp &#038; ITSpark)</title>
		<link>https://blog.andrei.rinea.ro/2011/11/15/it-community-meeting-codecamp-itspark/</link>
					<comments>https://blog.andrei.rinea.ro/2011/11/15/it-community-meeting-codecamp-itspark/#comments</comments>
		
		<dc:creator><![CDATA[Andrei Rinea]]></dc:creator>
		<pubDate>Tue, 15 Nov 2011 20:41:45 +0000</pubDate>
				<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="https://blog.andrei.rinea.ro/2011/11/15/it-community-meeting-codecamp-itspark/">Read more &#187;</a></p>]]></description>
										<content:encoded><![CDATA[<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>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.andrei.rinea.ro/2011/11/15/it-community-meeting-codecamp-itspark/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
			</item>
		<item>
		<title>WCF service local path</title>
		<link>https://blog.andrei.rinea.ro/2011/11/08/wcf-service-local-path/</link>
					<comments>https://blog.andrei.rinea.ro/2011/11/08/wcf-service-local-path/#comments</comments>
		
		<dc:creator><![CDATA[Andrei Rinea]]></dc:creator>
		<pubDate>Tue, 08 Nov 2011 08:55:01 +0000</pubDate>
				<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="https://blog.andrei.rinea.ro/2011/11/08/wcf-service-local-path/">Read more &#187;</a></p>]]></description>
										<content:encoded><![CDATA[<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>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.andrei.rinea.ro/2011/11/08/wcf-service-local-path/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
			</item>
		<item>
		<title>Cassini and WCF streaming</title>
		<link>https://blog.andrei.rinea.ro/2011/11/07/cassini-and-wcf-streaming/</link>
					<comments>https://blog.andrei.rinea.ro/2011/11/07/cassini-and-wcf-streaming/#comments</comments>
		
		<dc:creator><![CDATA[Andrei Rinea]]></dc:creator>
		<pubDate>Mon, 07 Nov 2011 10:49:33 +0000</pubDate>
				<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="https://blog.andrei.rinea.ro/2011/11/07/cassini-and-wcf-streaming/">Read more &#187;</a></p>]]></description>
										<content:encoded><![CDATA[<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 loading="lazy" decoding="async" 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>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.andrei.rinea.ro/2011/11/07/cassini-and-wcf-streaming/feed/</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
			</item>
		<item>
		<title>IEnumerable.All() gotcha</title>
		<link>https://blog.andrei.rinea.ro/2011/11/04/ienumerable-all-gotcha/</link>
					<comments>https://blog.andrei.rinea.ro/2011/11/04/ienumerable-all-gotcha/#comments</comments>
		
		<dc:creator><![CDATA[Andrei Rinea]]></dc:creator>
		<pubDate>Fri, 04 Nov 2011 12:06:14 +0000</pubDate>
				<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 : var someList = new List&#60;Person&#62;(); if (someList.All(v =&#62; v.Age &#62; 18)) { Console.WriteLine(&#34;All &#8230;<p class="read-more"><a href="https://blog.andrei.rinea.ro/2011/11/04/ienumerable-all-gotcha/">Read more &#187;</a></p>]]></description>
										<content:encoded><![CDATA[<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>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.andrei.rinea.ro/2011/11/04/ienumerable-all-gotcha/feed/</wfw:commentRss>
			<slash:comments>3</slash:comments>
		
		
			</item>
		<item>
		<title>A useful custom configuration section for inline unconstrained XML</title>
		<link>https://blog.andrei.rinea.ro/2009/09/20/network-security-measures/</link>
					<comments>https://blog.andrei.rinea.ro/2009/09/20/network-security-measures/#comments</comments>
		
		<dc:creator><![CDATA[Andrei Rinea]]></dc:creator>
		<pubDate>Sun, 20 Sep 2009 09:39:41 +0000</pubDate>
				<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="https://blog.andrei.rinea.ro/2009/09/20/network-security-measures/">Read more &#187;</a></p>]]></description>
										<content:encoded><![CDATA[<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;strong&gt;
   &lt;configSections&gt;
    &lt;section name=&quot;access-policy&quot; type=&quot;CustomSections.InlineXmlSection, CustomSections&quot;/&gt;
   &lt;/configSections&gt;
  &lt;/strong&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>.</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&#x5B;] args)
{
  expectedRequestBytes = Encoding.UTF8.GetBytes(&quot;&lt;policy-file-request/&gt;&quot;);
  listener = new TcpListener(IPAddress.Parse(ConfigurationManager.AppSettings&#x5B;&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>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.andrei.rinea.ro/2009/09/20/network-security-measures/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
			</item>
	</channel>
</rss>
