Posts

Showing posts from 2007

Know thy exceptions, part 2

(At the time of writing this, I have three comments on the previous article. That is the background to this post) With a modified version of the below application, where I wrap the entire loop into a try-catch-statement instead of every iteration, and multiplying the number of iterations by 100 (for better statistical value), a debug-release generates the following: VB.NET - Debug Build With Try-Catch (100 iterations): 356433 ms Without Try-Catch (100 iterations): 175644 ms Diff: 180790 ms (49%) VB.NET - Debug Build - Single Iteration, 3rd execution With Try-Catch (100 iterations): 4703 ms Without Try-Catch (100 iterations): 1750 ms Diff: 2953 ms (37%) VB.NET - Release Build With Try-Catch (100 iterations): 248033 ms Without Try-Catch (100 iterations): 175517 ms Diff: 72516 ms (71%) VB.NET - Release Build - Single Iteration, 3rd execution With Try-Catch (100 iterations): 2516 ms Without Try-Catch (100 iterations): 1750 ms Diff: 766 ms (70%) C# - Debug Build - coming

Know thy exceptions

Image
A nother performance query: What is the cost of an arbitrary try-catch? To your right, you should see the results. Note that it took 2.5 times longer to execute the same code when it was inside a Try-Catch-block even though No exception was thrown . Don't get me wrong - the cost is often worth it. However, given the cost, it is wise to study exactly what Exceptions can be thrown in what scenarios, rather than just sprinkle your code with Try-Catches everywhere. The code that was executed, was: Private Function WithTryCatch () As Integer    Dim number As Integer    For index As Integer = 0 To CInt ( Integer . MaxValue / 2 )      Try        number += 1      Catch ex As Exception      End Try    Next    Return number End Function Private Function WithoutTryCatch () As Integer    Dim number As Integer    For index As Integer = 0 To CInt ( Integer . MaxValue / 2 )      number += 1    Next    Return number End Function

The ASP.NET Page Cycle

Being a consultant, I have worked with a lot of other consultants - professionals within their domain. It has struck me how few of the ASP.NET developers have a clear understanding of the ASP.NET page cycle, something I think is crucial to be able to write effective code. Given this experience, I have compiled a quick cheat-sheet that illustrates some basic, important, points. Please note, however, that what you find below is a non-exhaustive, simplified, list. The below page sequence is valid for instances of Control (Page inherits from Control): Page_PreInit Page_Init Page_PreLoad Page_Load EVENT HANDLERS , eg. Button1_Click If Page.Visible Then Page_PreRender This means, that Page_Load always runs. If you have code that decides whether or not a page/part of a page/control is shown that is dependant on another control, put that code into Page_PreRender. Example: Public Sub Page_Load( ... ) If Not IsPostBack Then LoadRegionalData() End If End Sub Public Sub Button1_

A scary realization, part 2

Image
OK, I just couldn't drop this subject until I'd done some more research. The image below, illustrates what I found: The application concatenates a bunch of strings, using different methods. Don't bother analyzing the actual individual values, but rather the relation between them: StringBuilder is fastest, most efficient without doubt. NO garbage collection was needed while processing the SAME strings, while all the other methods caused 2001 cleanups of the objects in Generation 0 (ms-help://MS.VSCC.v80/MS.MSDN.v80/MS.NETDEVFX.v20.en/cpref2/html/M_System_GC_CollectionCount_1_804c5d7d.htm) String.Concat uses slightly less memory than &-concatenation, but takes up about the same CPU time. Using the StringBuilder.AppendFormat method, uses almost double the CPU time in comparission to StringBuilder.Append, and even more than using &-concatenation. Furthermore, this was the only method that caused recycling of objects in Generation 1. Using String.Format is the slowe

A scary realization

I wanted to find out how much faster using String.Format was, in comparison to just concatenating strings, using "&" ("+" in C#). To do so, I iterated a String.Format -statement and a equivalent concatenation statement 10'000'000 times, calculated the median and created a report. I did this a few times and found the following: When combining three strings (e.g. "Hello " & strFirstName & "!") String.Format used 96% more memory, taking up 50% more processor time than an &-concatenation. String.Concat used 16% more memory, taking up virtually the same processor time (1 ms more) as an &-concatenation. When combining seven strings String.Format used 10% less memory, taking up 59% more processor time than an &-concatenation. String.Concat used 2% less memory, taking up 3% less processor time than an &-concatenation. Conclusion When doing small concatenation, use "&" or "+". When

Visual Studio Macros

Long time no see! I recently discovered the use of Macros in Visual Studio. Yes, I have known ABOUT them since the release of the IDE, but I haven't actually used them. Until recently. I must say that I find them extremely useful for helping with repetitive tasks. In earlier posts, you've read about various time saving techniques, including building your own form builder application. But instead of building dozens of specialized applications, you could instead create Macros IN the IDE that you are using and USING that IDE to perform your work. Saves some copying and pasting plus that you will not easily loose track of them since they are nicely listed in your Macro Explorer. But enough babble ... A quick introduction The Macro Explorer is accessible from the View - Other Windows - Macro Explorer (or by simply pressing ALT+F8). In the Explorer, you get a project listing which contains documents (modules) which, in turn, contains Visual Basic Sub procedures that are the actual

Am I a Popup?

One way of determining if the current page is a popup or not, is to check the Request.UrlReferrer. If the object is Nothing, it is safe to assume that the page is a popup. However, during subsequent page loads, the UrlReferrer changes - to the active page! One work around is displayed below: If Request.UrlReferrer Is Nothing OrElse Not String.IsNullOrEmpty(Request.Form("__IsPopup")) Then Master.isMenuVisible = False SearchMenu.Visible = False btnBack.OnClientClick = "window.close()" ClientScript.RegisterHiddenField("__IsPopup", True) End If By Registering a HiddenField with a clever name, you can have your page remember that it is a popup window and act accordingly.

Silverlight

Getting started With a seamless integration with the existing .NET framework, clean distinction between UI design and code, I strongly believe this will be a hit. I predict a lot of Silverlight applications or at least applets in a near future. Get on the train!

Modal JavaScript windows

There does not seem to be a unified way of creating a modal window. Web sources have told me that Mozilla and Opera supports a "modal=yes" attribute in it's window.open argument string, whereas Internet Explorer supports an showModal-method. Issues include, however, Mozilla's inability to keep the modal window on top, whereas Internet Explorer's approach disables access to global variables in the opening window, thus limiting the functionality. I have come up with an alternate approach: function OnBlurEventHandler() { window. focus(); if ( window .attachEvent) window .opener.attachEvent("onfocus", OnBlurEventHandler); else if ( window .addEventListener) window .opener.addEventListener("focus", OnBlurEventHandler, false ); } if ( window .attachEvent) window .opener.attachEvent("onfocus", OnBlurEventHandler); else if ( window .addEventListener) window .opener.addEventListener("focus", OnBlurEventHandler, fal

WebDings Web Graphics

Brief list of useful font glyphs that can be used in grid views and what-nots (Caveat: Doesn't work in FireFox 2 ): Glyph Text representation 3 (previous) 3 4 (play / next) 4 7 (rewind) 7 8 (fast forward) 8 9 (previous track / go to beginning) 9 : (next track / go to end) : A more compatible, but less functional (see post date) option is Unicode; see this page I ended up using the ASP.NET browser ID functionality, separating my GridView's Pager implementation for the two browsers like so: <ie:PagerSettings   Mode="NextPreviousFirstLast"   FirstPageText="9" LastPageText=":" NextPageText="4" PreviousPageText="3"   Position="Bottom" /> <ie:PagerStyle   ...   Font-Bold="True"   Font-Names="webdings"   Font-Size="Larger"   HorizontalAlign="Right" /> <mozilla:PagerSettings   Mode="NextPreviousFirstLast"   FirstPageText="&lArr;" Las

It's beautiful ...

http://www.castleproject.org/monorail/gettingstarted/index.html Wow.

Applied TDD in C#

I just found a nice article about applied TDD (Test Driven Development) in C# and thought I'd share. It's nicely condenced and to the point and will take you about 5-15 minutes to read, depending on whether or not you want to try out examples too. Improving Application Quality Using Test-Driven Development (TDD)

Sleeping vs. performance

This post is dedicated the human performance, rather than the performance of the code we write. The past two nights, I have gotten less sleep than I need. Unsurprisingly, the result is that I am slightly more tired than usual. I have noted, however, that I do boring, repetative tasks much quicker and with less errors today though, than when I am more rested. At the same time, I am noticing that I have to correct more typos in this post than I usually have... I am currently developing a ASP.NET Forms application, and am writing code for a form with a gazillion or so inputs. I'm progressing much faster today, than two days ago. I need to stop writing this post, though ... my brain is not able to produce anything more creative. My quick conclusion is: Less sleep = More efficient in executing repetative tasks Less sleep = Less efficient in executing creative/improvised tasks Very interesting. :-)

"Validation of viewstate MAC failed" and "Invalid Viewstate"

This solved it for me: <%@ Page ... EnableViewStateMac="False" ViewStateEncryptionMode="Never" CompilationMode="always" EnableEventValidation="false" %>

ASP.NET Atlas

Have you tried it yet? I haven't, but I will as soon as my computer at home is running again (hardware issues ... ). That was another thing that was successfully demonstrated at the MSDN Live event yesterday. With only two extra controls (ScriptManager (global) and UpdatePanel (that you put your controls in)), you could get classic ASP controls (such as the ASP:Calendar) to refresh using Ajax instead of PostBacks. Very nice indeed. I'm going to experiement some with that as soon as I have time, and I strongly suggest that you do the same. :-)

Nag: Use StringBuilder

Yesterday, I visited MSDN Live here in Stockholm. It was very interesting (as usual). One thing I noted, however, was the reminder not to use string concatenation everywhere, but to use StringBuilder for that task. In my professional life, I have seen a lot of developer disregarding this as well. What was demonstrated at the event, was something like this: string msg = String.Empty; for(int i = 0; i < 10000; i++) { msg += i.ToString(); } Console.WriteLine(msg); Memory Allocation: About 400 Mega byte Garbage Collector: Tired. With StringBuilder: StringBuilder msg = new StringBuilder(); for(int i = 0; i < 10000; i++) { msg.Append(i.ToString()); } Console.WriteLine(msg.ToString()); Memory Allocation: About 400 Kilobyte. Garbage Collector: Happy. 400 megs or 400 kbs ... you pick ;-) Also, check this out: Writing High-Performance Managed Applications : A Primer

Find and Replace in Visual Studio 2005 using Regular Expressions

The search dialouge in Visual Studio 2005 supports Regular Expressions, which is neat. A gotcha is that it's not the regular expression you might be used to... it's a special kind ... Here's a quicky-quick tutorial: To find all entries of GetString(" variable string ") (to insert appropriate values in a resource file, for example), you do this: CTRL+SHIFT+F (find in files (to get the result as a list)) Type GetString\({:q}\) Find Options: Check Use -> Regular expressions Result Options: Find results 1 window ALT+F (Find All) Sweet. Quick explanation: "\" escapes just like in "real regex" "{" and "}" groups results (instead of "(" and ")") ":q" means "match quoted string"

Poor man's JavaScript debugger

// Hold the trace data var trace = String(); // Debug log method function debug(str) { if(trace.length > 0) trace += "\n-> "; trace += str; } // The function with errors function advancedFunction() { try { debug("advancedFunction()"); debug("doing this"); doThis(); debug("doing that"); doThat(); debug("doing other"); doOther(); } catch(ex) { debug(ex.message); alert(trace); } }

Jennifer v0.1

Image
Public release! Jennifer (the code generator), v0.1 Download Source (Boo Programming Language) Download Executable (.NET 2 Platform) Screen shot: Features: Builds ASP.NET Labels, TextBoxes and validator in a flash! Plans for next release: A saved list of control definitions so that you can create more than one control set at a time. Support for date format(s) Support for control pre- and postfixs (such as td-tags)

Dynamically creating forms in ASP.NET 2

For those of us who'd rather write code than dragging and dropping controls on a form, here comes a few pointers: 1) Always create all controls of all possible views Even if you don't want to display all dynamically created controls, you will need to create them, if you would like to benefit from ASP.NET's built-in ViewState capability. That said, you don't have to display or even populate (see point 2 below) all controls. Just create them. Then, if you don't want them after all, set their Visible flag to False . 2) Don't databind controls on postback. A common mistake when dynamically creating pages, is to attempt to databind on callback. Well,m the thing is that the control is already bound, sort of speak. The data you are trying to bind is already in the control's view state, isn't it? ;-) 3) Create a FormBuilder class Save yourself some time. Here's a sample FormBuilder (written in VB.NET becuase I get paid for it ;-)): Publ