Gypsy女郎的大秘密











Both WebResource.axd and ScriptResource.axd give an error at System.Web.HttpCachePolicy.UtcSetLastModified(DateTime utcDate) method, as shown below:

[ArgumentOutOfRangeException: Specified argument was out of the range of valid values.

Parameter name: utcDate]

System.Web.HttpCachePolicy.UtcSetLastModified(DateTime utcDate) +3258643
System.Web.HttpCachePolicy.SetLastModified(DateTime date) +47
System.Web.Handlers.ScriptResourceHandler.PrepareResponseCache(HttpResponse response, Assembly assembly) +194
System.Web.Handlers.ScriptResourceHandler.ProcessRequest(HttpContext context) +1154
System.Web.Handlers.ScriptResourceHandler.System.Web.IHttpHandler.ProcessRequest(HttpContext context) +4
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +154
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +64

First, look for the simple. If it’s your machine’s date time is in the past (or the future), then it is easy to fix. Just change your system clock.

In our case, it is not that straight forward. We have moved the time forward for a while, and ASP .NET 2.0 SP1 was installed while the time is in the future. So basically the assemblies and GAC modified date time is in the future. AJAX does not like it. I guess it is a bug.

We wanted to uninstall and reinstall SP1, but windows does not allow us to remove it. So we click “change” instead of “remove” in Add/Remove programs. Not sure what did windows do, but magically it works. It probably update all the installed dlls, so the modified date times are corrected.

Otherwise, we may have to “touch” all the files… :(



{十一月 29, 2007}   .NET AJAX fail in FireFox

In short, if the following line exists in your web.config, REMOVE IT!!!

<xhtmlConformance mode="Legacy" />

It is in confiugration\system.web.

By default when you convert a VS2003 web project to VS3005, the legacy switch is added to your web.config automatically. I have found some background information about this magical line (click here).



{十月 8, 2007}   First Chance Exception

Andre and Jeff came up with these terms this morning and honestly I have no idea what they mean. The Internet always always have an answer. I found an explanation from David Kline’s blog under the topic What is a First Chance Exception?.  The following is quoted from his blog:

What is a First Chance Exception?

Have you ever been debugging an application and seen a message, in the output window, about a “First chance” exception?
Ever wondered:

  • What is a first chance exception?
  • Does a first chance exception mean there is a problem in my code?

What is a first chance exception?
When an application is being debugged, the debugger gets notified whenever an exception is encountered  At this point, the application is suspended and the debugger decides how to handle the exception. The first pass through this mechanism is called a “first chance” exception. Depending on the debugger’s configuration, it will either resume the application and pass the exception on or it will leave the application suspended and enter debug mode. If the application handles the exception, it continues to run normally.

In Visual Studio, you may see a message in the output window that looks like this:

A first chance exception of type 'System.ApplicationException' occurred in myapp.exe

In Visual Studio 2005 Beta2, you will see this message anytime a first chance exception is encountered in your application’s code.  If you are using Visual Studio .NET 2003, this message is shown if you have configured the debugger to stop when the specific exception type is thrown.

If the application does not handle the exception, the debugger is re-notified. This is known as a “second chance” exception. The debugger again suspends the application and determines how to handle this exception. Typically, debuggers are configured to stop on second chance (unhandled) exceptions and debug mode is entered, allowing you to debug.

Does a first chance exception mean there is a problem in my code?
First chance exception messages most often do not mean there is a problem in the code. For applications / components which handle exceptions gracefully, first chance exception messages let the developer know that an exceptional situation was encountered and was handled.

For code without exception handling, the debugger will receive a second chance exception notification and will stop with a unhandled exception.



{十月 5, 2007}   C# yield return/break

yield is cool (you may already notice that I basically think everything’s cool), the main reason is that it reminds me about Mozart Oz (which has pure logic form of programming style). There is no relationship between them, but one just made me remind the other. It’s interesting to see how human’s brain categorize stuff. Anyway.

yield is used to provide enumeration over objects or to signal the end of iteration. Here is a basic non-generic example from MSDN, which basically return a list of numbers from n^1 to n^m:

public static IEnumerable Power(int n, int m)
{
int counter = 0;
int result = 1;
while (counter++ < m)
{
result = result * n;
yield return result;
}
}

static void Main()
{
// Display powers of 2 up to the exponent 8:
foreach (int i in Power(2, 8))
{
Console.Write("{0} ", i);
}
}

I have to say this is not interesting at all.

However when we combine the power of yield, generics and predicates, that’s where the fun is. I have copied a piece of code from Andre’s blog (look at the Extended Enumerable created here): 

public delegate R Func<T, R>(T t);
public static class SequenceOperators
{
public static IEnumerable<R> Select<T, R>
(IEnumerable<T> sequence, Func<T, R> mapping)
{
foreach (T t in sequence)
yield return mapping(t);
}



public static IEnumerable<T> Where<T>
(IEnumerable<T> sequence, Predicate<T> filter)
{
foreach (T t in sequence)
if (filter(t))
yield return t;
}
}

So, how exciting! The Select method takes an IEnumerable<T> and a function which has input param type T  (you know it’s not really “T”) and return type R (not Civic type R). By passing every t in T into the function, an enumeration of R objects were returned. The Where method takes an IEnumerable<T> and a predicate, and return enumeration of T objects of t in T that match the criteria.

It’s so flexible and powerful. :)



{八月 23, 2007}   Simple Hover Image/Button

Back in the old days, when I have completely no idea about HTML, I found that the HoverButton created by Microsoft FrontPage was very exciting. Now hover button is nothing fancy. It’s simply using onmouseover and onmouseout events.

<input type=”image” name=”HoverButton1″ id=“HoverButton1″ onmouseover=”this.src=’/grey_btn.gif’;” onmouseout=”this.src=’/green_btn.gif’;” src=”/green_btn.gif” />

Personally I prefer wrap these up in a web control (extending ImageButton).
Download ExtendedWebControls.dll & HoverButton.cs

So in development I can add it to my toolbox and use it as a normal web control.

<%@ Register Assembly=”ExtendedWebControls” Namespace=”ExtendedWebControls” TagPrefix=”cc1″ %>

<cc1:HoverButton ID=”HoverButton1″ runat=”server” BaseImgURL=”green_btn.gif” HoverImgURL=”grey_btn.gif” />



In .NET 2.0, behaviour of TextBox has slightly changed. For a TextBox with ReadOnly property set to true then the text is not be posted back to the server side. To set a TextBox read-only and keep the text on post back, use the following to set the readonly property on client site rendering:

TextBoxA.Attributes.Add(“readonly”, “readonly”)


Joseph and I have spent a long time figuring out why the session variable is refreshed after a page load. It was working well in .NET 1.0, but it fails when after we’ve converted the project to .NET 2.0. At first we have no idea it is a .NET 2.0 issue. Actually we didn’t even know it is a session variable issue (all we got was the mysterious object null reference exception). Anyway, after some difficult time we found out updating sub directories restart the web application. Unfortunately we have to keep this operation. After some googling we finally found a solution, and here it is.

If the sub directory is linked to another directory (as conjunction), then updating that sub directory would not trigger application restarts. For example my application is in C:\MyApp and the sub directory is C:\MyApp\SubDir. I should create another directory, for example C:\MyAppSubDirLink. Then download Window Server 2003 Resource Kit (here) and install it.

The resource kit has “linkd” command, which is all we need to get this working. Run the following in command prompt:

linkd C:\MyApp\SubDir C:\MyAppSubDirLink

That’s it! Now you can update C:\MyApp\SubDir without restarting the web application, and therefore session variable would be preserved!



Follow from the previous post, anonymous delegate can be used as predicate, which is a method that defines a set of criteria and determines whether the specified object meets those criteria. For example we have the following method:

public static void DoSomething<TObj>(IEnumerable<TObj>
objs, Action<TObj> action, Predicate<TObj> pred)
{

foreach (TObj obj in objs)
if(pred(obj))
action(obj);

}

which takes a predicate parameter and only perform the action if the predicates is true.

We can pass in anonymous delegate for the predicate:

List<string> listOfStrings = new List<string>();
listOfStrings.Add(“one”);
listOfStrings.Add(“two”);
listOfStrings.Add(“three”);

AnonymousDelegate.DoSomething<string>(listOfStrings,
delegate(string s) { Response.Write(s + “<br/>”);},
delegate(string s) { return !s.StartsWith(“o”); });

In this case on “two” and “three” would be written out.



{八月 15, 2007}   Simple anonymous delegate

Although anonymous method has been supported by Java for a long long time, finally it comes to .NET 2.0. Here is a simple generic method:

public static void DoSomething<TObj>(IEnumerable<TObj> objs, Action<TObj> action){

foreach (TObj obj in objs)
action(obj);

}

We can pass in anonymous delegate for the action. The action represents a method that performs an action on the specified object. For example:

List<string> listOfStrings = new List<string>();
listOfStrings.Add(“one”);
listOfStrings.Add(“two”);
listOfStrings.Add(“three”);

AnonymousDelegate.DoSomething<string>(listOfStrings,
delegate(string s) { Response.Write(s + “<br/>”); });

The output in this example would be:

one
two
three


{八月 15, 2007}   .Net 2.0 configuration reload

In .Net 1.0, if you have changed the app.config settings of a service, a restart is require to pick up the setting. Web applications automatically restart when web.config is modified.

.Net 2.0 allows you to refresh cached application configuration setting with the following method:

ConfigurationManager.RefreshSection(“appSettings”);

which refreshes the named section so the next time it is retrieved it will be re-read from disk.



et cetera
Follow

Get every new post delivered to your Inbox.