Friday, 21 December 2007

.NET AJAX .axd give error regarding utcDate

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... :(

Tuesday, 18 December 2007

Deploying Silverlight Application - Why Blank?!

Yesterday we have deployed a Silverlight 1.0 application onto a Window Server 2003 machine. The deployment seems very easy (well you only need to create an application in IIS), however when we try to load the application, the screen was blank.

We need to add new MIME type for the application to recognize XAML:

Properties > HTTP Headers Tab


Clicks "MIME Types...", and click "New"
Add extension ".xaml" with type "application/xaml+xml"

Tuesday, 11 December 2007

2008 Summer Road Trip - Auckland

Date and time:
Monday, 4 February 2008 at 1:00 p.m.

Hosted by:
Jacqui Chow (ya apparently that's me!)

Location:
Auckland Institute of Technology, Ground Floor, Wright Stevenson House 585 Great South Road, Penrose, Auckland

Summer is here! And with it is coming new technology from Microsoft that will affect how we design and build infrastructure and applications.

Come and join Chris Auld and Jeremy Boyd along with local, Alex Henderson, as they set up a solution entirely on Windows Server 2008, SQL Server 2008 and host an application built in Visual Studio 2008 and .Net 3.5 over a two hour period.

The application show cases all the latest features of these products including Virtualization, IIS, Spatial data, web and HTTP programing, and much more to demonstrate how these products will affect technology professionals (both infrastructure and developers) in the next couple of years.

There will be some very cool spot prizes and give aways on the day, and by registering and turning up on the day you will go into the draw to win one of three Windows Home Servers (to be drawn at the end of the road trip on Feb 21).

To register for the road trip, click here, enter your details (plus any friends you want to invite) and click register.

Doors open at 1pm, presentation starts at 1:30pm and the presentation will be done by 3:30pm.

Come along and meet your peers and learn about the latest technology and maybe even win a (very cool) prize - for free!

Dont forget to register at http://www.dot.net.nz/Default.aspx?tabid=113!

See you there!

Thursday, 29 November 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).

Tuesday, 27 November 2007

Javascript Hashtable

I can't remember where did I find this so I cannot put the reference here.

function Hashtable(){
this.clear = hashtable_clear;
this.containsKey = hashtable_containsKey;
this.containsValue = hashtable_containsValue;
this.get = hashtable_get;
this.isEmpty = hashtable_isEmpty;
this.keys = hashtable_keys;
this.put = hashtable_put;
this.remove = hashtable_remove;
this.size = hashtable_size;
this.toString = hashtable_toString;
this.values = hashtable_values;
this.hashtable = new Array();
}
/*=======Private methods for internal use only========*/

function hashtable_clear(){
this.hashtable = new Array();
}

function hashtable_containsKey(key){
var exists = false;
for (var i in this.hashtable) {
if (i == key && this.hashtable[i] != null) {
exists = true;
break;
}
}
return exists;
}

function hashtable_containsValue(value){
var contains = false;
if (value != null) {
for (var i in this.hashtable) {
if (this.hashtable[i] == value) {
contains = true;
break;
}
}
}
return contains;
}

function hashtable_get(key){
return this.hashtable[key];
}

function hashtable_isEmpty(){
return (this.size == 0) ? true : false;
}

function hashtable_keys(){
var keys = new Array();
for (var i in this.hashtable) {
if (this.hashtable[i] != null)
keys.push(i);
}
return keys;
}

function hashtable_put(key, value){
if (key == null || value == null) {
throw 'NullPointerException {' + key + '},{' + value + '}';
}else{
this.hashtable[key] = value;
}
}

function hashtable_remove(key){
var rtn = this.hashtable[key];
this.hashtable[key] = null;
return rtn;
}

function hashtable_size(){
var size = 0;
for (var i in this.hashtable) {
if (this.hashtable[i] != null)
size ++;
}
return size;
}

function hashtable_toString(){
var result = '';
for (var i in this.hashtable)
{
if (this.hashtable[i] != null)
result += '{' + i + '},{' + this.hashtable[i] + '}\n';
}
return result;
}

function hashtable_values(){
var values = new Array();
for (var i in this.hashtable) {
if (this.hashtable[i] != null)
values.push(this.hashtable[i]);
}
return values;
}

Basic Silverlight 1.0 (javascript) - Load another XAML

I keep things simple in this blog, because when I search on web, I would like to find simple explanations and examples, not a sophisticated one. I can write a sophisticated one once I know the basic.

It is easy to load another xaml onto the existing one -  if you have not use 1.1 before 1.0. Since I have developed 1.1 first, I actually found it confusing in the first place, anyway.

Here is a simple Page.xaml, named "Page", have a canvas, and a TextBlock:

<Canvas
xmlns="http://schemas.microsoft.com/client/2007"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Width="970" Height="616"
Background="White"
x:Name="Page"
>
<TextBlock x:Name="RandomButton" Width="36.258" Height="14.1" TextWrapping="Wrap"
Canvas.Left="19.639" Canvas.Top="110.283">
<Run FontFamily="Arial" FontSize="12" FontWeight="Bold"
Foreground="#FFFFFFFF" Text="Random"/>
</TextBlock>
</Canvas>


In the javascript "code behind" I add an event listener to the RandomButton textblock. I want to load Random.xaml onto this page when I click on RandomButton.

if (!window.Trash)
window.Trash = {};

Trash.Page = function() {}

Trash.Page.prototype =
{
handleLoad: function(control, userContext, rootElement)
{
this.control = control;
this.root = control.content.findName("Page");
this.RandomButton = control.content.findName("HomeButton");
this.RandomButton.addEventListene("MouseLeftButtonUp",
this.Random_onMouseLeftButtonUp);
}
}


We are going to send request for the xaml, and add it to the page asynchronously after it is loaded.

Trash.Page.prototype.Random_onMouseLeftButtonUp = function(sender, e)
{
Control_Send(sender.getHost(), "Random.xaml");
}

function Control_Send(host, control_path)
{
var downloader = host.createObject("downloader");
downloader.addEventListener("completed", Control_DownloaderCompleted);
downloader.open("GET", control_path);
downloader.send();
}

function Control_DownloaderCompleted(sender, e)
{
var xamlItem = sender.getResponseText("");

var host = sender.getHost();
var page = host.content.findName("Page");
var control = host.content.createFromXaml(xamlItem, true);

page.children.Add(control);
}


That's it!

Thursday, 22 November 2007

Part IV project - Graphical display for Trees and Graphs for Bioinformatics Software

I found my year IV project final report online. I looked through it, and it's very funny. As usual, my project partner implemented the back end C++ logic - decoding a strange string into a tree, and I do the front end GUI.

The hardest part was drawing tree correctly on the screen. Branch lengths have to visually tell the distant between the nodes. It requires quite a bit of Maths to calculate the drawing branch length, and have to fit them all on the screen. It was also quite interesting implementing tree traversal, i.e. moving up (towards the root) and down (towards the bottom). 

Anyway, if anyone interested, here's the link:

http://www.ece.auckland.ac.nz/~PIVprojects/archive/reports2004/pdfs/ccho096.pdf

Friday, 2 November 2007

Silverlight (Orcas) - Mouse Events Not Working?!

I know this sounds stupid, but I was having a problem with mouse events.

So what happened was I have another control on top of the one that has mouse events. The control on top has a canvas as big as the one underneath, but a transparent background. Well, "transparent" <> "not exists", it's like a piece of glass on top. I forgot.

So if you find your mouse events not working, check if there is a piece of transparent control on top of it!

Ellerslie .NET User Group Facebook Group

I have created a group on facebook for our DNUG, join if you want to keep an eye on latest events and news!

http://www.facebook.com/group.php?gid=5912067218&ref=mf

Monday, 29 October 2007

.NET User Group 3 - Microsoft PerformancePoint Server 2007

Date: 08/11/2007
Gather at 5:45, starting at 6:00
Catering: Pizza & Drinks
Venue: Olympic Software, 10 Cawley Street, Ellerslie, Auckland

Presented by Adam Cogan (Chief Architect at SSW, MVP)

Microsoft Office PerformancePoint Server 2007 is an integrated performance management application designed to help improve operational and financial performance across all departments and all levels of your organization.

With Office PerformancePoint Server 2007, you can monitor progress, analyse what is driving variances, and plan your business from budgeting to creating management reports. You can have metrics, key performance indicators (KPIs), and reports delivered to every desktop through intuitive scorecards, dashboards, and the easy-to-use 2007 Microsoft Office system environment. A key component of the Microsoft Business Intelligence (BI) offering, Office PerformancePoint Server 2007 can help you understand how performance can align with personal and departmental.
http://www.ssw.com.au/ssw/Products/Training.aspx#MSPerformancePoint

Presented by Adam Cogan
Position: Chief Architect, Microsoft Regional Director
Qualifications: B Bus, JP, MCP, Microsoft MVP (Visual Studio Team System)
Adam Cogan is the Chief Architect at SSW, a Microsoft Certified Partner specializing in Office and .NET Solutions. At SSW, Adam has been developing custom solutions for businesses across a range of industries such as Government, banking, insurance and manufacturing since 1990 for clients such as Microsoft, Quicken, and the Fisheries Research and Development Corporation.

Adam was one of the lead developers behind Australia's first live .NET site - using a version that was pre Beta 1! One of his latest projects was the Smart Tag implementation for Quicken Australia. Adam was also responsible for developing Reporting Services and Exchange Server samples for Microsoft that turned into a hugely popular Exchange Reporting Tool. Adam develops in Microsoft technologies; his favorites being SQL Server 2005, Reporting Services, OLAP, Winforms and Webforms (using Visual Studio .NET 2005 with both VB.NET and C#), Access 2007, Outlook 2007/Exchange Server 2007.

http://www.ssw.com.au/ssw/Employees/EmployeesProfile.aspx?EmpID=AC

Thursday, 25 October 2007

Post-.NET User Group 2 - Policy Injection Application Block

Thanks for coming! This time we have about 25 people, it's around the number we've expected, without some people I've expected to come. I blame the rainy weather and bad traffic.

Mateus Velloso gave us an overview of the Enterprise Library in particular the Policy Injection Application Block. I had an overview from the code camp a month (or two?) ago but this time I get to know a bit more what PIAB can and cannot do.

It's not a my concern whether it is easy or hard to pick up. Personally I think nothing is really hard to learn. I am more concern what can be done and what's the limitation of these libraries, so in the future when i meet a problem i can identify the best practice for it.

Hmm hmm, but comparatively nice stuff up front seems more attractive to me. Andre is going back to Brazil for 7 weeks during Christmas time, so I will have to get speakers for January and February. I will see Nigel Parker's availability for those two months... he will be showing some pretty things up front, hehe...

Thursday, 18 October 2007

Blah 3 - I am not a geek

Yesterday Darryl said I am a geek (yes, a super geek said I am a geek, very unconvincing), I am not a geek.

Here are the premises of my argument:

P1 I can read and write Chinese.

P2 I read a lot of fiction books, in Chinese.

P3 My life blog has 14.7 times more posts than this blog.

P4 I am not that excited whenever Alex show me new C# features.

P5 I buy Marie Claire and Cosmopolitan often, and New Scientist. Never buy any software magazine.

P6 I love Final Fantasy. Can discuss every single one from FFVII to FFXII.

P7 I do Philosophy. Not master/PhD of Software Engineering, or Microsoft Certificate exams.

P8 I watch a lot of cartoons, and read heaps of anime.

P9 When I have free time, I would play FF, Civilization IV, Sims, etc. Not coding.

P10 I have Mr. and Mrs Potato Head on my desk in the office.

P11 I have Haro from Gundam Seed (a pink one) on my desk as well.

P12 In the old mIRC days, I did not write my own scripts.

P13 Never interested in hacking.

P14 I love All Blacks (yes, especially DC).

So in conclusion, I can't be called a geek. If you think this doesn't logically follow, yeah, it doesn't. However because I am not a geek, so I don't care whether it logically follows or not. :P

Tuesday, 16 October 2007

Firefox Add-ons: Firebug 1.0.5

Get FireBug

Firebug homepage

Today Jeff has shown me this tool, I hope I would have known about this earlier, then my development life would be easier.

 

Firebug integrates with Firefox to put a wealth of web development tools at your fingertips while you browse. You can edit, debug, and monitor CSS, HTML, and JavaScript live in any web page.

 

Just the way you like it

Firebug is always just a keystroke away, but it never gets in your way. You can open Firebug in a separate window, or as a bar at the bottom of your browser. Firebug also gives you fine-grained control over which websites you want to enable it for.

Learn more

 

Inspect and edit HTML

Firebug makes it simple to find HTML elements buried deep in the page. Once you've found what you're looking for, Firebug gives you a wealth of information, and lets you edit the HTML live.

Learn more

 

Tweak CSS to perfection

Firebug's CSS tabs tell you everything you need to know about the styles in your web pages, and if you don't like what it's telling you, you can make changes and see them take effect instantly.

Learn more

 

Visualize CSS metrics

When your CSS boxes aren't lining up correctly it can be difficult to understand why. Let Firebug be your eyes and it will measure and illustrate all the offsets, margins, borders, padding, and sizes for you.

Learn more

 

Monitor network activity

Your pages are taking a long time to load, but why? Did you go crazy and write too much JavaScript? Did you forget to compress your images? Are your ad partner's servers taking a siesta? Firebug breaks it all down for you file-by-file.

Learn more

 

Debug and profile JavaScript

Firebug includes a powerful JavaScript debugger that lets you pause execution at any time and have look at the state of the world. If your code is a little sluggish, use the JavaScript profiler to measure performance and find bottlenecks fast.

Learn more

 

Quickly find errors

When things go wrong, Firebug lets you know immediately and gives you detailed and useful information about errors in JavaScript, CSS, and XML.

Learn more

 

Explore the DOM

The Document Object Model is a great big hierarchy of objects and functions just waiting to be tickled by JavaScript. Firebug helps you find DOM objects quickly and then edit them on the fly.

Learn more

 

Execute JavaScript on the fly

The command line is one of the oldest tools in the programming toolbox. Firebug gives you a good ol' fashioned command line for JavaScript complete with very modern amenities.

Learn more

 

Logging for JavaScript

Having a fancy JavaScript debugger is great, but sometimes the fastest way to find bugs is just to dump as much information to the console as you can. Firebug gives you a set of powerful logging functions that help you get answers fast.

Learn more

Monday, 15 October 2007

.NET User Group 2 - Policy Injection Application Block

Alright, our second .NET User Group meeting is on next Wednesday, 24th Oct 2007!

This time our topic is Policy Injection Application Block.

Presented by Mateus Velloso (Principal Software Architect at Gen-i, MVP)

Ready to pimp your objects?

The Policy Injection Application Block simplifies the separation of business logic from cross cutting concerns (such as logging, validation, exception handling, and authorisation) by letting you define policies and the objects/methods they apply to in a declarative way.

Gather at 5:45, starting at 6:00

Catering: Pizza & Drinks
Door Charge: Free
Parking: Free, just park in Olympic Software’s car park.

Venue
Olympic Software
10 Cawley St
Ellerslie Auckland

Map of venue

If you know anyone who might be interested please tell them about it. Remember it’s an open event so everyone is welcome.

Thursday, 11 October 2007

Button trigger UpdatePanel fails in FireFox

Firefox drove me crazy! I have spend hours to work out why it does not work, and the reason is: it does not have an image url but have alt text (and my Button is an ImageButton).

To demonstrate this, here is an example:

<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<div id="Html" runat="server" Visible="true">
Please submit
</div>

<asp:ImageButton id="SubmitButton" ImageUrl="submit_btn.gif"
onclick="SubmitButton_Click" alt="Submit" runat="server"
OnClientClick="this.style.display='none';"></asp:ImageButton>
<asp:ImageButton id="AmendButton" onclick="AmendButton_Click" alt="Amend"
runat="server" OnClientClick="this.style.display='none';"></asp:ImageButton>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="AmendButton" EventName="Click" />
<asp:AsyncPostBackTrigger ControlID="SubmitButton" EventName="Click" />
</Triggers>
</asp:UpdatePanel>

And the code behind is very simple:

        protected void SubmitButton_Click(object sender, ImageClickEventArgs e)
{
Html.InnerHtml = "Please Amend";
}

protected void AmendButton_Click(object sender, ImageClickEventArgs e)
{
Html.InnerHtml = "Please Submit";
}

The page looks like this:


s


If you click the submit button, it becomes:


a


As expected. However if you click the alt text "Amend", it will refresh the whole page instead of updating just the update panel. Basically I mean it does not work. The only solution is, of coz, give it a valid image!!!


Wasted me several hours! Now I am going home, it's 7:00pm already!

Tuesday, 9 October 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.

Friday, 5 October 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. :)

Thursday, 4 October 2007

Expression around the Clock

I went to Expression around the Clock this morning with Warner and I am happy that finally I have a chance to meet Nas. The content of August de los Reyes's talk was a bit unexpected, but I am a philosophy student so of course I love it. Two  things really have caught my attention were Seadragon and Photosynth.  I have seen Seadragon before, but not Photosynth. It's very cool, so I tried out the Photosynth tech preview after I got back to the office.

Go to the Photosynth site and have a look. :)

Monday, 1 October 2007

Silverlight project

I am so excited because we have finally started our first small silverlight project. Unfortunately (or fortunately?!) I am not involved in any development. I am only overseeing the project (for my own interest sake), not even managing it. That's cool, more people (girls!) get a chance to expose to the technology. Warner's design for the website is excellent. I love it so much, really can't wait to see the final product.


Since I don't get a chance to do the development part but I am too keen, therefore I have created a super simple silverlight example today after I have setup the development environment for those girls. Well, I am not a designer and I can only draw stickman, so the example site only consists of a moving rectangle and a moving ellipse. Don't expect to much from me, haha.


Will show you all once it's done. :)

Wednesday, 26 September 2007

First post from Windows Live Writer!

Andre showed me this cute tool. I love it. I got a "Insert Code" plugin as well, now I can do this:

<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>

and this:

protected void Page_Load(object sender, EventArgs e)
{
if (!this.Page.IsPostBack)
{
this.DataBind();
}
}

The only thing I am quite annoyed is the white background. I have changed the style to yellow already but no idea why it's still white. If you still see my code has a white background, that means I haven't sort that out yet. Anyway, time to go home for dinner!


P.S. HA, it's yellow now. But I have to get the border!!!

Friday, 21 September 2007

First .NET AJAX page

This is not my first AJAX page, but it's the first one I do for this project. Before this one I haven't really use .NET AJAX much although I have looked into all features and understand most theories about it. So I know a bit more than nothing, but not too much.

I've decided to document this purely for myself because I always forget what I have done, what I have encountered and what I have resolved.

First of all I've made this project into an AJAX enabled application by putting these sections into the web.config file:

1. In configuration\configSections\
<sectionGroup name="system.web.extensions" type="System.Web.Configuration.SystemWebExtensionsSectionGroup, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35">
<sectionGroup name="scripting" type="System.Web.Configuration.ScriptingSectionGroup, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35">
<section name="scriptResourceHandler" type=
"System.Web.Configuration.ScriptingScriptResourceHandlerSection, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
requirePermission="false" allowDefinition="MachineToApplication"/>
<sectionGroup name="webServices" type=
"System.Web.Configuration.ScriptingWebServicesSectionGroup, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
>
<section name="jsonSerialization" type=
"System.Web.Configuration.ScriptingJsonSerializationSection, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
requirePermission="false" allowDefinition="Everywhere" />
<section name="profileService" type=
"System.Web.Configuration.ScriptingProfileServiceSection, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
requirePermission="false" allowDefinition="MachineToApplication" />
<section name="authenticationService" type=
"System.Web.Configuration.ScriptingAuthenticationServiceSection, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
requirePermission="false" allowDefinition="MachineToApplication" />
</sectionGroup>
</sectionGroup>
</sectionGroup>

2. In configuration\system.web\
<pages validateRequest="false">
<controls>
<add tagPrefix="asp" namespace="System.Web.UI" assembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
</controls>
</pages>

<compilation debug="true">
<assemblies>
<add assembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
</assemblies>
</compilation>

<httpModules>
<add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
</httpModules>

3. In configuration\system.web\httpHandlers
<remove verb="*" path="*.asmx"/>
<add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
<add verb="*" path="*_AppService.axd" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
<add verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" validate="false"/>

4. In configuration\
<system.web.extensions>
<scripting>
<webServices>
<!-- Uncomment this line to customize maxJsonLength and add a custom converter -->
<!--
<jsonSerialization maxJsonLength="500">
<converters>
<add name="ConvertMe" type="Acme.SubAcme.ConvertMeTypeConverter"/>
</converters>
</jsonSerialization>
-->
<!-- Uncomment this line to enable the authentication service. Include requireSSL="true" if appropriate. -->
<!--
<authenticationService enabled="true" requireSSL = "truefalse"/>
-->

<!-- Uncomment these lines to enable the profile service. To allow profile properties to be retrieved
and modified in ASP.NET AJAX applications, you need to add each property name to the readAccessProperties and
writeAccessProperties attributes. -->
<!--
<profileService enabled="true"
readAccessProperties="propertyname1,propertyname2"
writeAccessProperties="propertyname1,propertyname2" />
-->
</webServices>
<!--
<scriptResourceHandler enableCompression="true" enableCaching="true" />
-->
</scripting>

</system.web.extensions>
<system.webServer>
<validation validateIntegratedModeConfiguration="false"/>
<modules>
<add name="ScriptModule" preCondition="integratedMode" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
</modules>
<handlers>
<remove name="WebServiceHandlerFactory-Integrated" />
<add name="ScriptHandlerFactory" verb="*" path="*.asmx" preCondition="integratedMode"
type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
<add name="ScriptHandlerFactoryAppServices" verb="*" path="*_AppService.axd" preCondition="integratedMode"
type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
<add name="ScriptResource" preCondition="integratedMode" verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
</handlers>
</system.webServer>

Then I started to create my control. As everyone may already know, a ScriptManager is required.

<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>

Next I've added my UpdatePanel. My trigger is a drop down list. When I add the trigger in I thought it would automatically work, but it doesn't! I know this sounds stupid, but, anyway, I forgot to make the drop down list auto post back in the first place. So here is the piece of code I have:
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<div id="Div1" runat="server" />
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="RandomDropDownList" EventName="SelectedIndexChanged" />
</Triggers>
</asp:UpdatePanel>

(to be continue... because my days usually pass too quick, I don't have too much time to do development...)

Wednesday, 19 September 2007

Blah 2

We were having lunch in Nando to farewell Alex because Nando is his favourite restaurant.

Andre: I have made Jacqui the co-leader of the user group.
Alex: Oh, so when will you have your talk?
Jacq: When I have something to talk about.
Alex: I guess you already have a lot to talk about.
Jacq: Can I talk about Philosophy in the user group? Like human nature?
Alex: Yeah, I don't think anyone would come though.

Umm, for those who don't know, I am a part time student, doing a Graduated Diploma in Philosophy (University of Auckland). Unfortunately it probably doesn't give me any advantage in work. :D

Any idea for .NET User Group topics?

We are thinking of all possible topics for our .NET User Group. Of cause there are heaps of things we can do, however it's good to gather more idea from the community because real and practical needs can only be found out from people in the community. So if you have any idea, anything you would like us to talk about in the .NET User Group, leave a comment here to let me know. :)

Friday, 14 September 2007

No more "Click to activate and use this control"

Well, I kind of know this trick for ages (really long long time ago). Actually most of the big websites now have changed their code so the annoying "Click to activate and use this control" for objects like flash does not appear anymore. All you have to do, is to have a javascript funcition for creating the object in an external js file. Use the script in your html and call the function to write the object out, like what Sony, Samsung, etc does.

See also : No more "Click to activate and use this control" (2)

Or, like my wedding website (sorry for being budget not having my own domain but rely on blogspot), have external header and footer generation functions, but leave the middle part inside the html. I can't remember why did I do that, but I did.

Anyway a js file with a function like this and call the function in your html will do:

function CreateObject(){
document.write(' <OBJECT id="WeddingHP4.swf");
document.write(' codeBase="...');
document.write(' height="470" width="700" align="middle" classid="..." style="border:solid 2px #FFCECC"');
document.write(' VIEWASTEXT>');
document.write(' <PARAM NAME="Movie" VALUE="WeddingHP4.swf"');
document.write(' <PARAM NAME="Src" VALUE="WeddingHP4.swf">');
document.write(' <embed src="WeddingHP4.swf" quality="high" bgcolor="#ffffff" width="800" height="470" name="WeddingHP4.swf" align="middle" allowscriptaccess="sameDomain" type="application/x-shockwave-flash" pluginspage="..."> </embed>');
document.write(' </OBJECT>');
}

NAnt task example - XmlPokeExtendedTask

NAnt has a XmlPoke task, which is good, but unfortunately it does not create the node if it does not already exists. I have created my XmlPokeExtendedTask which would create xml node with and the spcified attribute for me.

For example
/configuration/appSettings/add[@key='Some.Setting']/@value,10
/configuration/appSettings/add[@key='Some.Setting2']/@value,Low

the ouput XML will contains the following:
<configuration>
<appsettings>
<add key="Some.Setting" value="10">
<add key="Some.Setting2" value="Low">
</appsettings>
</confugration>


Here is the assembly and an example. Simply putting the dll into the NAnt folder would work because NAnt automatically include assemblies that are named *Tasks.dll.

Wednesday, 12 September 2007

Blah 1

This has nothing to do with development.

I've been reading what I typed this afternoon and have found lots of typo and even sentences that don't make any sense. I was working at the same time I type that up. Have to admit that my multi-tasking skill is not good enough. Anyway, forgive me if you see any typo or spelling or grammatical mistake.

I hope I won't do that in my philosophy essays and exams.

C# 3.0 Basic - Lambda expressions

"A lambda expression is written as a parameter list, followed by the => token, followed by an expression or a statement block."

This is not the first time I see Lambda expressions. I love Lambda expressions in the first sight because the look pretty much like logic to me. Alex talked about this in his LINQ example. I will talk about it in LINQ later, but here are some examples I copy from c#3.0 specification document:

x => x + 1 // Implicitly typed, expression body
x => { return x + 1; } // Implicitly typed, statement body
(int x) => x + 1 // Explicitly typed, expression body
(int x) => { return x + 1; } // Explicitly typed, statement body
(x, y) => x * y // Multiple parameters
() => Console.WriteLine() // No parameters

Honestly I am not confident in typing an example for this in notepad and assume it will work. So i will go home and install VS 2008 beta on my machine first, have a try and create an example. Then I can create example for LINQ as well.:)

C# 3.0 Basic - Anonymous type

"An anonymous object initializer declares an anonymous type and returns an instance of that type."

Cool, another thing in .NET allows anonymous. It's quite handy to have anonymous method and type support.
var meeting = new {Time = 3.Hours().Ago(), Location = "Ellerslie"};

The variable meeting has a type, which, technically not really anonymous. An ugly system name is assigned to this type and which I honestly cannot remember.

If there is another anonymous type with the same initializer, C# 3.0 is smart enough to recognise them as the same type. e.g.
var meeting2 = new {Time = 3.Hours().FromNow(), Location = "CBD"};
meeting = meeting2;

I think this is really cool although I don't have in mind where can I use this yet, haha.

C# 3.0 Basic - Extension methods

Alex's example on extension method as a whole was really cool. I will ask him for it later. Meanwhile I will write a super simplified one to show that I understand what he was saying.:D

First here are two extension methods. The first one, Hours, extends int type; and the second one, FromNow, extends TimeSpan type.
public static TimeSpan Hours(this int i)
{
return new TimeSpan(0, i, 0, 0);
}

public static DateTime FromNow(this TimeSpan t)
{
return DateTime.Now.Add(t);
}

So I can write something like this:
DateTime ThreeHoursFromNow = 3.Hours().FromNow();

Probably my example cannot illustrate the power of extension methods, but well, you get the idea. :)

C# 3.0 Basic - Implicit typing

var i = 5;
var s = "Hello";
var d = 1.0;
var numbers = new int[] {1, 2, 3};
var persons= new Dictionary<int,Order>();

Basically the above are equivalent to
int i = 5;
string s = "Hello";
double d = 1.0;
int[] numbers = new int[] {1, 2, 3};
Dictionary<int,Order> persons= new Dictionary<int,Order>();

"In an implicitly typed local variable declaration, the type of the local variable being declared is inferred from the expression used to initialize the variable". IntelliSense recognises the type of the variable and support normal auto completion of that type for the variable.

Note that the following are example of incorrect declarations:
var x; // Error, no initializer to infer type from
var y = {1, 2, 3}; // Error, collection initializer not permitted
var z = null; // Error, null type not permitted

C# 3.0 Basic - Collection initializer

According to C# 3.0 specification, "a collection initializer consists of a sequence of element initializers, enclosed by { and } tokens and separated by commas".

So
Person p1 = new Person("Jacqualine", "Chow");
Person p2 = new Person("Andre", "Meurer");
Person p3 = new Person("Alex", "James");

List<Person> pList = new List<Person>();
pList.Add(p1);
pList.Add(p2);
pList.Add(p3);

can be written as

List<Person> pList = new List<Person>{ p1, p2, p3};

and in combining the power of object initializer, this will become

List<Person> pList = new List<Person>
{
new Person { Firstname = "Jacqualine", Lastname = "Chow" },
new Person { Firstname = "Andre", Lastname = "Meurer" },
new Person { Firstname = "Alex", Lastname = "James" }
};

C# 3.0 Basic - Object initializer

This is the first thing I remember from Alex's talk.

According to C# 3.0 specification, "an object initializer consists of a sequence of member initializers, enclosed by { and } tokens and separated by commas".

So
Person p = new Person();
p.Firstname = "Jacqualine";
p.Lastname = "Chow";

and

public Person(string firstname, string lastname)
{
this.Firstname = firstname;
this.Lastname = lastname;
}

Person p = new Person("Jacqualine", "Chow");


can be written as
Person p = new Person { Firstname = "Jacqualine", Lastname = "Chow" };

In this case we do not have to create a lot of constructors for different combination of initial parameters.

Post-.NET User Group 1 - VS 2008 and C#3.0

Thanks for everyone that have attended the .NET User Group meeting held in Olympic Software last night. I was very happy because there are more people than we expected and there are pizzas, haha.

I will try to get Darryl Burling's presentation slide up here later when he has finished his VS 2008 .NET User Group tour these two months. It is not very nice if I ask him for it now and people can get it before his talks. :P

I will post the C# 3.0 cool features and tricks that Alex James showed us here in the upcoming posts. Since Alex didn't have any slides and he is too busy now (see Off to sunny Seattle), I have to dig out what he has said from my little brain. Anyway, will post all (alright, most) of them here soon.

I am very happy to see VS2008 having so many improvements on the design side of things. There are not many developers care about whether things look good or not and about usability issues, but most of them do care about functionality. One of the obvious reason is currently it is very hard to make things look nice. I am very interested to learn about XAML (Silverlight and WPF specifically). It will be good if we can hold XAML based user group here in Auckland as well like Nas Khan is doing in Wellington. The user group in Wellington is called ZamDes (yet for me to find out why).

Andre said I should start blogging about Silverlight. I wish I can really do that soon. :)

Tuesday, 4 September 2007

NAnt task example - Update database

NAnt is a .Net build tool (which obviously similar to Ant). We have been using NAnt to create and deploy patches and I have been creating my own NAnt tasks to do the job. Recently I am thinking of enhancing the script that I have written couple of years ago.

Each user defined task has a TaskName, maybe some TaskAttribute too, and override ExecuteTask method. Let me just post an example of user defined task here.

Nant.UpdateDatabase.build.txt (save this as .build)

.NET User Group 1 - VS 2008 and C#3.0

Olympic is hosting the first Ellerslie .NET User Group meeting next Tuesday. This is a public event free of charge for all developers keen on learning new tips & tricks, and keeping up to date with what’s coming up. We will host regular meetings at the Olympic Auckland office every 4-6 weeks.

Our opening night will be a double session by Darryl Burling of Microsoft (on Visual Studio 2008) and Alex James (on C# 3.0)

If you know anyone who might be interested please tell them about it. Remember it’s an open event so everyone is welcome.

Here are the details:

A lap around Visual Studio 2008 & A lap around C# 3.0
Auckland 11/09/2007
Gather at 5:45, starting at 6:00

A lap around Visual Studio 2008
Presented by Darryl Burling
Explore all the new Visual Studio 2008 features, from language enhancements; improved designers; Web and smart-client development tools; to Visual Studio Team System, a suite of software lifecycle management tools poised to transform how you deliver software for Windows Vista, the 2007 Microsoft Office system, and the Web.

A lap around C# 3.0
Presented by Alex James
Explore quickly the new features of C# 3.0, including things like LINQ, Lambda Expressions, Anonymous Types etc.

Catering: Pizza & Drinks
Door Charge: Free
Parking: Free, just park in Olympic Software’s car park.

Venue
Olympic Software
10 Cawley St
Ellerslie Auckland

Map of venue

Monday, 27 August 2007

Checking object existence in SQL 2000 and SQL 2005

I have SQL 2005 on my machine but sometimes I am connecting to SQL 2000 database. If you generate drop object script from SQL 2005 Server Management Studio, it cannot be applied to the SQL 2000 database because they do not have the same system tables and views. For example dropping a stored procedure:

SQL 2005 syntax:

IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[StoredProc_Name]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[StoredProc_Name]


However SQL 2000 database does not have sys.objects table. In SQL 2000 syntax:
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[StoredProc_Name]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[StoredProc_Name]


This will work in SQL 2005 database as well because SQL 2005 database has a view named sysobjects (for backward compatibility?!).

To check function existence in SQL 2000 syntax:
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Function_Name]') AND xtype in (N'FN', N'IF', N'TF'))
DROP FUNCTION [dbo].[Function_Name]


To check table existence in SQL 2000 syntax:
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Table_Name]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
DROP TABLE [dbo].[TableName]

Thursday, 23 August 2007

Absolute positioned div and dropdown box

An old bug has been fixed in IE 7. It's always working as expected in FireFox but as I can remember it wasn't drawing it out nicely (it is now, in 2.0.0.6).

See the code below:

<div id="DivA" style="position:absolute;
width:200px; height:200px; background-color:Green; display:block; z-index:100;">
I am a div</div>

<select name="DropDownList1" id="DropDownList1">
<option value="Item1">Item1</option>

<option value="Item2">Item2</option>

<option value="Item3">Item3</option>

<option value="Item4">Item4</option>
</select>


In IE 6 showing a div in absolute position on top of / overlapping a select (drop down box) would always fail. The select box will ALWAYS be on top of everything except one - the iFrame. Therefore we need an iframe with exactly the same size draw beneath the div in order to hide the select box completely. In IE7 this trick is no longer required. :)

T-SQL Cursor syntax

I've been asked a few times about the cursor syntax (and actually myself have been forgetting too). I know the SQL books online has syntax for everything, but apparently it is a bit hard to read some times. Anyway, post this here so it's handy for myself and the others. :)

DECLARE some_cur CURSOR FOR
SELECT Column1, Column2, Column3 FROM TableName

OPEN some_cur

DECLARE @col1 INT, @col2 NVARCHAR(50), @col3 BIT

FETCH NEXT FROM some_cur INTO @col1, @col2, @col3

WHILE (@@fetch_status <> -1)
BEGIN

-- Do whatever you want

FETCH NEXT FROM some_cur INTO @col1, @col2, @col3

END

CLOSE some_cur
DEALLOCATE some_cur