Friday, April 26, 2019

Sunday, November 25, 2007

Book Review "Code Complete"

http://www.amazon.com/Code-Complete-Practical-Handbook-Construction/dp/0735619670/ref=pd_sim_b_img_2

I just finished reading this book. It was a very good read. I do not remember myself thinking "this is incorrect" or "this guy is nuts".

A  lot of very good analysis of what software construction is about. I have been programming for almost 30 years and the experience you acquire is difficult to transfer to younger programmers. Finally, all the ins and outs of good programming are here on these pages. I wish I had known about this book earlier. It would have saved me some time reading about what I just discovered by a lot of practice.

This book should be a required read for all college students that get started in the real world. Then, they should read it again after a year and see the light.

The only problem with this book is that the author refers to many other books that just sound too interesting for me to not read them too!

#$#@%%, I have to go spend more money on computer books (for a change)














Never miss a thing. Make Yahoo your homepage.

Friday, January 05, 2007

ASP.Net 2.0 Event Validation Exception / The Why and the How

There is a new feature in ASP.Net 2.0 called Event Validation. Its value (EnableEventValidation) is true by default. If you upgraded from 1.1 to 2.0, your site may stop working.

The purpose of this feature is to protect your site from illegal values from being posted. For instance, let's say your have a drop down list with 3 values "0,1,2".
It is possible to construct a post (hacking) to post a value "3" for this drop down.
Indeed, the drop down simply generates a <select> element on the browser and is simple to alter.

Now, this rogue "3" may not be very serious for this example but all posted values
could be subject to change and force your application to do something that was
not intended.
In ASP.Net the event validation just checks that the value that is posted was actually in the list of values in the drop down. In other words, if a hacker posted "3" the framework would throw an exception since the initial list was "0,1,2".

Most of the time, you do not have to worry about it since you do not intentionaly
post bad values. However, once you start manipulating the DOM on the browser, you could for instance dynamically add a "3" to your <select> and the user could click on it.

As we move to more code on the client (the AJAX thing), you can see how this could happen. An asynchronous post back for instance could fetch data and you could add more options to your <select>.

If you know you may post values that were not in the initial list, you need to
call ClientScript.RegisterForEventValidation(). In this case you would do this:
ClientScript.RegisterForEventValidation(yourDropDown.UniqueID,"3").

Now, I have code that broke from 1.1 to 2.0. The reason was this. We created some javascript that used the __doPostBack() but we typed it manually. In other words, we were not using the GetCallBackReference() API that returns the javascript code to raise an event on the server. So we violated the framework's intent.

If you use Reflector and look at the GetCallBackReference(), you will see that
it uses the RegisterForEventValidation() and takes care of its business.

The conclusion is that the framework does a lot of work for you. Use it as intended or pull your hair for hours trying to figure out what's going on.





__________________________________________________
Do You Yahoo!?
Tired of spam? Yahoo! Mail has the best spam protection around
http://mail.yahoo.com

Monday, December 11, 2006

Extending the shell to get a .Net 3.0 command prompt

Take this text below. Save it as a DotNetCmd3_0.reg file and then double click on it. Now, on any folder, you can right click and see the ".NET Cmd 3.0" command prompt. You can then use ildasm for instance or xamlpad. This reg file basically saves you from selecting the following "Start/All Programs/Microsoft Windows SDK/Cmd Shell" with the mouse every time you need 3.0.

Windows Registry Editor Version 5.00

[HKEY_CLASSES_ROOT\Folder\shell\.NET Cmd 3.0\command]
@="C:\\WINDOWS\\system32\\cmd.exe /E:ON /V:ON /T:0E /K \"C:\\Program Files\\Microsoft SDKs\\Windows\\v6.0\\Bin\\SetEnv.Cmd\""




Cheap Talk? Check out Yahoo! Messenger's low PC-to-Phone call rates.

Friday, October 06, 2006

Solving The Double Post Problem On A Button

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;

namespace Developmentor
{
    /// <summary>
    /// C. Fouquet: Oct 2006
    /// This button cannot be clicked more than once during a post.
    /// This solves the classic double post problem where a user clicks
    /// a button more than once quickly and therefore posts twice!
    /// The idea is simple. Disable the button IMMEDIATELY after the click and
    /// THEN post. For that, we need to set a short timer to post very quickly after the
    /// button is disabled and give the illusion that the click is immediate.
    /// </summary>
    public class OneClickButton : Button
    {
        public int DelayInMs
        {
            get
            {
                if (ViewState["DelayInMs"] == null) return 20;
                return (int)ViewState["DelayInMs"];
            }
            set
            {
                ViewState["DelayInMs"] = value;
            }
        }

        protected override void Render(HtmlTextWriter writer)
        {
            string DisableMySelf = "document.getElementById('" + this.ClientID + "').disabled = true;";
            string PostIt = Page.ClientScript.GetPostBackEventReference(this, string.Empty);

            string FunctionName = "DelayedClick" + this.ClientID;
            StringBuilder sb = new StringBuilder();
            sb.Append("<script type=text/javascript >"); sb.Append(Environment.NewLine);
            sb.Append("function "); sb.Append(FunctionName); sb.Append("()"); sb.Append(Environment.NewLine);
            sb.Append("{"); sb.Append(Environment.NewLine);         
            sb.Append(PostIt); sb.Append(";"); sb.Append(Environment.NewLine);
            sb.Append("}"); sb.Append(Environment.NewLine);
            sb.Append("</script>"); sb.Append(Environment.NewLine);
            this.Attributes.Add("onclick", DisableMySelf + ";" + "setTimeout('" + FunctionName + "()',"+ DelayInMs.ToString() + ");return false");           
            writer.Write(sb.ToString()); // Write the javascript FIRST to it is available on click!
            base.Render(writer);           
        }             
    }
}


Saturday, August 05, 2006

One-Liners Getters And Setters For ASP.Net Control Properties


It is a little tiring to repeat the same code when persisting properties in the ViewState.
You basically have to do this for each property. Let assume we have a Count and a Text property.

int Count
{
    get
    {
        if(ViewState["Count"] == null) return 0; // Handle the null case
        return (int) ViewState["Count"]; // Need to cast
    }
    set
    {
        ViewState["Count"] = value;
    }
}

string Text
{
    get
    {
        if(ViewState["Text"] == null) return string.Empty; // Handle the null case
        return (string) ViewState["Text"];// Need to cast
    }
    set
    {
        ViewState["Text"] = value;
    }
}

Each time, you have to handle the case where the slot in ViewState is null and decide on a default value. It gets very boring very quickly. Casting the return value gets tiring too.

In my day job (yes, I have one), we have made our own bases classes for UserControls. This allows us to use some goodies we have made over time that is relevant to our application.

It would be cool to somehow "Factorize" this .... so here it is. We use generics to do the same logic every time.

namespace Developmentor
{
    public class UserControl : System.Web.UI.UserControl
    {
        protected void SetProperty<T>(string Name, T value)
        {
            ViewState[Name] = value;
        }

        protected T GetProperty<T>(string Name, T defaultValue)
        {
            if (ViewState[Name] == null)
            {
                return defaultValue;
            }
            return (T)ViewState[Name];
        }
    }
}

Now use it in an ascx like this. Just change the Inherits to point to your new and improved base. We have gained a little. At least we can do all this in one line now. There is still some typing but it is a little more 'Generic' ;-)


<%@ Control Language="C#" ClassName="simpleControl" Inherits="Developmentor.UserControl" %>

<script runat="server">
    
    string TheProperty
    {
        set
        {
            SetProperty<string>("TheProperty", value);
        }
        get
        {
            return GetProperty<string>("TheProperty", "?");
        }
    }
    protected override void Render(HtmlTextWriter writer)
    {
        writer.Write(TheProperty);
    }
</script>

This has been in my mind for a while. If you think that a brain like mine can't come up with this, well, you are right. I saw this in the Atlas framework using Reflector. Somebody at microsoft is thinking. When can we get this in the System.Web.UI.Control class in the framework? .Net 3.0?


Groups are talking. We´re listening. Check out the handy changes to Yahoo! Groups.