<?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>Catalin's Zeroes and Ones</title>
	<atom:link href="http://blog.nvise.com/?feed=rss2" rel="self" type="application/rss+xml" />
	<link>http://blog.nvise.com</link>
	<description>// TODO: choose a tagline</description>
	<lastBuildDate>Mon, 17 Aug 2009 12:58:33 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<item>
		<title>Restoring Intel Matrix RAID Configuration</title>
		<link>http://blog.nvise.com/?p=31</link>
		<comments>http://blog.nvise.com/?p=31#comments</comments>
		<pubDate>Mon, 17 Aug 2009 12:58:33 +0000</pubDate>
		<dc:creator>Catalin</dc:creator>
				<category><![CDATA[Miscellaneous]]></category>

		<guid isPermaLink="false">http://blog.nvise.com/2009/08/restoring-intel-matrix-raid-configuration/</guid>
		<description><![CDATA[I had 2 HDDs in Intel Matrix RAID configuration on a motherboard with Intel southbridge ICH9R. I had a RAID 0 (Strip) volume and a RAID 1 (Mirroring) volume (Intel Matrix RAID allows you exactly that: having a RAID 0 &#8230; <a href="http://blog.nvise.com/?p=31">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>I had 2 HDDs in Intel Matrix RAID configuration on a motherboard with Intel southbridge ICH9R. I had a RAID 0 (Strip) volume and a RAID 1 (Mirroring) volume (Intel Matrix RAID allows you exactly that: having a RAID 0 and a RAID 1 volume on the same 2 HDDs).</p>
<p>Somehow when replacing my videocard I unplugged the power connector from one of the HDDs. When I booted only one disk was showing. So I turned off the PC and correctly plugged the power connector. But now both HDDs where there but showing as &quot;<strong>Non-Raid Disk</strong>&quot;</p>
<p><a href="http://blog.nvise.com/wp-content/uploads/2009/08/image.png"><img style="border-bottom: 0px; border-left: 0px; display: block; float: none; margin-left: auto; border-top: 0px; margin-right: auto; border-right: 0px" title="image" border="0" alt="image" src="http://blog.nvise.com/wp-content/uploads/2009/08/image-thumb.png" width="244" height="138" /></a> Under the BIOS RAID menu (you can enter this menu by pressing &lt;Ctrl+I&gt; after booting) the only choices I had where to create a RAID array, to delete a disk from the array or to reset it. No option to repair/recover/rebuild. </p>
<p>I tried many things like clearing CMOS, upgrading/downgrading BIOS version without any result, the disks kept showing as Non-Raid Disk.</p>
<p>So I installed Windows on a 3<sup>rd</sup> disk thinking that at least I’ll recover my data on the mirroring volume. But the mirroring partition wasn’t visible from windows. I tried all the partition recovery programs I could find but none of them could restore the Raid 1 partition. I found one program (<a href="http://www.derescue.com/">DERescue Data Recovery Master</a>) that could recover the files on this partition but not restore it. This was quite surprising because Raid 1 is supposed to be “safe”; if one of the disks is functioning correctly you should easily recover you data. And both disks where functioning correctly. I suppose that’s because of how Matrix Raid works; it keeps the information about the Raid configuration on the first volume and if the first volume fails everything fails. When configuring Matrix Raid the first volume should be the Raid 1 one. </p>
<p>So what to do? First, I played it safe and I buyed Data Recovery Master and recovered all my files on the Raid 1 partition. </p>
<p>Second, I went to Raid BIOS menu and tried to recreate the volumes using the same parameters as the first time I configured it (three years ago). I knew I had one raid 0 volume and one raid 1 volume but I wasn’t very sure about strip size or volume size. So each time I created the two volumes then used <a href="http://www.cgsecurity.org/wiki/TestDisk">TestDisk</a> under Windows to search for lost partitions then reinitialized the raid array and recreated the volumes with other settings.</p>
<p>When using incorrect strip size TestDisk didn’t found anything on “Quick Search” mode. When using correct strip size but incorrect volume size TestDisk managed to find some partitions on the strip volume but nothing on the second. With the right Raid settings it quickly finds all the partitions.</p>
<p>All the partitions where now visible but not bootable. I booted the Windows 7 install DVD and I choosed the repair option. It repaired the boot sector and I could boot Windows 7 I had on one of the partitions. </p>
<p>But still Windows XP I had on another partition wasn’t bootable. I launched <a href="http://neosmart.net/dl.php?id=1">EasyBCD</a> under Windows 7 and configured the right drive letter for XP and everything worked like before…</p>
<p>Conclusions: If you are going to use Matrix RAID always:</p>
<ol>
<li>Create RAID 1 volume first and RAID 0 second</li>
<li>Make sure you save your raid settings (strip size and volumes sizes) somewhere where you can find them later if your Raid gets reinitialized.</li>
</ol>
]]></content:encoded>
			<wfw:commentRss>http://blog.nvise.com/?feed=rss2&amp;p=31</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>ASP.NET MVC returning 302 (Found) HTTP status code on unauthorized Ajax calls instead of 401(Unauthorized) like classic ASP.NET</title>
		<link>http://blog.nvise.com/?p=26</link>
		<comments>http://blog.nvise.com/?p=26#comments</comments>
		<pubDate>Thu, 02 Jul 2009 12:10:20 +0000</pubDate>
		<dc:creator>Catalin</dc:creator>
				<category><![CDATA[AJAX]]></category>
		<category><![CDATA[JavaScript]]></category>

		<guid isPermaLink="false">http://blog.nvise.com/2009/07/aspnet-mvc-returning-302-found-http-status-code-on-unauthorized-ajax-calls-instead-of-401unauthorized-like-classic-aspnet/</guid>
		<description><![CDATA[Classic ASP.NET On classic ASP.NET when calling a [WebMethod] with Ajax in an unauthorized context (most likely in the case where the session expired) the response http status code is 401. You can handle this in the “error” handler (provided &#8230; <a href="http://blog.nvise.com/?p=26">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<h2>Classic ASP.NET</h2>
<p>On classic ASP.NET when calling a [WebMethod] with Ajax in an unauthorized context (most likely in the case where the session expired) the response http status code is 401. You can handle this in the “error” handler (provided by most Ajax frameworks) and redirect to login page. For example I use this code with jQuery:</p>
<p>WebMethod;</p>
<pre class="csharpcode">[WebMethod]
<span class="kwrd">public</span> <span class="kwrd">static</span> MyModel GetStuff()
{
    <span class="kwrd">return</span> <span class="kwrd">new</span> MyModel();
}</pre>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
<p>Javascript:</p>
<pre class="csharpcode">$.ajax({
    type: <span class="str">&quot;POST&quot;</span>,
    url: <span class="str">&quot;Default.aspx/GetStuff&quot;</span>,
    data: <span class="str">&quot;{}&quot;</span>,
    contentType: <span class="str">&quot;application/json; charset=utf-8&quot;</span>,
    dataType: <span class="str">&quot;json&quot;</span>,
    success: <span class="kwrd">function</span>(msg) {
        <span class="rem">// do stuff</span>
    },
    error: <span class="kwrd">function</span>(xhr, status, ex) {
        <span class="kwrd">if</span> (xhr.status == 401) <span class="rem">// unauthorized</span>
        {
            window.location = <span class="str">&quot;Login.aspx?ReturnUrl=&quot;</span> + window.location.pathname;
        }
    }
});</pre>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
<h2>ASP.NET MVC</h2>
<p>To do the same in ASP.NET MVC I have this method in my controller:</p>
<pre class="csharpcode">[Authorize]
<span class="kwrd">public</span> ActionResult GetStuff()
{
    <span class="kwrd">return</span> Json(<span class="kwrd">new</span> MyModel());
}</pre>
<p>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
<p>The ASP.NET MVC infrastructure doesn’t return 401 http status code on failed authorization but 302 http status code (actually the 401 status code is returned initially but later, in the same request, is intercepted by the infrastructure and replaced by 302 status code). <a href="http://fr.wikipedia.org/wiki/XMLHttpRequest" target="_blank">XMLHttpRequest</a> object handles this internally automatically following the redirect (no event is fired client side). The Ajax call will end in “success” but the message won’t be the expected JSON but the html of the login page.</p>
<p>The best (well, it’s a hack, if you a better way please tell me) way I found is to replace 302 status code by 401 status code on request end. I added the following code to Global.asax :</p>
<pre class="csharpcode"><span class="kwrd">protected</span> <span class="kwrd">void</span> Application_EndRequest()
{
    <span class="kwrd">if</span> (Context.Response.StatusCode == 302 &amp;&amp;
        Context.Request.Headers[<span class="str">&quot;X-Requested-With&quot;</span>] == <span class="str">&quot;XMLHttpRequest&quot;</span>)
    {
        Context.Response.Clear();
        Context.Response.StatusCode = 401;
    }
}</pre>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
<p>And the client side code (using Ext JS this time) is:</p>
<pre class="csharpcode">Ext.Ajax.on(<span class="str">'requestexception'</span>, <span class="kwrd">function</span>(conn, response, options) {
    <span class="kwrd">if</span> (response.status == 401) {
        window.location = <span class="str">'&lt;%= Html.ActionUrl(&quot;Account&quot;, &quot;LogOn&quot;) %&gt;?ReturnUrl='</span> +
            window.location.pathname;
    }
});</pre>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
]]></content:encoded>
			<wfw:commentRss>http://blog.nvise.com/?feed=rss2&amp;p=26</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Why aren&#8217;t my third party Ajax controls showing correctly in a ASP.NET MVC page ?</title>
		<link>http://blog.nvise.com/?p=22</link>
		<comments>http://blog.nvise.com/?p=22#comments</comments>
		<pubDate>Thu, 02 Jul 2009 07:55:12 +0000</pubDate>
		<dc:creator>Catalin</dc:creator>
				<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[CSS]]></category>
		<category><![CDATA[ASP.NET-MVC ExtJS CSS]]></category>

		<guid isPermaLink="false">http://blog.nvise.com/2009/07/why-arent-my-third-party-ajax-controls-showing-correctly-in-a-aspnet-mvc-page/</guid>
		<description><![CDATA[I was setting up a Ext JS grid and the rendering was wrong : It was a CSS conflict between default ASP.NET CSS and Ext JS CSS. After commenting out all table related styles from Site.css the grid pager is &#8230; <a href="http://blog.nvise.com/?p=22">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>I was setting up a <a href="http://extjs.com/" target="_blank">Ext JS</a> grid and the rendering was wrong :</p>
<p><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="cssconflict" border="0" alt="cssconflict" src="http://blog.nvise.com/wp-content/uploads/2009/07/cssconflict.png" width="650" height="69" /> </p>
<p>It was a CSS conflict between default ASP.NET CSS and Ext JS CSS. After commenting out all table related styles from Site.css the grid pager is displaying correctly:</p>
<p><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="image" border="0" alt="image" src="http://blog.nvise.com/wp-content/uploads/2009/07/image.png" width="406" height="36" /></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.nvise.com/?feed=rss2&amp;p=22</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Calling SharePoint web services using jQuery</title>
		<link>http://blog.nvise.com/?p=15</link>
		<comments>http://blog.nvise.com/?p=15#comments</comments>
		<pubDate>Thu, 02 Oct 2008 10:50:41 +0000</pubDate>
		<dc:creator>Catalin</dc:creator>
				<category><![CDATA[AJAX]]></category>
		<category><![CDATA[Sharepoint]]></category>
		<category><![CDATA[jQuery]]></category>

		<guid isPermaLink="false">http://blog.nvise.com/?p=15</guid>
		<description><![CDATA[I needed to update a SharePoint list item directly on client side in a classic SharePoint list form. I found this blog who explains very well how to do it by using Prototype but I was already using jQuery and &#8230; <a href="http://blog.nvise.com/?p=15">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>I needed to update a SharePoint list item directly on client side in a classic SharePoint list form. I found <a href="http://blog.glenc.net/2007/04/20/calling-sharepoint-web-services-from-javascript/">this blog</a> who explains very well how to do it by using Prototype but I was already using jQuery and didn&#8217;t want to add another javascript framework to my solution. Sure this is very easily portable to jQuery but I wanted a cleaner solution.</p>
<p>I found this: <a href="http://plugins.jquery.com/node/2604">jQuery SOAP Client</a>, a jQuery plug-in (it&#8217;s really an add-on because it doesn&#8217;t use jQuery extension mechanism) who was looking very promising. So I started to code&#8230;</p>
<p>I was going to call the UpdateListItems of the list web service (http://server/_vti_bin/lists.asmx). This method requires two arguments: <code>listName</code> and <code>updates</code>. Updates are the CAML commands describing the changes to the list and looks like this:</p>
<pre>
<pre class="brush: xml;">
&lt;Batch OnError=&quot;Continue&quot;&gt;
    &lt;Method ID=&quot;1&quot; Cmd=&quot;Update&quot;&gt;
       &lt;Field Name=&quot;ID&quot;&gt;1&lt;/Field&gt;
       &lt;Field Name=&quot;Title&quot;&gt;updated title&lt;/Field&gt;
    &lt;/Method&gt;
&lt;/Batch&gt;</pre>
</pre>
<p>I think that&#8217;s pretty readable: we want to change the Title of the element with the ID=1 to &#8220;updated title&#8221;.</p>
<p>Next: the javascript code using jQuery SOAP Client:</p>
<pre>
<pre class="brush: jscript;">
var wsMethod = &quot;UpdateListItems&quot;;
var soapNs = &quot;http://schemas.microsoft.com/sharepoint/soap/&quot;;

var soapBody = new SOAPObject(wsMethod);
soapBody.ns = soapNs;
soapBody.appendChild(new SOAPObject(&quot;listName&quot;)).val(&quot;list1&quot;);
soapBody.appendChild(new SOAPObject(&quot;updates&quot;)).val(batch);

var sr = new SOAPRequest(soapNs + wsMethod, soapBody);

SOAPClient.Proxy = &quot;http://server/_vti_bin/lists.asmx&quot;;

SOAPClient.SendRequest(sr, processResponse);
</pre>
</pre>
<p>For this to work it needs to be executed from an already authenticated SharePoint web page. Internet Explorer automatically passes the credentials with the XHR call. You could pass the credentials in the jQuery call but I wouldn&#8217;t do that if I where you.</p>
<p>Well, this didn&#8217;t work&#8230; I was getting some generic SharePoint error page, not very useful for debugging so I fired up Fiddler2.<br />
I found out that the response was a HTTP error code 415 &#8211; Unsupported Media Type. I noticed some differences between the SOAP request created by jQuery SOAP Client and the SOAP code expected by the service and modified the plug-in accordingly. But I was still getting the same error.</p>
<p>And then I saw it: the Content-Type sent was <code>application/x-www-form-urlencoded, text/xml; charset= "utf-8"</code>; Thing is when you make an AJAX call with jQuery it automatically ads <code>application/x-www-form-urlencoded</code> content-type if no content-type is specified. But jQuery SOAP Client added the content-type not by using jQuery but directly into the XmlHttpRequest object:</p>
<pre>
<pre class="brush: jscript;">
$.ajax({
	 type: &quot;POST&quot;,
	 url: SOAPClient.Proxy,
	 dataType: &quot;xml&quot;,
	 processData: false,
	 data: content,
	 complete: getResponse,
	 beforeSend: function(req) {
		req.setRequestHeader(&quot;Method&quot;, &quot;POST&quot;);
		req.setRequestHeader(&quot;Content-Length&quot;, SOAPClient.ContentLength);
		req.setRequestHeader(&quot;Content-Type&quot;, SOAPClient.ContentType + &quot;; charset=\&quot;&quot; + SOAPClient.CharSet + &quot;\&quot;&quot;);
		req.setRequestHeader(&quot;SOAPServer&quot;, SOAPClient.SOAPServer);
		req.setRequestHeader(&quot;SOAPAction&quot;, soapReq.Action);
	 }
});
</pre>
</pre>
<p>Fixing that was simple and&#8230; it worked!!!</p>
<pre>
<pre class="brush: jscript;">
$.ajax({
	 type: &quot;POST&quot;,
	 url: SOAPClient.Proxy,
	 dataType: &quot;xml&quot;,
	 processData: false,
	 data: content,
	 contentType : SOAPClient.ContentType + &quot;; charset=\&quot;&quot; + SOAPClient.CharSet + &quot;\&quot;&quot;,
	 complete: getResponse,
	 beforeSend: function(req) {
		req.setRequestHeader(&quot;Method&quot;, &quot;POST&quot;);
		req.setRequestHeader(&quot;Content-Length&quot;, SOAPClient.ContentLength);
		req.setRequestHeader(&quot;SOAPServer&quot;, SOAPClient.SOAPServer);
		req.setRequestHeader(&quot;SOAPAction&quot;, soapReq.Action);
	 }
});
</pre>
</pre>
<p>You can download the source code <a href="http://www.nvise.com/files/jQueryWSCall.rar">here</a></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.nvise.com/?feed=rss2&amp;p=15</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Programming Challenge: 2D Geometry</title>
		<link>http://blog.nvise.com/?p=12</link>
		<comments>http://blog.nvise.com/?p=12#comments</comments>
		<pubDate>Wed, 06 Aug 2008 21:46:54 +0000</pubDate>
		<dc:creator>Catalin</dc:creator>
				<category><![CDATA[.NET]]></category>

		<guid isPermaLink="false">http://blog.nvise.com/2008/08/programming-challenge-2d-geometry/</guid>
		<description><![CDATA[This blog publishes each week a programming challenge they think would appropriate for a programming job interview. In my opinion most of them aren&#8217;t very well suited for a job interview but this isn&#8217;t the subject of my post. The &#8230; <a href="http://blog.nvise.com/?p=12">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.dev102.com/2008/08/05/a-programming-job-interview-challenge-14-2d-geometry/" target="_blank">This</a> blog publishes each week a programming challenge they think would appropriate for a programming job interview. In my opinion most of them aren&#8217;t very well suited for a job interview but this isn&#8217;t the subject of my post. The aim of my post is to solve this week challenge.</p>
<p>This week question is:</p>
<blockquote><p>Your input:</p>
<ol>
<li>List of points in a 2D space. If you draw lines between one point to the next one, a closed polygon is created (can be either concave or convex).</li>
<li>A single point in a 2D space.</li>
</ol>
<p>You need to determine whether the given point is inside or outside the given polygon.</p>
<p>[...]</p>
<p>Provide the most efficient and simple algorithm.</p></blockquote>
<h3>The &#8220;simplest&#8221; solution</h3>
<p>The simplest algorithm I have in mind would be:</p>
<ul>
<li>draw red point</li>
<li>draw blue filled polygon</li>
<li>check point color (red means outside, blue means inside)</li>
</ul>
<p>Problem solved is a few lines of code <img src='http://blog.nvise.com/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /> . But what happens if coordinates aren&#8217;t integers or are really big (&gt; 10000) ? This algorithm is not very accurate, we&#8217;d run out of memory and filling up a big polygon would take lots of time.</p>
<h3>The geometrical solution</h3>
<p>Lets draw a ray starting at our point in a random direction to the infinity. This ray intersects our polygon zero or more times.</p>
<p><a href="http://blog.nvise.com/wp-content/uploads/2008/08/shape-ray.png"></a></p>
<p style="text-align: center"><img class="aligncenter" style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" src="http://blog.nvise.com/wp-content/uploads/2008/08/shape-ray-thumb.png" border="0" alt="shape_ray" width="449" height="329" /></p>
<p>Zero times would mean the point is outside the polygon. One time means the point is inside, two times outside and so on&#8230; <strong>Even number of intersections means the point is outside, odd number means the point is inside.</strong> How do I prove that ?</p>
<p>I don&#8217;t have a mathematical proof, rather an intuitive one&#8230; Lets choose an imaginary point on the ray at infinity. Could this point be inside the polygon ? No, it can&#8217;t: because the polygon is closed and finite a point at infinity can&#8217;t be inside it. Lets walk backwards from the point to infinity to our reference point. Each time the ray intersects the polygon we switch from inside to outside and vice versa. Even number of switches (intersections) -&gt; the point is outside; odd number of switches -&gt; the point is inside. The algorithm is pretty simple and is O(n) complexity:</p>
<ul>
<li>Get a ray originating with the input point</li>
<li>Transform the input polygon points into segments</li>
<li>For each segment check if it intersects the ray and count the number of intersections</li>
<li>If odd number of intersections the point is inside else it is outside</li>
</ul>
<p>How can we implement that ?! The mathematical representation of a ray is:</p>
<blockquote><p><em><strong>Ray(t) = Po + t*Pd</strong></em> with <em><strong>t&gt;=0</strong></em></p></blockquote>
<p>Where Po is the origin point and Pd is a point somewhere on the ray witch gives the ray direction.</p>
<p>The mathematical representation of a segment is:</p>
<blockquote><p><em><strong>Segment(u) = P1 + u * (P2-P1)</strong></em> with <em><strong>0&lt;=u&lt;=1</strong></em></p></blockquote>
<p>Where P1 and P2 are the head points of the segment. If we replace (P2-P1) by D (as in Delta) we get the same formula as the ray. Only the limits for the argument are different.</p>
<p>To find out if the ray intersects the segment we have to solve the equation</p>
<blockquote><p><em><strong>Ray(t) = <em><strong>Segment(u) </strong></em></strong></em></p></blockquote>
<p>and check if <em>t&gt;=0</em> and <em>0&lt;=u&lt;=1</em>. But I won&#8217;t steal you the pleasure of solving it <img src='http://blog.nvise.com/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /> </p>
<h3>Show me the code</h3>
<p>First let me warn you that for the sake of simplicity I eliminated input validation code: polygon should have at least three points, segment and ray validation (origin and direction points should be different).</p>
<p>The language used is C# 3.0.</p>
<p>Lets start with some simple geometric classes:</p>
<p>public class Point<br />
{<br />
public Point(float x, float y)<br />
{<br />
X = x;<br />
Y = y;<br />
}</p>
<p>public float X { get; private set; }<br />
public float Y { get; private set; }<br />
}</p>
<p>public class Ray<br />
{<br />
public Ray(Point p1, Point p2)<br />
{<br />
Origin = p1;<br />
Direction = p2;<br />
}</p>
<p>public Point Origin { get; private set; }<br />
public Point Direction { get; private set; }<br />
}</p>
<p>public class Segment<br />
{<br />
public Segment(Point p1, Point p2)<br />
{<br />
Origin = p1;<br />
Delta = new Point(p2.X &#8211; p1.X, p2.Y &#8211; p1.Y);<br />
}</p>
<p>public Point Origin { get; private set; }<br />
public Point Delta { get; private set; }<br />
}</p>
<p>Now the method witch finds out if a ray and an segment intersect:</p>
<p>///<br />
<summary>
/// Solves the equation Ray(t) = Segment(u) where<br />
/// Ray(t) = Po + t*Pd with t>=0<br />
/// Segment(u) = P1 + u * (P2-P1) with 0&#038;lt=u&#038;lt=1<br />
/// </summary>
<p>///
<param name="ray">the ray</param>
///
<param name="seg">the segment</param>
/// <returns>true if ray and segment intersect</returns><br />
private static bool Intersecting(Ray ray, Segment seg)<br />
{<br />
var a =<br />
seg.Delta.X * ray.Direction.Y -<br />
seg.Delta.Y * ray.Direction.X;</p>
<p>// if ray and segment are parallel they don&#8217;t intersect<br />
if (0 == a) return false;</p>
<p>var b =<br />
(ray.Origin.X &#8211; seg.Origin.X) * ray.Direction.Y -<br />
(ray.Origin.Y &#8211; seg.Origin.Y) * ray.Direction.X;</p>
<p>var u = b / a;</p>
<p>b =<br />
(ray.Origin.X &#8211; seg.Origin.X) * seg.Delta.Y -<br />
(ray.Origin.Y &#8211; seg.Origin.Y) * seg.Delta.X;</p>
<p>var t = b / a;</p>
<p>return 0 <= t &#038;&#038; 0 <= u &#038;&#038; 1 > u;<br />
}<br />
} </p>
<p>Did you notice that something changed ? The constraints on <strong><em>u</em></strong> changed from <em><strong>0&lt;=u&lt;=1 </strong>to<strong> </strong></em><em><strong>0&lt;=u&lt;1.</strong></em> What happens if the ray contains one of the polygon points ? The intersection would be counted twice ! Hence the change.</p>
<p>To define the polygon the input is a list of points but our algorithm needs segments so we transform the input:</p>
<p>///<br />
<summary>
/// Transforms a list of polygon points in a list of polygon segments<br />
/// </summary>
<p>///
<param name="polyPoints">list of polygon points</param>
/// <returns>list of polygon segments</returns><br />
private static IList<Segment> GetPolySegments(IList<Point> polyPoints)<br />
{<br />
IList<Segment> segments = new List<Segment>();</p>
<p>for (var i = 0; i < polyPoints.Count - 1; i++)<br />
{<br />
segments.Add(new Segment(polyPoints[i], polyPoints[i + 1]));<br />
}</p>
<p>segments.Add(new Segment(polyPoints[polyPoints.Count - 1], polyPoints[0]));</p>
<p>return segments;<br />
}</p>
<p>To define the ray we need an origin point (the input point) and a direction point. For fun I choosed the direction point to be the center of the polygon.</p>
<p>///<br />
<summary>
/// Calculates the center of a polygon. (the averege of coordinates)<br />
/// </summary>
<p>///
<param name="polyPoints">collection of polygon</param>
/// <returns>Center Point</returns><br />
private static Point GetPolyCenter(ICollection<Point> polyPoints)<br />
{<br />
return new Point(<br />
polyPoints.Sum(p => p.X) / polyPoints.Count,<br />
polyPoints.Sum(p => p.Y) / polyPoints.Count);<br />
}</p>
<p>Any random direction point would work as long as it is different form the input point.</p>
<p>And now the main algorithm:</p>
<p>///<br />
<summary>
/// Finds if a point is inside a closed polygon<br />
/// </summary>
<p>///
<param name="p">point</param>
///
<param name="polyPoints">list of points definig the polygon</param>
/// <returns>true if point p is inside the polygon</returns><br />
public static bool IsPointInsidePoly(Point p, IList<Point> polyPoints)<br />
{<br />
// define ray<br />
var rayToPolyCenter = new Ray(p, GetPolyCenter(polyPoints));</p>
<p>// count intersections<br />
var intersections =  GetPolySegments(polyPoints).Count(<br />
s => Intersecting(rayToPolyCenter, s));</p>
<p>// Odd number of intersections means inside<br />
return 1 == intersections % 2;<br />
}</p>
<p>So that&#8217;s it. There are some ways of improving the code (input validation, test it with very close points, etc.) but I&#8217;ll stop here.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.nvise.com/?feed=rss2&amp;p=12</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Hello world!</title>
		<link>http://blog.nvise.com/?p=1</link>
		<comments>http://blog.nvise.com/?p=1#comments</comments>
		<pubDate>Wed, 09 Jul 2008 20:11:27 +0000</pubDate>
		<dc:creator>Catalin</dc:creator>
				<category><![CDATA[Miscellaneous]]></category>

		<guid isPermaLink="false">http://blog.nvise.com/?p=1</guid>
		<description><![CDATA[It seems like everybody and his dog is blogging these days, could I be a cool kid like the others? (Now I realize I don&#8217;t see any smiley on technical blogs I&#8217;m reading even when they are joking, why is &#8230; <a href="http://blog.nvise.com/?p=1">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p><a href="http://blog.nvise.com/wp-content/uploads/2008/07/blogging_for_dummies.jpg"><img class="alignright size-full wp-image-4" style="float: right;" title="blogging_for_dummies" src="http://blog.nvise.com/wp-content/uploads/2008/07/blogging_for_dummies.jpg" alt="" width="96" height="120" border="0" /></a>It seems like everybody and his dog is blogging these days, could I be a cool kid like the others? (Now I realize I don&#8217;t see any smiley on technical blogs I&#8217;m reading even when they are joking, why is that?!)</p>
<p>This is going to be a technical/programming/geek blog; I&#8217;m going to write about .NET, software development, computer hardware, digital photography, computer games and other geeky stuff.</p>
<p>So, that&#8217;s it, my first post. Next step: update the &#8220;about&#8221; page.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.nvise.com/?feed=rss2&amp;p=1</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>
