Restoring Intel Matrix RAID Configuration

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).

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 "Non-Raid Disk"

image Under the BIOS RAID menu (you can enter this menu by pressing <Ctrl+I> 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.

I tried many things like clearing CMOS, upgrading/downgrading BIOS version without any result, the disks kept showing as Non-Raid Disk.

So I installed Windows on a 3rd 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 (DERescue Data Recovery Master) 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.

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.

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 TestDisk under Windows to search for lost partitions then reinitialized the raid array and recreated the volumes with other settings.

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.

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.

But still Windows XP I had on another partition wasn’t bootable. I launched EasyBCD under Windows 7 and configured the right drive letter for XP and everything worked like before…

Conclusions: If you are going to use Matrix RAID always:

  1. Create RAID 1 volume first and RAID 0 second
  2. Make sure you save your raid settings (strip size and volumes sizes) somewhere where you can find them later if your Raid gets reinitialized.
Posted in Miscellaneous | Leave a comment

ASP.NET MVC returning 302 (Found) HTTP status code on unauthorized Ajax calls instead of 401(Unauthorized) like classic ASP.NET

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 by most Ajax frameworks) and redirect to login page. For example I use this code with jQuery:

WebMethod;

[WebMethod]
public static MyModel GetStuff()
{
    return new MyModel();
}

Javascript:

$.ajax({
    type: "POST",
    url: "Default.aspx/GetStuff",
    data: "{}",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function(msg) {
        // do stuff
    },
    error: function(xhr, status, ex) {
        if (xhr.status == 401) // unauthorized
        {
            window.location = "Login.aspx?ReturnUrl=" + window.location.pathname;
        }
    }
});

ASP.NET MVC

To do the same in ASP.NET MVC I have this method in my controller:

[Authorize]
public ActionResult GetStuff()
{
    return Json(new MyModel());
}

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). XMLHttpRequest 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.

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 :

protected void Application_EndRequest()
{
    if (Context.Response.StatusCode == 302 &&
        Context.Request.Headers["X-Requested-With"] == "XMLHttpRequest")
    {
        Context.Response.Clear();
        Context.Response.StatusCode = 401;
    }
}

And the client side code (using Ext JS this time) is:

Ext.Ajax.on('requestexception', function(conn, response, options) {
    if (response.status == 401) {
        window.location = '<%= Html.ActionUrl("Account", "LogOn") %>?ReturnUrl=' +
            window.location.pathname;
    }
});
Posted in AJAX, JavaScript | 8 Comments

Why aren’t my third party Ajax controls showing correctly in a ASP.NET MVC page ?

I was setting up a Ext JS grid and the rendering was wrong :

cssconflict

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:

image

Posted in ASP.NET MVC, CSS | Tagged | 1 Comment

Calling SharePoint web services using jQuery

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 didn’t want to add another javascript framework to my solution. Sure this is very easily portable to jQuery but I wanted a cleaner solution.

I found this: jQuery SOAP Client, a jQuery plug-in (it’s really an add-on because it doesn’t use jQuery extension mechanism) who was looking very promising. So I started to code…

I was going to call the UpdateListItems of the list web service (http://server/_vti_bin/lists.asmx). This method requires two arguments: listName and updates. Updates are the CAML commands describing the changes to the list and looks like this:

<Batch OnError="Continue">
    <Method ID="1" Cmd="Update">
       <Field Name="ID">1</Field>
       <Field Name="Title">updated title</Field>
    </Method>
</Batch>

I think that’s pretty readable: we want to change the Title of the element with the ID=1 to “updated title”.

Next: the javascript code using jQuery SOAP Client:

var wsMethod = "UpdateListItems";
var soapNs = "http://schemas.microsoft.com/sharepoint/soap/";

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

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

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

SOAPClient.SendRequest(sr, processResponse);

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’t do that if I where you.

Well, this didn’t work… I was getting some generic SharePoint error page, not very useful for debugging so I fired up Fiddler2.
I found out that the response was a HTTP error code 415 – 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.

And then I saw it: the Content-Type sent was application/x-www-form-urlencoded, text/xml; charset= "utf-8"; Thing is when you make an AJAX call with jQuery it automatically ads application/x-www-form-urlencoded 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:

$.ajax({
	 type: "POST",
	 url: SOAPClient.Proxy,
	 dataType: "xml",
	 processData: false,
	 data: content,
	 complete: getResponse,
	 beforeSend: function(req) {
		req.setRequestHeader("Method", "POST");
		req.setRequestHeader("Content-Length", SOAPClient.ContentLength);
		req.setRequestHeader("Content-Type", SOAPClient.ContentType + "; charset=\"" + SOAPClient.CharSet + "\"");
		req.setRequestHeader("SOAPServer", SOAPClient.SOAPServer);
		req.setRequestHeader("SOAPAction", soapReq.Action);
	 }
});

Fixing that was simple and… it worked!!!

$.ajax({
	 type: "POST",
	 url: SOAPClient.Proxy,
	 dataType: "xml",
	 processData: false,
	 data: content,
	 contentType : SOAPClient.ContentType + "; charset=\"" + SOAPClient.CharSet + "\"",
	 complete: getResponse,
	 beforeSend: function(req) {
		req.setRequestHeader("Method", "POST");
		req.setRequestHeader("Content-Length", SOAPClient.ContentLength);
		req.setRequestHeader("SOAPServer", SOAPClient.SOAPServer);
		req.setRequestHeader("SOAPAction", soapReq.Action);
	 }
});

You can download the source code here

Posted in AJAX, Sharepoint, jQuery | 34 Comments

Programming Challenge: 2D Geometry

This blog publishes each week a programming challenge they think would appropriate for a programming job interview. In my opinion most of them aren’t very well suited for a job interview but this isn’t the subject of my post. The aim of my post is to solve this week challenge.

This week question is:

Your input:

  1. 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).
  2. A single point in a 2D space.

You need to determine whether the given point is inside or outside the given polygon.

[...]

Provide the most efficient and simple algorithm.

The “simplest” solution

The simplest algorithm I have in mind would be:

  • draw red point
  • draw blue filled polygon
  • check point color (red means outside, blue means inside)

Problem solved is a few lines of code :D . But what happens if coordinates aren’t integers or are really big (> 10000) ? This algorithm is not very accurate, we’d run out of memory and filling up a big polygon would take lots of time.

The geometrical solution

Lets draw a ray starting at our point in a random direction to the infinity. This ray intersects our polygon zero or more times.

shape_ray

Zero times would mean the point is outside the polygon. One time means the point is inside, two times outside and so on… Even number of intersections means the point is outside, odd number means the point is inside. How do I prove that ?

I don’t have a mathematical proof, rather an intuitive one… Lets choose an imaginary point on the ray at infinity. Could this point be inside the polygon ? No, it can’t: because the polygon is closed and finite a point at infinity can’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) -> the point is outside; odd number of switches -> the point is inside. The algorithm is pretty simple and is O(n) complexity:

  • Get a ray originating with the input point
  • Transform the input polygon points into segments
  • For each segment check if it intersects the ray and count the number of intersections
  • If odd number of intersections the point is inside else it is outside

How can we implement that ?! The mathematical representation of a ray is:

Ray(t) = Po + t*Pd with t>=0

Where Po is the origin point and Pd is a point somewhere on the ray witch gives the ray direction.

The mathematical representation of a segment is:

Segment(u) = P1 + u * (P2-P1) with 0<=u<=1

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.

To find out if the ray intersects the segment we have to solve the equation

Ray(t) = Segment(u)

and check if t>=0 and 0<=u<=1. But I won’t steal you the pleasure of solving it :D

Show me the code

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).

The language used is C# 3.0.

Lets start with some simple geometric classes:

public class Point
{
public Point(float x, float y)
{
X = x;
Y = y;
}

public float X { get; private set; }
public float Y { get; private set; }
}

public class Ray
{
public Ray(Point p1, Point p2)
{
Origin = p1;
Direction = p2;
}

public Point Origin { get; private set; }
public Point Direction { get; private set; }
}

public class Segment
{
public Segment(Point p1, Point p2)
{
Origin = p1;
Delta = new Point(p2.X – p1.X, p2.Y – p1.Y);
}

public Point Origin { get; private set; }
public Point Delta { get; private set; }
}

Now the method witch finds out if a ray and an segment intersect:

///

/// Solves the equation Ray(t) = Segment(u) where
/// Ray(t) = Po + t*Pd with t>=0
/// Segment(u) = P1 + u * (P2-P1) with 0&lt=u&lt=1
///

/// the ray /// the segment /// true if ray and segment intersect
private static bool Intersecting(Ray ray, Segment seg)
{
var a =
seg.Delta.X * ray.Direction.Y -
seg.Delta.Y * ray.Direction.X;

// if ray and segment are parallel they don’t intersect
if (0 == a) return false;

var b =
(ray.Origin.X – seg.Origin.X) * ray.Direction.Y -
(ray.Origin.Y – seg.Origin.Y) * ray.Direction.X;

var u = b / a;

b =
(ray.Origin.X – seg.Origin.X) * seg.Delta.Y -
(ray.Origin.Y – seg.Origin.Y) * seg.Delta.X;

var t = b / a;

return 0 <= t && 0 <= u && 1 > u;
}

Did you notice that something changed ? The constraints on u changed from 0<=u<=1 to 0<=u<1. What happens if the ray contains one of the polygon points ? The intersection would be counted twice ! Hence the change.

To define the polygon the input is a list of points but our algorithm needs segments so we transform the input:

///

/// Transforms a list of polygon points in a list of polygon segments
///

/// list of polygon points /// list of polygon segments
private static IList GetPolySegments(IList polyPoints)
{
IList segments = new List();

for (var i = 0; i < polyPoints.Count - 1; i++)
{
segments.Add(new Segment(polyPoints[i], polyPoints[i + 1]));
}

segments.Add(new Segment(polyPoints[polyPoints.Count - 1], polyPoints[0]));

return segments;
}

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.

///

/// Calculates the center of a polygon. (the averege of coordinates)
///

/// collection of polygon /// Center Point
private static Point GetPolyCenter(ICollection polyPoints)
{
return new Point(
polyPoints.Sum(p => p.X) / polyPoints.Count,
polyPoints.Sum(p => p.Y) / polyPoints.Count);
}

Any random direction point would work as long as it is different form the input point.

And now the main algorithm:

///

/// Finds if a point is inside a closed polygon
///

/// point /// list of points definig the polygon /// true if point p is inside the polygon
public static bool IsPointInsidePoly(Point p, IList polyPoints)
{
// define ray
var rayToPolyCenter = new Ray(p, GetPolyCenter(polyPoints));

// count intersections
var intersections =  GetPolySegments(polyPoints).Count(
s => Intersecting(rayToPolyCenter, s));

// Odd number of intersections means inside
return 1 == intersections % 2;
}

So that’s it. There are some ways of improving the code (input validation, test it with very close points, etc.) but I’ll stop here.

Posted in .NET | Tagged | 6 Comments

Hello world!

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’t see any smiley on technical blogs I’m reading even when they are joking, why is that?!)

This is going to be a technical/programming/geek blog; I’m going to write about .NET, software development, computer hardware, digital photography, computer games and other geeky stuff.

So, that’s it, my first post. Next step: update the “about” page.

Posted in Miscellaneous | 7 Comments