Monday, September 08, 2008

reflection

Like may others, I recently received the fateful email notifying me that Lutz Roeder will be giving up his work on .NET Reflector, the brilliant and essential tool he developed to peer into the internal implementation of .NET assemblies.  Of course the whole idea of reflecting into an assembly is cheating a bit, since one of the principles of OO design is that we don't care about implementations, only about contracts.  It gets worse, since one of the main reasons for using .NET Reflector is to reverse engineer someone else's (particularly Microsoft's) code.  Yet it is the perfect tool when one is good at reading code and simply needs to know how to do something special -- something that cannot be explained, but must be seen.

While many terms in computer science are drawn from other scientific fields, reflection appears not to be.  Instead, it is derived from the philosophical "reflective" tradition, and is a synonym for looking inward: introspection.  Reflection and introspection are not exactly the same thing, however.  This is a bit of subjective interpretation, of course, but it seems to me that unlike introspection, which is merely a turning inward, reflection tends to involve a stepping outside of oneself and peering at oneself.  In reflection, there is a moment of stopping and stepping back; the "I" who looks back on oneself is a cold and appraising self, cool and objective as a mirror.

Metaphors pass oddly between the world of philosophy and the world of computer science, often giving rise to peculiar reversals.  When concepts such as memory and CPU's were being developed, the developers of these concepts drew their metaphors from the workings of the human mind.  The persistent storage of a computer is like the human faculty of memory, and so it was called "memory".  The CPU works like the processing of the mind, and so we called it the central processing unit, sitting in the shell of the computer like a homunculus viewing a theater across which data is streamed.  Originally it was the mind that was the given, while the computer was modeled upon it.  Within a generation, the flow of metaphors has been reversed, and it is not uncommon find arguments about the computational nature of the brain based on analogies with the workings of computers.  Isn't it odd that we remember things, just like computers remember things?

The ancient Skeptics had the concept of epoche to describe this peculiar attitude of stepping back from the world, but it wasn't until Descartes that this philosophical notion became associated with the metaphor of optics.  In a letter to Arnauld from 1648, Descartes writes:

"We make a distinction between direct and reflective thoughts corresponding to the distinction we make between direct and reflective vision, one depending on the first impact of the rays and the other on the second."

This form of reflective thought, in turn, also turns up in at an essential turning point in Descartes' discussion of his Method, when he realizes that his moment of self-awareness is logically dependent on something higher:

"In the next place, from reflecting on the circumstance that I doubted, and that consequently my being was not wholly perfect, (for I clearly saw that it was a greater perfection to know than to doubt,) I was led to inquire whence I had learned to think of something more perfect than myself;"

Descartes uses the metaphor in several places in the Discourse on Method.  In each case, it is as if, after doing something, for instance doubting, he is looking out the corner of his eye at a mirror to see what he looks like when he is doing it, like an angler trying to perfect his cast or an orator attempting to improve his hand gestures.  In each case, what one sees is not quite what one expects to see; what one does is not quite what one thought one was doing.  The act of reflection provides a different view of ourselves from what we might observe from introspection alone.  For Descartes, it is always a matter of finding out what one is "really" doing, rather than what one thinks one is doing.

This notion of philosophical "true sight" through reflection is carried forward, on the other side of the channel, by Locke.  In his Essay Concerning Human Understanding, Locke writes:

"This source of ideas every man has wholly in himself; and though it be not sense, as having nothing to do with external objects, yet it is very like it, and might properly enough be called internal sense. But as I call the other Sensation, so I call this REFLECTION, the ideas it affords being such only as the mind gets by reflecting on its own operations within itself. By reflection then, in the following part of this discourse, I would be understood to mean, that notice which the mind takes of its own operations, and the manner of them, by reason whereof there come to be ideas of these operations in the understanding."

Within a century, reflection becomes so ingrained in philosophical thought, if not identified with it, that Kant is able to talk of "transcendental reflection":

"Reflection (reflexio) is not occupied about objects themselves, for the purpose of directly obtaining conceptions of them, but is that state of the mind in which we set ourselves to discover the subjective conditions under which we obtain conceptions.

...

"The act whereby I compare my representations with the faculty of cognition which originates them, and whereby I distinguish whether they are compared with each other as belonging to the pure understanding or to sensuous intuition, I term transcendental reflection."

In the 20th century, the reflective tradition takes a peculiar turn.  While the phenomenologists continued to use it as the central engine of their philosophizing, Wilfred Sellars began his attack on "the myth of the given" upon which phenomenological reflection depended.  From an epistemological viewpoint, Sellars questions the implicit assumption that we, as thinking individuals, have any privileged access to our own mental states. Instead, Sellars posits that what we actually have is not clear vision of our internal mental states, but rather a culturally mediated "folk psychology" of mind that we use to describe those mental states.  In one fell swoop, Sellars sweeps away the Cartesian tradition of self-understanding that informs the cogito ergo sum.

In a sense, however, this isn't truly a reversal of the reflective tradition but merely a refinement.  Sellars and his contemporary heirs, such as the Churchlands and Daniel Dennett, certainly provided a devastating blow to the reliability of philosophical introspection.  The Cartesian project, however, was not one of introspection, nor is the later phenomenological project.  The "given" was always assumed to be unreliable in some way, which is why philosophical "reflection" is required to analyze and correct the "given."  All that Sellars does is to move the venue of philosophical reflection from the armchair to the laboratory, where it no doubt belongs.

A more fundamental attack on the reflective tradition came from Italy approximately 200 hundred years before Sellars.  Giambattista Vico saw the danger of the Cartesian tradition of philosophical reflection as lying in its undermining of the given of cultural institutions.  A professor of oratory and law, Vico believed that common understanding held a society together, and that the dissolution of civilizations occurred not when those institutions no longer held, but rather when we begin to doubt that they even exist.  On the face of it, it sounds like the rather annoying contemporary arguments against "cultural relativism", but is actually a bit different.  Vico's argument is rather that we all live in a world of myths and metaphors that help us to regulate our lives, and in fact contribute to what makes us human, and able to communicate with one another.  In the 1730 edition of the New Science, Vico writes:

"Because, unlike in the time of the barbarism of sense, the barbarism of reflection pays attention only to the words and not to the spirit of the laws and regulations; even worse, whatever might have been claimed in these empty sounds of words is believed to be just.  In this way the barbarism of reflection claims to recognize and know the just, what the regulations and laws intend, and endeavors to defraud them through the superstition of words."

For Vico, the reflective tradition breaks down those civil bonds by presenting man as a rational man who can navigate the world of social institutions as an individual, the solitary cogito who sees clearly, and cooly, the world as it is.

This begets the natural question, does reflection really provide us with true sight, or does it merely dissociate ourselves from our inner lives in such a way that we only see what we want to see?  In computer science of course (not that this should be any guide to philosophy) the latter is the case.  Reflection is accomplished by publishing metadata about a code library which may or may not be true.  It does not allow us to view the code as it really is, but rather provides us a mediated view of the code, which is then associated with the code.  We assume it is reliable, but there is no way of really knowing until something goes wrong.

posted by J Ashley on Monday, September 08, 2008 1:54:30 PM (Eastern Standard Time, UTC-05:00)  #    Comments [0]
 Wednesday, September 03, 2008

The Validator Callout Extender is one of the controls included in the Ajax Control Toolkit.  It allows one to replace the normal appearance of an asp.net validation control with an attractive cutout.  For instance:

This is a required field.

A common problem concerns how to restyle the callout to give it a custom appearance.  The documentation for this control makes it clear that the default CSS class may be overridden in order to change the appearance of the callout. The Callout Extender has a CssClass property which may be set to a custom style.  Unfortunately, the documentation also includes an apparent error.  According to the documentation for the Validation Callout Extender:

If your CssClass does not provide values for any of those then it falls back to the default value.

This turns out not to be true.  Instead, one must override all the nested classes of the Callout Extender in order to get a reasonably good looking callout.  If any of the nested classes are not overridden, once a value has been assigned to the CssClass property, no style is applied to the nested style.

Consequently, in order to do something as simple as setting the back-color of the callout to Blue, the custom style will end up looking like this:

    <style type="text/css">
        .customCalloutStyle div, .customCalloutStyle td
        {
            border: solid 1px Black;
            background-color: Blue;
        }
        .customCalloutStyle .ajax__validatorcallout_popup_table
        {
            display: none;
            border: none;
            background-color: transparent;
            padding: 0px;
        }
        .customCalloutStyle .ajax__validatorcallout_popup_table_row
        {
            vertical-align: top;
            height: 100%;
            background-color: transparent;
            padding: 0px;
        }
        .customCalloutStyle .ajax__validatorcallout_callout_cell
        {
            width: 20px;
            height: 100%;
            text-align: right;
            vertical-align: top;
            border: none;
            background-color: transparent;
            padding: 0px;
        }
        .customCalloutStyle .ajax__validatorcallout_callout_table
        {
            height: 100%;
            border: none;
            background-color: transparent;
            padding: 0px;
        }
        .customCalloutStyle .ajax__validatorcallout_callout_table_row
        {
            background-color: transparent;
            padding: 0px;
        }
        .customCalloutStyle .ajax__validatorcallout_callout_arrow_cell
        {
            padding: 8px 0px 0px 0px;
            text-align: right;
            vertical-align: top;
            font-size: 1px;
            border: none;
            background-color: transparent;
        }
        .customCalloutStyle .ajax__validatorcallout_callout_arrow_cell .ajax__validatorcallout_innerdiv
        {
            font-size: 1px;
            position: relative;
            left: 1px;
            border-bottom: none;
            border-right: none;
            border-left: none;
            width: 15px;
            background-color: transparent;
            padding: 0px;
        }
        .customCalloutStyle .ajax__validatorcallout_callout_arrow_cell .ajax__validatorcallout_innerdiv div
        {
            height: 1px;
            overflow: hidden;
            border-top: none;
            border-bottom: none;
            border-right: none;
            padding: 0px;
            margin-left: auto;
        }
        .customCalloutStyle .ajax__validatorcallout_error_message_cell
        {
            font-family: Verdana;
            font-size: 10px;
            padding: 5px;
            border-right: none;
            border-left: none;
            width: 100%;
        }
        .customCalloutStyle .ajax__validatorcallout_icon_cell
        {
            width: 20px;
            padding: 5px;
            border-right: none;
        }
        .customCalloutStyle .ajax__validatorcallout_close_button_cell
        {
            vertical-align: top;
            padding: 0px;
            text-align: right;
            border-left: none;
        }
        .customCalloutStyle .ajax__validatorcallout_close_button_cell .ajax__validatorcallout_innerdiv
        {
            border: none;
            text-align: center;
            width: 10px;
            padding: 2px;
            cursor: pointer;
        }
    </style>

This will give you the following change in appearance:

This is a required field.

In order to play with the nested classes in order to customize the look of the callout, it would be useful to know what the HTML for the Validator Callout actually looks like.  Unfortunately, the callout is generated using client script, making it impossible to simply peek at the source in order to figure out what the markup looks like.  After about an hour of reading through the behavior class for the Callout Extender, I was finally able to come up with this:

        <table id="_popupTable" cellpadding="0" cellspacing="0" border="0" class="customCalloutStyle">
            <tbody>
                <tr class="ajax__validatorcallout_popup_table_row">
                    <td class="ajax__validatorcallout_callout_cell">
                        <table width="200px" cellpadding="0" cellspacing="0" border="0" 
                            class="ajax__validatorcallout_callout_table">
                            <tbody>
                                <tr class="ajax__validatorcallout_callout_table_row">
                                    <td class="ajax__validatorcallout_callout_arrow_cell">
                                        <div class="ajax__validatorcallout_innerdiv">
                                            <div style="width: 14px">
                                            </div>
                                            <div style="width: 13px">
                                            </div>
                                            <div style="width: 12px">
                                            </div>
                                            <div style="width: 11px">
                                            </div>
                                            <div style="width: 10px">
                                            </div>
                                            <div style="width: 9px">
                                            </div>
                                            <div style="width: 8px">
                                            </div>
                                            <div style="width: 7px">
                                            </div>
                                            <div style="width: 6px">
                                            </div>
                                            <div style="width: 5px">
                                            </div>
                                            <div style="width: 4px">
                                            </div>
                                            <div style="width: 3px">
                                            </div>
                                            <div style="width: 2px">
                                            </div>
                                            <div style="width: 1px">
                                            </div>
                                        </div>
                                    </td>
                                    <td class="ajax__validatorcallout_icon_cell">
                                        <img alt="" border="0" src="alert-large.gif" />
                                    </td>
                                    <td class="ajax__validatorcallout_error_message_cell">
                                        This is a required field.
                                    </td>
                                    <td class="ajax__validatorcallout_close_button_cell">
                                        <div class="ajax__validatorcallout_innerdiv">
                                            <img alt="" border="0" src="close.gif" />
                                        </div>
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                    </td>
                </tr>
            </tbody>
        </table>
 

This probably isn't completely correct, but it's pretty close.  If you want to try to write your own custom style for the Validator Callout Extender, just copy the markup above, as well as the CSS class above that, into your favorite WYSIWYG editor and have at it.  At a minimum, you should be able to customize the colors either to match your site design (the default background color is Chiffon Yellow, after all), or to indicate different sorts of validation errors.

One question I've seen on the ASP.NET Forums concerns whether it is possible to switch the arrow that flies off the left side of the callout to the right.  Unfortunately, the arrow is actually coded into the HTML generated by the Validator Callout, and is not controlled by CSS styles.  It would be nice to see this as a feature of future releases of the Ajax Control Toolkit.

posted by J Ashley on Wednesday, September 03, 2008 9:13:41 PM (Eastern Standard Time, UTC-05:00)  #    Comments [1]
 Tuesday, September 02, 2008

Rocky Lhotka recently announced a pre-release drop for CSLA Light (the less filling version of CSLA 3.6).  Silverlight raises special problems for creating tiered applications.  CSLA Light tries to fill this problem domain by providing a framework for building bindable objects that know how to interact with Silverlight.  This is the sort of solution that will allow us to do more than simply build cool games with Silverlight, since the real promise of Silverlight is the ability to write business applications that are also RIA's.

One of the few alternatives to CSLA Light that I've seen is Shawn Wildermuth's work integrating Astoria with Silverlight.  I'm keeping an eye on both of these technologies to see how line-of-business Silverlight applications will shape up over the next year.

posted by J Ashley on Tuesday, September 02, 2008 5:33:16 PM (Eastern Standard Time, UTC-05:00)  #    Comments [0]
 Tuesday, August 26, 2008

sleestak1-349x267

I previously posted about how to use the Microsoft Ajax Library in order to provide Globalization script functionality without using the ScriptManager control.  Why would you want to do this?

One issue is that Microsoft is currently working on the ASP.NET MVC framework, which will provide a way of doing web applications that is more familiar to PHP and JSP programmers.  In other words, it doesn't use the WebForms infrastructure that has underpinned Microsoft's whole approach to web development for the past six years.  The original promise of WebForms was to abstract web development so it looks more like traditional Windows Forms development.  In order to accomplish this, the developers at Microsoft have worked hard to abstract the underlying web technology using windows components that render html and emit client script for the developer.

But now the tide is turning, and with WPF and XAML, Microsoft's newest technology for building desktop applications, we are seeing a transition to the development metaphors that we have become accustomed to in web development.

ASP.NET AJAX was originally developed following the WebForms paradigm.  While other AJAX frameworks provided script libraries that you needed to manipulate using client script (typically javascript), Microsoft provided their framework wrapped in controls like the ScriptManager and the UpdatePanel.  Even the Ajax Control Toolkit, the Microsoft backed opensource project that extends ASP.NET AJAX with additional controls, follows this model.

But the MVC model doesn't follow this model.  It follows the model followed by every other vendor of web technology.

So how do ASP.NET MVC and ASP.NET AJAX come together if they follow these radically different models?  Well ... the Microsoft AJAX team also provides the underlying scripts for their framework in the Microsoft Ajax Library, which can be used in JSP, PHP, or even your traditional HTML page if you are willing to do the muscle work required to hook into them.  They can also, of course, be used with the MVC framework.

The Ajax Control Toolkit now also exposes its underlying script files for general use, allowing use to get all the great ACT functionality with WebForms or a ScriptManager.  The only problem is that learning to use the library without controls to manage our state and emit our code is difficult, and there is very little online help to get you started.

Stephen Walther is now helping people through this difficulty on his blog, and it is a wonderful thing.  He has already tackled the Popup Calendar and Autocomplete.  Expect to hear more from him in the near future.  I can't wait to see what he does next.

h/t to Bertrand Leroy's Tales From the Evil Empire for highlighting this.

posted by J Ashley on Tuesday, August 26, 2008 11:17:07 AM (Eastern Standard Time, UTC-05:00)  #    Comments [0]
 Wednesday, August 20, 2008

bigfoot

I just spent about four hours trying to solve a problem I'll probably never actually encounter in the wild.  Someone posted on the asp.net forums about script globalization using ASP.NET AJAX.  This can be set up pretty easily by simply using the ScriptManager control and setting its EnableScriptGlobalization property to true.  ScriptManager takes care of importing the necessary scripts and handling all the underlying code required to make things work.

What the seeker on the forums wanted to know, however, was whether this could be accomplished without the ScriptManager.  In theory, all the ASP.NET AJAX framework scripts can be downloaded and used in a non-platform dependent manner.

Certain software problems are ubiquitous, and people tend to fall over themselves blogging and posting about them until Microsoft or some other vendor eventually either fixes the problem and it goes away.  On the other hand, there are problems in the software bestiary that are so rare that working on them is the programming equivalent of doing cryptozoology.

This was a juicy problem of that sort.  And I believe I have a solution. It basically involves redoing some of what the ScriptManager does automatically, but what the hey.

To support globalization in ecmascript, the ScriptManager basically sets a variable called __cultureInfo behind the scenes.  This is then used by various ASP.NET AJAX script methods to provide formatting information.  This is actually explained in the Microsoft documentation for the feature.

Behind the scenes, it seems clear, the ScriptManager is querying the CurrentUICulture of the current thread in order to determine the browser's preferred language, and passing this to the __cultureInfo variable.  The trick, then, is to determine the format of the culture data passed to __cultureInfo.

Here I had to use reflection to discover that there is an internal ClientCultureInfo type in the Sys.Web.Extensions assembly.  It made sense that this was being serialized and passed to the __cultureInfo variable.  With some trial and error, I finally got the serialization correct.

To make this work, you will need to download the Ajax Framework Library, which is a collection of javascript files.  You will need to import the MicrosoftAjax.js file into your web project, and then reference it in your page, like this:

<script src="MicrosoftAjax.js" type="text/javascript"></script>

You will also need to create the ClientCultureInfo class for your project, and make sure that it is serializable.  I tried DataContractJsonSerializer class to do my serializing,  but had problem getting the DateTimeFormatInfo type to serialize correctly, so I finally opted to use the now obsolete JavaScriptSerializer.  Here's what the class looks like:

    public class ClientCultureInfo

    {

 

        public string name;

        public DateTimeFormatInfo dateTimeFormat;

        public NumberFormatInfo numberFormat;

 

        public ClientCultureInfo(CultureInfo cultureInfo)

        {

            this.name = cultureInfo.Name;

            this.numberFormat = cultureInfo.NumberFormat;

            this.dateTimeFormat = cultureInfo.DateTimeFormat;

        }

 

        public static string SerializedCulture(ClientCultureInfo info)

        {

            JavaScriptSerializer js = new JavaScriptSerializer();

            return js.Serialize(info);

 

        }

 

    }

Now that we have the culture info formatted correctly, we need to be able to pass it to the client variable.  We'll create a public property in the code-behind that is accessible from the client, and set its value in the Page.Load event handler:

 

        protected void Page_Load(object sender, EventArgs e)

        {

            if (!Page.IsPostBack)

            {

                CultureInfo cultureInfo = System.Threading.Thread.CurrentThread.CurrentUICulture;

                ClientCultureInfo o = new ClientCultureInfo(cultureInfo);

                SerializedCulture = ClientCultureInfo.SerializedCulture(o);

            }

 

        }

 

        public string SerializedCulture

        {

            set

            {

                ViewState["kultur"] = value;

            }

            get

            {

                if (ViewState["kultur"] == null)

                    return string.Empty;

                else

                    return ViewState["kultur"].ToString();

            }

        }

Finally, we  need to use this code-behind property to set __cultureInfo.  Just add the following script block to your markup in order to set the current culture:

 

<script type="text/javascript">
    // Get the name field of the CurrentCulture object   
    var __cultureInfo = '<%= this.SerializedCulture %>';
    Sys.CultureInfo.CurrentCulture = Sys.CultureInfo._parse(__cultureInfo);
</script>

 

I added this to the bottom of the page.  To test whether this works, you will need to set the language property of your browser (if you are using IE, like I am).  I set mine to French for testing.  Then append the following script block below the one setting the culture above:

<script type="text/javascript">
    var currentCultureInfoObj = Sys.CultureInfo.CurrentCulture;
    var d = new Date();
    alert("Current culture is " + currentCultureInfoObj.name 
    + " and today is " 
    + d.localeFormat('dddd, dd MMMM yyyy HH:mm:ss'));  
</script> 

 

If you encounter any problems, it is possible that the web.config file is overriding the culture information from the browser.  In that case, make sure the culture is set to "auto" in the config file, like this:

 

    <system.web>

        <globalization uiCulture="auto" culture="auto" />

    </system.web>

posted by J Ashley on Wednesday, August 20, 2008 7:07:16 PM (Eastern Standard Time, UTC-05:00)  #    Comments [0]