My new digital life

Personal, Readify 3 Comments

Well, TechEd is done (and dusted) and now I’m back to my normal life. Go to work in the morning to some customer, come back home in the evening, spend some quality time with family, browse the net a bit, code a bit, do a bit of support and maybe enjoy tv a bit. So life is pretty well defined.

However I started to realize how much my digital side life has changed lately. Not sure if it’s in better or worse but it has changed. Got a bunch of new gadgets, got a new backup plan, got a new Internet connection and just about to do some legal changes to our online shops.

So, here are some of the details:

New Gadgets

  1. NAS: After having several failures with my hard-drives I’ve decided backup is a high priority so I went out and invested in a D-Link DNS 323 Network Storage Enclosure. I’ve plugged in one Samsung 750Gb HDD (I plan to plug in a second one soon) and started to get my backups running. I have to say I love the NAS enclosure. Small and very quiet. I just didn’t find yet a good software to backup all my machines. The default software that comes with this NAS is Memeo but this is really bad. My machines now simply stay trashing the HDDs all the time. I had to disable the service to be able to do anything with my machine. I’m still trying to find a good backup software. Please let me know if you can recommend one.
  2. Bluetooth hands-free: At TechEd I’ve received a cute hand-free + wireless headset Jabra BT3030. I’ve connected it to my mobile and it works a treat. Superb quality, easy controls of calls and music, great battery, cute looking. My only comment is that it does not make any noise/vibration if you get a call so if you don’t hear your mobile or you don’t have the earphones plugged in you don’t know you receive a call so you miss it. If you are looking for a hands-free I highly recommend this. My only comment is that when you plug-in the default earplugs you feel like you are swimming in a fish-bowl. It’s supposed to part of the “noise-reduction”.
  3. Mouse: As part of making it to the State finals of the Demos Happen Here I’ve received a Microsoft Wireless Notebook Presenter Mouse 8000 (that’s a mouthful of name). I’ve just connected it and feel nice and smooth. The only problem is my Bluetooth drivers on the laptop are very flaky so I have a feeling this won’t work for too long.
  4. Laptop Battery: I have a beautiful but power-hungry Dell M65. I used to use a 9 cell battery that (when new) was giving me a good 3.5 hours of power. Almost 18 months after it was purchased the power dropped suddenly to about 40 minutes so I knew I had to get a new one. Best place is of course eBay. Original Dell OEM part from Hong-Kong for $87AUD delivered. I feels good to be back to 3.5 hours running on battery. I can go through most of my meetings unplugged. Oh yes …

New backup plan

Well, it’s not there yet. I’ve got the NAS device, some software running on my machine backing up my projects and documents to the NAS, Live Mesh for all shared document with my partner and Mozy for almost all documents. I love Mozy. The real set-and-forget backup.

New Internet connection

I live in a “remote” area of Sydney. The next suburb is the limit between metropolitan Sydney and Regional NSW. Well, not exactly but that’s how my friends tease me. Unfortunately my good’ old ISP Internode does not provide ADSL2 in my area. So because paying $30 for a Telstra phone line and $80 for an ADSL1+ is way too much I’ve decided to switch to the only provider that offers Naked ADSL2+ in my area: IINet.

I’ve applied for the plan about 3 weeks ago online and filled in all the details. The told me I’ll be offline for 10-20 days depending on my luck, the ordering of the planets and the mood of some of the Telstra engineers. Now, you really need to prepare your wife for a big event like 10-20 days of no Internet + no phone. Seriously.

On Monday (3 weeks after the application) around 9AM the Internet and phone stopped working. Ok, so we are about to get connected. Expect 10-20 days of downtime. Around 11AM I’ve got an email telling me I’ve been disconnected and I’ll be connected in 10-20 days.

Today, Tuesday, about 24h after the disconnection I get an email that my Internet is connected. Two hours later my phone was connected.

WOW. That’s impossible. No it’s not. It’s not Tuesday evening and I’m connected via the iiNet Naked ADSL2 connection. Feels good and just ok in speed. I guess I’m far from the exchange. I’m still happy. 24h downtime only is pretty good. I’ve just started to save about $50 a month. Not bad. Well done iiNet.

Domain ownership

As you might know, part of the rules for .com.au domains is that the company that has the domain has to have a good reason to own it (same or similar name or some other explanation).

So to buy a .com.au domain all you need is a company, an ABN and about $30 for two years.

However, if you want to change the ownership of a domain (company + ABN) you need a bunch of paperwork, signatures, align the planets, get your beloved mother in law to sign her mortgage and pay an arm and a leg. Yes, to transfer the ownership of a domain you can expected to be charged anywhere from $440 to $220 depending on the register that has your domain. Well, if $220 for a domain is a rip-off then $440 is outrageous.

So for the last 4 days I’ve started a quest to find a register that will change the ownership of some of my domains for less than $220 and I found them: www.anchor.com.au. The only company in Australia that decided to charge a fair amount for a simple procedure. All they charge for an ownership transfer is a same rate as a two years renewal $69.00 (you need to renew for two years anyway when you change a .com.au). Now this is fair and cheap. I can now recommend Anchor as the best value for money for domain ownership transfers.

Well, this is my new exciting digital life. Now, back to watching Mythbusters and then doing some more coding before going to bed.

TechEd done and dusted

.Net, Debugging, Readify, Tools, Visual Studio 4 Comments

Well, it seems like everyone is doing a post TechEd review of their own.

Me … I have to start with the comment that this was the best TechEd I’ve been too mostly because of the comments I’ve received for my sessions.

Some comments were good, some were great, some were funny and some were really eye-openers. (oh, yes, some were dull but they are worthless).

On Sunday I flew to TechEd NZ and much to my surprise when I’ve tried to book into my reserved hotel I was informed that I was upgraded and moved to the hotel on the other side of the road. Well, thank you. This was much appreciated. I was basically in the hotel just above the conference. I was taking the lift to level 4-5 and I was existing directly in the middle of the conference. You godda love that.

On Tuesday I had to do both my talks one after the other and then run straight to the airport. I didn’t get any feedback back as TechEd NZ seems to use paper to collect feedback and evaluations and heard no news from them. I hope they were good as I want to go back next year … one week earlier to do a bit of skiing as well …

On Wednesday I had my talk on debugging which went very well. The room was packed and the demos worked a threat. The only issue I had were the lights which were pointing straight into my eyes giving me the feeling of an FBI interview. It was hard to see the people in the room and the raised hands for questions.

The reviews&evals were really great. So great, I jumped straight in the top 10 best sessions and top 5 best speakers. Thanks everyone for filling in the reviews.

I have to write here some of the comments:

  • Best session I’ve been to for several Techeds, congratulations. this is what it is all about….
  • Simply amazed by this session, by far the best one I have seen during Tech-ed so far.
  • Utterly brilliant - this session paid for the entire entrance fee Excellent

Well, there were over 50 such comments so thanks everyone for taking the time and writing them.

Now, some of the funny ones included no comments but a rating of “Too Technical“. Well, for what we considered (and it was marked as) a 400 level presentation and some considered in their comments as a 300 level presentation, a “Too Technical” comment can only be considered a compliment. If you left that comment, then mate, the session was supposed to be technical ;)

Some of the eye-opener comments:

  • I understand there was alot to cover, but at times the information was a bit rushed, and I found myself unable to keep up with some of the more arcane sections
  • The only thing is that sometimes he’d speak a little too quickly, which combined with the accent made it hard to hear some things
  • Well delivered. He did have a “balky” moment when he mentioned he might shoot himself in the “leg”.(Woops. It was supposed to be “foot”. Sorry for that.)
  • Speaker’s accent was hard to understand at times

Comments from the security talk:

  • Ease up on the hand waving Corneliu :-) When flicking through code please linger a little longer to give people at least 2-3 seconds to process the context and the detail.
  • Speaks very fast
  • The guy was like a ferret on speed. Great knowledge, but flicked between code wayyy too quick. There were very few web developers in the room, and most of it was about web stuff. Can’t remember what was in the description, but this was disappointing.
  • Very web oriented, which was not obvious from the title.

Thanks a lot for these comments.

I know exactly what I need to focus on for next year.

  • Speak slower (and keep that rhythm of talking): I know I was quite conscious at times of this during my debugging talk but I completely lost myself in the security one as I had the feeling I’m running out of time
  • Present less: Have a smaller amount of information to talk about in one hour. Plan to have the session for only 50 minutes so I have time to speak slower. It’s easy to have an ace up the sleeves prepared that can fill in the last 5 minutes if you finish early.
  • Fix my accent: Maybe if I can just speak a bit slower it’s easier with my accent as well. I know my diction in English is quite bad and I’m hard to understand at time (let me tell you I speak as bad and hard to understand in my native Romanian as well). I’ve already engaged an English teacher (my lovely wife) to prepare a course for me to improve my diction and accent.
  • Work on some of the “quotes”/”jokers” that I use in my talks and make sure they are right. I’ll have to make sure you shot yourself in the “foot” not in the “leg”. (The original joke I was trying to refer to is How to Shoot Yourself In the Foot)

Well, now, back to my small corner of development:

  1. I have to finish the Deadlock detector as I think I have a fix for the tool not finding deadlocks between a lock() and a slim lock or read/write lock.
  2. I want to publish a Secure Web library for automatic encoding for ASP.Net controls that I was talking about in my security talk.
  3. I need to publish a new site for my games shop
  4. I need to start planning my upcoming trip to Europe

And most importantly I want to start planning for some new RDN talks and for some cool talks for next year’s TechEd.

PS>> If you were in my sessions and are looking for the demos/slides, please logon to TechEd portal and navigate to the session scheduler and you can find the pptx attached to the description of the sessions.

Green Tech.Ed

Personal, Readify No Comments

As I’m preparing for next week’s TechEd in NZ and Australia I’ve started to browse the pages they have prepared with details of the event.

One of the pages that I was most impressed by was the Earth Friendly Tech.Ed. Me trying to be a very green citizen of this planet (I run a house on green energy, offset my carbon emissions from the car and recycle every bit of recyclable material) I was very pleasantly surprised by Microsoft’s initiative.

Earlier this year Microsoft gave away some great reusable bottles to all it’s employees in Sydney in order to help reduce the number of plastic bottles used. I was lucky to work there at the time and received one of these bottles which not only it is very handy but also looks cool, attracts positive comments about it and yes, it’s green.

The initiative was very welcome.

So please go and visit the page and try to align and respect their initiatives.

Well done Microsoft.

TechEd & TechEd: Security and debugging

.Net, Improve Your Code, Readify, Secure your code, Visual Studio 3 Comments

It’s all been confirmed: I’ll be speaking at both TechEd New Zealand and TechEd Australia delivering two talk:

  1. Secure Development Patterns - How not to screw yourself during development
    We’ve all seen the news reports showing what can happen when an application goes into production with security issues. But what can you, as a developer or architect, do to stop it from happening to your team? Plenty! This session will provide a bunch of practical, real-world examples of how you can implement “defence in depth” in your projects.
  2. Debugging the world starting with the CLR
    It’s 3:00 AM and your service is down; your boss is breathing down your neck, and your SLA is approaching fast. The operations team refuse to allow you to install Visual Studio on the production machine, and without F5 or Attach to Process, you don’t know what to do. If only you had attended this session. Corneliu Tusnea will show you how to debug systems where no IDE is allowed; on running servers with live data, or offline with memory dumps. You’ll develop a sixth sense for finding deadlocks, memory leaks or unexpected exceptions. Whether you build Windows Services, ASP.NET websites or smart client applications, this session will give you the skills you need to debug in production, impress your fellow developers, and avoid being called into work at 3:00 AM!!

TechEd New Zealand schedule:

  1. SEC314 - Secure Development Patterns: How not to screw yourself during development
    Tuesday, 02 September 2008, 12:10PM - 1:25PM
    Elliot Rooms 1-3, Crowne Plaza
  2. DEV313 - Debugging the world, starting with the CLR (or Debugging from the trenches) (a shortened version of the talk as all I received was 30 minutes of talking)
    Tuesday, 02 September 2008, 1:40PM - 2:10PM
    NZ Room 4, SkyCity

You can book the sessions here: https://aunz.msteched.com/nz/sessions.aspx

TechEd Australia schedule:

  1. DEV410 - Debugging the world, starting with the CLR (or Debugging from the trenches)
    Wednesday, 03 September 2008, 2:00PM - 3:15PM
    Parkside Ballroom B
  2. SEC314 - Secure Development Patterns: How not to screw yourself during development
    Thursday, 04 September 2008, 12:00PM - 1:15PM
    Bayside 202/203

You can book the sessions here: https://aunz.msteched.com/au/sessions.aspx

I’ll also be around at other sessions and at the Ask the Experts night so please come and ping me.

As per Michael’s post there is also a competition on Ask the Experts to find the ultimate expert. Someone has to ask a question and nominate you to provide an answer to win a cool HP TouchSmart.

So please go and ask a question and nominate me to answer it.

Make the questions cool but not too hard as I might not be able to answer them :))

ACorns.Debugging - The .Net Deadlock Detector

.Net, Debugging, Improve Your Code, Tools, Visual Studio 17 Comments

As nothing exciting has happed in my yard since the last release of Hawkeye I’ve decided to spice up my life and write a new .Net tool: The .Net Deadlock Detector.

The punch line: The .Net Deadlock Detector is the only* tool that is able to detect and report a deadlock inside a running .Net process in a production environment or out of a memory dump.

(* Disclaimer: I couldn’t find any other tool to do this. If you know of one please let me know)

Production environment is an environment in which you don’t (want to) have installed a debugging tool like Visual Studio.

The .Net Deadlock Detector

  1. The tool does not require to have the code re-compiled in any way or form, with any external dependencies, nor reference any external library or have you modify your code to use any special type of locks inside your code
  2. It works on release builds with no PDB files
  3. It works on running processes or previously captured memory dumps
  4. It detects deadlocks across multiple threads and returns detailed call-stack and lock usage information
  5. It only detect deadlocks in which threads are actively waiting for locks acquired by other threads
  6. It does not detect the dining philosophers problem or deadlocks created in combination of time waits + wake/check + lock
  7. It has an external dependency on the cdb.exe (part of the the free Debugging Tools for Windows package from Microsoft)
  8. It requires absolutely no installation. It an xcopy deployment
  9. And best of all it’s free (source code to be published soon)

What’s a deadlock

A deadlock is a situation wherein two or more competing actions are waiting for the other to finish, and thus neither ever does. It is often seen in a paradox like ‘the chicken or the egg‘. (wikipedia)

For example Thread 1 locks resource A, Thread 2 locks resource B, Thread 1 wants resource B and starts a wait on resource B, Thread 2 wants resource A and starts a wait on resource A.

In this moment the two threads are considered deadlocked as each of them owns a resource while trying to acquire another resource owned by a different thread.

  1. Two threads, two resources
    image
  2. Thread 1 acquires resource A
    image
  3. Thread 2 acquires resource B
    image
  4. Thread 1 wants resource B and starts waiting for it
    image
  5. Thread 1 wants resource A and starts waiting for it
    image

Now both threads wait for the other one to release their resource.

How does the .Net Deadlock Detector work

The .Net Deadlock detector works by loading the cdb.exe (one of the native Windows Debuggers) on the target process and hooking the input and output streams of it to allow it to send commands and receive output from the debugger.

Then the tool is loading the sos (Son-on-Strike) debugging extensions into the cdb and starts sending commands to the cdb and sos and parse the output.

Then the tool follows a standard procedure in trying to find a managed deadlock by analysing the locks, the threads and the callbacks for each of the threads. As always one of the best examples to understand deadlocks is is Tess’s Deadlock case study.

So more or less the tool is a glorified macro system and command automation that is using standard cdb and sos commands to understand what is happening with the process and does some intensive analysis (including circular references search) to detect the deadlock.

How to “install” the .Net Deadlock Detector

  1. First of all before you can use the .Net Deadlock Detector you need to install (on your development machine not on the production machine) the Debugging Tools for Windows from Microsoft
  2. Then Download ACorns.Debugging.FindDeadlock.1.0.1.zip and unzip
  3. Now you need to copy the cdb.exe from the installation folder (defaults in C:\Program Files\Debugging Tools for Windows\cdb.exe) into the folder where the ACorns.Debugging.FindDeadlock.exe was unzipped
  4. You are now ready to use the tool
  5. You can now copy this new folder containing (ACorns.Debugging.Cdb.dll, ACorns.Debugging.FindDeadlock.exe and cdb.exe) to your production machine or target machine and start finding your deadlock

(Note: I’d love to deliver the a complete tool but the cdb.exe is not redistributable.)

How to use the .Net Deadlock Detector

If you finally got the right files prepared you are ready to try to find your deadlock.

The tool can be used with a set of command line parameters (exclusive):

ACorns.Debugging.FindDeadlock.exe [/pn=<processname>|/pid=<processid>|/DumpFile=<path to memory dump file>]

  • /pn=name of a process
  • /pid=id of a proces
  • /DumpFile=path to the file

For example to try the tool on the provided demo application start the application then start the deadlock detector with:

ACorns.Debugging.FindDeadlock.exe /pn=ACorns.Debugging.DeadlockTests.exe

Interpreting the results

The tool will output a bunch of less relevant details as it tries to understand the deadlock and at the end it presents a “graphical” representation of the deadlock with some general details about the threads and the locks:

image

Thread 4 owns a lock named B and waits for lock A. Thread 3 owns the lock A and waits for B.

Then the most relevant part of the analysis comes: the callstack involved in the deadlock. (the callstacks should be read bottom to top with the Using of locks referring to the next (up) method)

Thread 4 has the following callstack:

image

We can see that method StartThraed2 is using lock B and the Thread2Worker is trying to use lock A.

Thread 3 has the following callstack:

image

Method StartThread1 is using lock A and Thread1Worker is trying to use lock B.

With all this information at hand you should be able to find and fix your deadlock. Good luck!

If you have a memory dump of a process that has a deadlock that the tool can’t detect please let me know as I’d like to debug it and improve the tool.

Now, start the download of the ACorns.Debugging.FindDeadlock.1.0.1.zip tool and then head to Microsoft to download the Debugging Tools for Windows.

The tool is based on an idea by Tatham Oddie and Paul Stovell. Thanks guys!

Improve your debugging: Debugging Attributes to make your life easier

.Net, Improve Your Code, Visual Studio 6 Comments

During my recent talk on CLR Production Debugging I’ve talked about several interesting attributes that you introduce in your code to make debugging easier. Here is a review of these attributes:

Debugging support attributes

DebuggerStepThroughAttribute & DebuggerNonUserCodeAttrbute

Both attributes do about the same thing: they informs the debugger to not step into that class during normal “Step-Into” debugging. They are generally used on generated code or framework code to avoid the pain on getting into a method that you don’t care about while you debug.

There are very subtle differences between the two attributes:

  • DebuggerStepThroughAttribute
    • Can be applied to Classes, Structs, Constructors and Methods
    • Will not step into the method on “Step Into” through the debugger, but allows you to set a breakpoint in the method and the debugger will stop at that breakpoint.
  • DebuggerNonUserCodeAttrbute
    • Can be applied to Classes, Structs, Constructors, Methods and Properties
    • Will not step into the method at all even if you have a breakpoint setup or an exception is raised

Sample:

The debugger will not enter in any method declared in this class:

[DebuggerStepThrough()]
public static class ConfigUtils
{
    […]
}

Debugging enhancement attributes

Enhancements attributes are attributes that have no meaning for the CLR but are used by the debugger to improve the way the type/variable is displayed when you look at it in the debugger.

DebuggerDisplayAttribute

Changes the way the class is rendered in the debugger. In the declaration of the attribute you can include multiple properties or fields of you class to be displayed and even call methods on your class and render the result.

You can also include properties or fields of your member properties/fields and your class.

This attribute can be applied to basically almost every construct (classes, structs, enums, fields, properties, delegates and assemblies).

The attribute also supports display based on conditions and basic formatting like “nq” used to strip away quotes from strings.

Samples:

[DebuggerDisplay(“Id={id} Name={firstName} {lastName}”)]
public class Customer
{
    private int id;
    private string firstName;
    private string lastName;

No attributes applied:

image

Applying the attribute will display:

image 

The following attribute:

[DebuggerDisplay(“Id={id} Name={firstName, nq} {lastName, nq} Orders={Orders.Count}”)]

Renders this:

image

More details can be found on the MSDN page Using DebuggerDisplay Attribute.

DebuggerBrowsableAttribute

The attribute can be used to let the debugger know how to display (or not to display) specified fields or properties of your class.

For example setting [DebuggerBrowsable(DebuggerBrowsableState.Never)] will make the field invisible in the watch of data tips of the debugger. This is especially useful when you have fields that are exposed as properties and you don’t want to see them twice in the debugger:

Sample:

public class Customer
{
    [DebuggerBrowsable(DebuggerBrowsableState.Never)]
    private int id;
    public int Id
    { get { return id; } set { id = value; } }
    [DebuggerBrowsable(DebuggerBrowsableState.Never)]
    private string firstName;
    [DebuggerBrowsable(DebuggerBrowsableState.Never)]
    private string lastName;

No attributes applied will render this:

image

(you can see both the fields and the properties)

Applying the attributes will render this:

image

(only the public properties are visible)

Several other attributes worth having a look at are:

  • DebuggerTypeProxyAttribute - allows to specify a proxy class that will be used to display your type. The debugger will instantiate the proxy and ask it to render your class. Can be very valuable when you want to look at complex classes.
  • DebuggerVisualizerAttribute - allows you to specify a class to be used to visualize your type.

Happy debugging.

Update: 25/07/2008 20:50: You can see a quick screen-cast of using these attributes here: http://www.acorns.com.au/files/VS_Debugging_Tips_Attributes.wmv (10.6Mb)

Production Debugging Talk: Debugging the World, Starting with the CLR

.Net, Personal, Readify 2 Comments

If you are based in Sydney or Melbourne come and see my next talk brought to you by Readify RDN.

Debugging the World, starting with the CLR: A session about real-life production debugging from the trenches and how to write better code to help you with debugging.

Leave F5 to the beginners and debug anywhere, anytime: Learn how to debug systems where you can’t install a debugger, release code or third-party code and production machines running live data.  Learn how to debug offline with memory dumps, how to detect deadlocks, debug Windows Services start-up crashes, ASP .NET websites or Smart Client applications.

Sydney

Melbourne

Don’t know what RDN is?

The Readify Developer Network is the easiest way for you to get a head start in new and upcoming Microsoft technologies, including BizTalk R2, Visual Studio 2008 and Powershell.

Head now to the Readify website and register.

Secure your website: Use AntiXss to protect your website

Improve Your Code, Secure your code 1 Comment

Intro

If you care only a little bit for the security of your ASP.Net application, I am sure that you’ve heard about of Cross-site scripting attacks and of the Microsoft Anti-Cross Site Scripting Library. Html Encoding using AntiXSS is a must for any serious website and it should be mandatory for any web framework (DNN, CS …).

If you didn’t hear about it, then head to it right now: Start here, then go to here and here.

If you don’t want to read about it then head here and here or even better here to read about what it can do it your site, then go back, read about it and implement it.

And if you are still not sure how popular this type of attack can be and how important is to protect then read Samy’s story about how he took down MySpace.com in 24 hours and added more than 1 million friends to himself using a tiny little Xss.

ASP.Net vs AntiXSS

Now that you have a good understanding of what XSS is, you noticed that one of the mitigations that has to be applied is to use HtmlEncode (or other variants) on all rendered data that could have originated from the user.

The main difference between ASP.Net’s HttpUtility.HtmlEncode and AntiXss.HtmlEncode is the fact that the ASP.Net version is using black-listing (encode several known characters) while the AntiXss.HtmlEncode (and the other variants) are using white-listing (encode everything except few not-dangerous characters). You can read more about the differences here.

Big Note: Please don’t even consider to use the ASP.Net HttpUtility.HtmlEncode as there is a reported, Won’t Fix bug reported about it that could become critical one day. Always use the AntiXss for any type of encoding.

What to encode

Everything containing data originating from the user (or data not owned by you and to be known to be secure). Better encode more than less.

Here is non-comprehensive list:

  • Names: User Names, First Name, Last Name …
  • Personal details (addresses, emails)
  • Urls
  • Subject lines, content of posts, emails, website or email feedback
  • Links to Images and avatars
  • User profiles and signatures

How to use Anti Xss:

Basic encoding for Labels, Literals or other controls:

Insecure:

lblEmail.Text = customer.EmailAddress;

Secure:

lblEmail.Text = AntiXss.HtmlEncode(customer.EmailAddress);

This type of code looks ok and it’s not that hard to write and to verify that your application is always using encoding.

However if you use some type of data binding you have to take a much longer route and change your code from something simple like:

Insecure:

<ItemTemplate>
    Description: <%# Eval(“Description”) %>
</ItemTemplate>

To this:

Secure:

<ItemTemplate>
    Description: <%# AntiXss.HtmlAttributeEncode ( DataBinder.Eval( Container.DataItem,“Description” ).ToString() ) %>
</ItemTemplate>  

One more resources worth having at hand for tests is the XSS (Cross Site Scripting) Cheat Sheet. Don’t try to enter this via your UI and say “hey, you can’t enter them” so I’m secure because it’s just a matter of time before someone enters them in your database.

For a real test enter the examples from this page directly in your database (as user names, customer names or user profiles for example) and see how well your website works.

Improve your code: ASP.Net Label vs Literal

Improve Your Code No Comments

Questions:

  • Do you know what is the difference between an asp:Label and an asp:Literal?
  • Do you know when to use one and when to use the other?

If you do, don’t read, if you don’t keep on reading:

Differences:

Label:

ASP.Net:

<asp:Label ID=”messageText” runat=”server” meta:resourcekey=”messageTextResource1″ />

Rendered HTML:

<span id=”ctl00_Main_ctl00_messageText”>An email has been sent to ‘gigi@gigi.com’.  </span>

Literal

ASP.Net:

<asp:Literal ID=”messageText” runat=”server” meta:resourcekey=”messageTextResource1″ />

Rendered HTML:

An email has been sent to 'gigi@gigi.com'.

As you can see an asp:Literal does not generate a <span> tag. This is the main difference.

Real life scenario:

When you embed a tag into another tag you should be aware of the validity of the generated code. I know most of us don’t (yet) target to generate any valid XHTML code it would be nice to get this first time around, so writing correct code in the first place should be important for us.

If you have the following pattern:

ASP.Net:

<h2><asp:Label ID=”lblSomeTitle” runat=”server” meta:resourcekey=”lblSomeTitleResource1″></asp:Label></h2>

Rendered HTML:

<H2><span id=” ctl00_Main_ctl00_lblSomeTitle>Step 2 of 3</span></h2>

This is invalid HTML as per XHTML 1.0 Strict or XHTML 1.1 Strict.

Not only we generate too much code (we have an extra Span with an id for no valid reason) we are also breaking standards. IE6, IE7 accepts it, FF mostly accepts it but it’s wrong.

The fix is simple: Change your code to use a Literal

ASP.Net:

<h2><asp:Literal ID=”lblSomeTitle” runat=”server” meta:resourcekey=”lblSomeTitleResource1″></asp:Literal></h2>

HTML:

<H2>Step 2 of 3</h2>

Almost the same code, much better and smaller HTML.

When to use which:

  1. Use Labels when you need to set a CSS class (errors or so)
  2. Use Labels when you have references from JavaScript to your label.
  3. Use Labels when they represent Field set labels with an AssociatedControlID set
  4. Use Literal when you need to display data that the user has originally entered (names, emails…) and set the Mode=”Encode” attribute to automatically Html Encode the rendered data to help avoiding CSS injection attacks
    • An even better approach is to use the AntiXSS library and encode your un-trusted strings before setting them into the label/literal.
  5. Use Literal in every other scenario

Improve your code: Take care of "magic values" in code

Improve Your Code No Comments

We all know that “magic values” can be bad but we still use them. Sometimes we need them to represent specific states like not initialised, or almost initialised or some other type of placeholder. The simple fact that we still see magic values in code in every project it means developers still use them.

Anyway, one day we had a problem on one of our views and we traced the problem to some wrong checks for the magic value of a specific id. We fixed the problem and also changed the “magic” value from the “magic 0 (zero)” to the less magic and obvious “-1”. We thought we fixed the problem until we discovered that the code had some tests not using the constant but checking directly against zero.

What we learned:

  1. If you need to use a magic value to represent a specific “non-existent” information NEVER user 0 (zero) or default(T). Zero is the default for an integer so your might hit your “magic” value even in the scenarios that you don’t expect.
  2. Never assume that if you could parse a string into an integer the value you just parsed is a valid value. We parsed a zero and the code simply assumed that if the parse worked the value is good. The parse worked with zero and the code did a (zero – 1) then referenced an array. It failed. Always validate the results of the parse.
  3. If you need to check against a magic value ALWAYS check against the constant and NEVER against the magic value itself.
  4. Obviously, this code:
    private const int Constants.ValueNotInitialised = 0;
    _someId = Constants.ValueNotInitialised;
    if (_someId == 0) { … }

    will fail when we modified Constants.ValueNotInitialised to be -1 and not zero.

A nice way to make sure none of your (non-string) magic values are safe and never used the wrong way is to declare your (non-string) constants using a non-fixed value:

#if DEBUG
    private readonly int MyMagicConstant = -Environment.TickCount;
#else
    private const int MyMagicConstant = -1;
#endif

On every debug run you’ll get a new MyMagicConstant value.

« Previous Entries