Archive for the ‘Tips & Tricks’ Category

SQL Server Compact not for ASP.Net   1 comment

“SQL Server Compact is not intended for ASP.NET development.”

Right…So you have this cool thing that allows you to have a SQL database in a hosting that only provides MySQL databases and such but you can’t use it. You got to be kidding me.

But, if really, really, really want it, there you go:

AppDomain.CurrentDomain.SetData("SQLServerCompactEditionUnderWebHosting", true);

Just put before the call to the database is made (Global.asax, etc.).

Posted 2010/11/17 by Bigsby in Tips & Tricks

Tagged with , ,

Chrome, AJAX & XMLHttpRequest.status 0   Leave a comment

I lost two hours of my precious time because of this issue.

 

What?

I’m making the back bones of a website for a friend and, after cleaning all the designer like HTML and making sure it was lookalike in IE, Chrome, FireFox, Opera and Safari. Being such a simple subject, I’m using a simple ASP.Net Web Form (.Net 3.0) where I’m making my own JSON serialization for the response. Then, I started on implementing AJAX stuff with jQuery and that’s when things started to, amazingly get messy.

 

The code

My server side looked something like this:

protected void Page_Load(object sender, EventArgs e)
{
    Response.Clear();
    var page = Pages.Find(p => p.Name == Request.QueryString["Name"]);
    if (null != page) Response.Write(page.ToJSON());
    Response.Flush();
    Response.Close();
}

Pretty simple, hey? We’ll see about that.

My jQuery AJAX request looked something like this:

$.ajax({
    url: "Server.aspx?Name=Home",
    success: PopulatePage,
    dataType: "json"
});

 

 

The occurrence

The DOM objects from the JSON sent by my server were OK in all browsers except for Chrome. Wow!

As I started to put alerts everywhere I first realized that Chrome was the only browser where XMLHtttRequest had no headers. Was this a cause or a symptom?
Furthermore, there was no responseText in XMLHttpRequest. Someone must be joking with me…

 

The solution

After some googling hitting everywhere but my issue, I managed to find the answer to my troubles in jQuery forums (link) where someone with a nickname that suggests he knows about Hi-Fi, kindly shared a link to where the cause and solution where explained.

It turns out that my good intensions to tell ASP handlers that I was done and that the response could be sent to the client by calling Response.Close() was causing, in Chrome, for the peer connection to be closed before any data was sent.

After a lot of code messing and try and miss and buffing, I just returned to my original code and commented the last line of Page_Load and the world was again turning.

 

PS

I had another minor issue, in this case, with Opera. I had a couple of span HTML elements where I set innerHTML with jQuery.html() method. Every other browser showed everything right except, as just stated, Opera. The cause was that these two span’s were self-closing elements, like so:

<span id="idOfASpan"/>

 

…and it looks like Opera doesn’t like it so I had to change it to:

<span id="idOfASpan"></span>

 

Now I really had a website W3C compliant in theory and visually as well.

Posted 2010/10/31 by Bigsby in Tips & Tricks

Tagged with , , , , , , ,

Calling methods with a time out   Leave a comment

I was implementing a communication with a device via RS232 and came across the possibility of not having any response. Just like every time one depends on someone else’s volatile response.

I looked around a bit and all I found was a little confusing and, as usual, very little generic. I put my hands on it and came up with this implementation that I now use, maybe, a little bit too much.

The Delegates

If you’re in .Net 2.0 Func<T> and Action are not yet implement. Actually, they’re just  particular delegates that are so often used that were considered for .Net 3.0 (and posterior) inclusion. Their implementation is as follows:

public delegate T Func<T>();
public delegate void Action();

 

Implemention

The implementation couldn’t be simpler and is based on the ability to call delegates asynchronously with BeginInvoke and WaitHandle.WaitOne method provided by IAsyncResult.AsyncWaitHandle. Note that BeginInvoke and EndInvoke are provided by the C# compiler in it’s delegate keyword. If we at the IL generated by the compiler for Func<T> it becomes clear, even if you don’t know anything about IL:

.class auto ansi sealed nested public Func<T>
    extends [mscorlib]System.MulticastDelegate
{
    .method public hidebysig specialname rtspecialname instance void .ctor(object 'object', native int 'method') runtime managed
    {
    }

    .method public hidebysig newslot virtual instance class [mscorlib]System.IAsyncResult BeginInvoke(class [mscorlib]System.AsyncCallback callback, object 'object') runtime managed
    {
    }

    .method public hidebysig newslot virtual instance !T EndInvoke(class [mscorlib]System.IAsyncResult result) runtime managed
    {
    }

    .method public hidebysig newslot virtual instance !T Invoke() runtime managed
    {
    }

}

If you’re wondering about System.MulticastDelegate

So the implementation goes like so for methods with a return object:

static T RunMethodWithTimeOut<T>(int millisecondsToWait, T timeoutResult, Func<T> method)
{
    var asyncResult = method.BeginInvoke(null, null);
    if (!asyncResult.AsyncWaitHandle.WaitOne(millisecondsToWait))
        return timeoutResult;
    return method.EndInvoke(asyncResult);
}

 

And with void return, a boolean is returned indicating if the method ended which might be handy:

static bool RunMethodWithTimeOut(int millisecondsToWait, Action method)
{
    var asyncResult = method.BeginInvoke(null, null);
    if (!asyncResult.AsyncWaitHandle.WaitOne(millisecondsToWait))
        return false;
    return true;
}

 

Testing

For testing I implemented these two methods that use both implementations of RunMethodWithTimeout:

static string TestStringTimeout(int timeoutSeconds, int methodSeconds, 
							string timeoutResult, string methodResult)
{
    return RunMethodWithTimeOut<string>(timeoutSeconds * 1000, timeoutResult,
			() => { Thread.Sleep(methodSeconds * 1000); return methodResult; });
}

static bool TestVoidMethod(int timeoutSeconds, int methodSeconds)
{
    return RunMethodWithTimeOut(timeoutSeconds * 1000, 
			() => Thread.Sleep(methodSeconds * 1000));
}

 

And run them in a console application testing all who-arrives-first scenarios:

static void Main(string[] args)
{
    Console.WriteLine(TestStringTimeout(1, 2, "Timed out!", "++Success"));
    Console.WriteLine(TestStringTimeout(2, 1, "Timed out!", "++Success"));
    Console.WriteLine(TestStringTimeout(1, 1, "Timed out!", "++Success"));
    Console.WriteLine();
    Console.WriteLine(TestVoidMethod(1, 2) ? "++Success" : "Timed out!");
    Console.WriteLine(TestVoidMethod(2, 1) ? "++Success" : "Timed out!");
    Console.WriteLine(TestVoidMethod(1, 1) ? "++Success" : "Timed out!");
    Console.ReadLine();
}

 

That’s wrap.

 

Heads up! Update

I was happily using this method when I started to run into some troubles. Now, it is quite obvious but I missed this very important issue: the method whose result is dismissed because it timed out has to be stopped.

In these cases, an overload providing and end method is most useful. Something like so:

static T RunMethodWithTimeOut<T>(int millisecondsToWait, T timeoutResult, Func<T> method, Action end)
{
    var asyncResult = method.BeginInvoke(null, null);
    if (!asyncResult.AsyncWaitHandle.WaitOne(millisecondsToWait))
    {
        end();
        return timeoutResult;
    }
    end();
    return method.EndInvoke(asyncResult);
}

 

And invoking would look something like this:

var isTimedOut = false;
var result = RunMethodWithTimeOut<string>(1000, "TimedOut",
    () =>
    {
        string successResult;
        do successResult = DoSomeProcessingThatMightNeverBeGood();
        while (null != successResult && !isTimedOut);
        return successResult;
    },
    () => { isTimedOut = true; });