I was looking at the generated site which ASP.NET Dynamic Data had provided and thought, I wonder how I can choose which columns I want to display based on the model itself.  This is then dynamic, in the way that for one model I show one column, but for the others I may show five, or six etc…

image

I have been following the posts from Matt Berseth, where he exploits the attributes from the System.ComponentModel namespace.  He shows how you can create a nice nested menu based on Category and Display Name attributes. 

So, this got me thinking, along the lines of, it is very convenient to use attributes in order to determine outcomes when working with meta data, and in this case, which columns I want to display inside the List.aspx template which you get provided out of the box as a standard template.  Alteration more than anything but before that, I need to set a few things up.

The MetaDataModels

These are the classes which dictate what meta information are available for your entities at runtime.  You assign the relevant meta data model to the entity using an attribute like the following:

[MetadataType(typeof(ProductMetadata))]
 public partial class Product
 {
     public Product(){

     }
 }

I then create another class which is the actual ProductMetaData.

[Category("Products")]
public class ProductMetadata
{
    [ScaffoldColumn(false)]
    public int ProductID{get;set;}

    [ListVisible]
    public string ProductCode{get;set;}
}

Now in the second example above you will notice the ListVisible attribute, this is custom and is defined simply like this:

[AttributeUsage(AttributeTargets.Property)]
public class ListVisibleAttribute : Attribute
{

}

The Column Generators

Once this is done you can then apply it to properties inside your class.  I only want to use this for Properties so I limit its scope using the AttributeUsage attribute.  So the idea now is this, once we have the meta table we are going to bind with, we want to then extract all the columns which have the attribute ListVisible.  I don’t want to create a new template though, not sure how yet lol, so I just want to edit the current.  The GridView auto generates its columns and something which I rooted out today was the ColumnGenerator type, or rather the IAutoFieldGenerator interface.  When you provide a GridView with this, it then knows which columns should be auto generated, so inline with this example I want to make a column generator which gets all the columns with the ListVisible attribute.

public class GridViewMetaColumnGenerator :IAutoFieldGenerator
{
    protected MetaTable table;

    public GridViewMetaColumnGenerator(MetaTable table)
    {
        this.table = table;
    }

    #region IAutoFieldGenerator Members

    public System.Collections.ICollection GenerateFields(Control control)
    {
        DataControlFieldCollection columns = new DataControlFieldCollection();

        foreach (MetaColumn col in table.Columns)
        {
            if (col.GetListVisible())
            {
                BoundField column = new BoundField();
                column.DataField = col.Name;
                column.SortExpression = col.Name;
                column.HeaderText = col.Name;
                columns.Add(column);
            }
        }

        return columns;
    }

    #endregion
}

So, i create the class which takes one argument in the constructor which is the MetaTable.  The GenerateFields method will be called by the GridView, so inside here I loop through the columns inside the MetaTable and if the column is decorated with the ListVisible attribute, I add it to the DataControlFieldCollection.  You will notice some familiar properties of the BoundField above.  The method GetListVisible is an extension method which I made, and simply checks for the presence of the attribute on the MetaColumn:

public static bool GetListVisible(this MetaColumn column)
{
    return column.Attributes[typeof(ListVisibleAttribute)] != null;
}

All that is left to do now is to alter the List.aspx template to include the column generator.  Below is the updated Page_Load event:

protected void Page_Load(object sender, EventArgs e)
{
    table = GridDataSource.GetTable();
    Title = table.DisplayName;
    InsertHyperLink.NavigateUrl = table.GetActionPath(PageAction.Insert);
    // Disable various options if the table is readonly

    GridViewMetaColumnGenerator metaColumnsGenerator = new GridViewMetaColumnGenerator(table);

    GridView1.ColumnsGenerator = metaColumnsGenerator;

    if (table.IsReadOnly)
    {
        GridView1.Columns[0].Visible = false;
        InsertHyperLink.Visible = false;
    }

}

And it works a treat, and if this is not the best way, I still think it is kind of clean.  Well I hope this helps some people as I appreciate this is new territory and I my self am constantly on the look out for helpful tutorials trying to open up the topic.

Cheers for now:

Andrew

UPDATE 27th March 2008

Although the above does work to an extent it does not work completely.  For one thing I have totally destroyed the functionality of the Dynamic Controls which are rendered based on the UIHint.  So, from reading about the internet I have found a few things including the fact that IAutoFieldGenerator has been used by the community in the ASP.NET Dynamic Data area for some time now.  The change required is the type which I am returning inside the GenerateFields method.  I currently instantiate BoundFields, where as I should be instantiating Dynamic Fields.

I also integrated a new field template which handles Many To Many relationships and that I got from this kind fellow at Micrsoft, David Ebbo.  Lots of Dynamic Data topics on here.

Another update I should also make the code above, is to provided further funationality on the custom attribute.  I am basically limiting its functionality to simply Lists.  Instead of that it would be better if you could state Flags for the type of Page Template the certain columns should be visible in.  Again this has already been done after searching round the internet.  So basically it provides a more robust approach than mine above.  Here is the example: http://stuartmanning.com/blogs/aspnet/archive/2009/01/26/dynamic-data-hiding-columns-in-selected-pagetemplates.aspx

So having not yet integrated that into my project I have still got the following as my GenerateFields method:

public System.Collections.ICollection GenerateFields(Control control)
{
    // Auto-generate fields from metadata.
    var fields = new List<DynamicField>();
    foreach (MetaColumn column in table.Columns)
    {
        // Skip column that shouldn't be scaffolded
        if (!column.Scaffold) continue;

        // Don't display long string in controls that show multiple items
        // REVIEW: we should avoid hard coding a list of control, but IDataBoundControl does not give us this info
        if ((column.IsLongString && control is GridView) || !column.GetListVisible())
            continue;


        // If it's a Many To Many column, use our special field template
        string uiHint = null;
        if (column.Provider.Association != null && column.Provider.Association.Direction == AssociationDirection.ManyToMany)
        {
            uiHint = "ManyToMany";
        }

        fields.Add(new DynamicField() { DataField = column.Name, UIHint = uiHint });
    }

    return fields;
}

Wednesday, March 25, 2009 9:09:39 PM (GMT Standard Time, UTC+00:00)  #    Disclaimer

I thought I would compose a short how to on programmatic web controls.  Often I have looked at the core set of controls within ASP.NET and wonder what design is required in order to get the design time mark up similar to that of the various controls.  The types of markup I am referring to includes:

  • Containers
  • Lists
  • Templates
  • Nested Controls of a certain type
  • Data bound controls
    • Only one example here, as I have wanted to do for ages and could not quite put my finger on how it was achieved.  Turns out, really simple lol

The following imports are used in these examples:

using System.Web.UI;
using System.Web.UI.WebControls;
using System.ComponentModel;

Simple Container Control

The first custom control structure I want to make is a custom panel.  Not inherited from a panel, although the same would be achieved but rather the simplest custom container. 

Desired Mark up

        <aebs:CustomPanel ID="Panel1" runat="server">
            Hell World
        </aebs:CustomPanel>
This is as simple as it gets.  This is a web control which persists any children controls or elements which you put in side.

    [ParseChildren(false)]
    [PersistChildren(true)]
    public class CustomPanel : WebControl
    {
        public CustomPanel()
        {
            //
            // TODO: Add constructor logic here
            //
        }
    }

A Control with an object list

This control is a web control but it has a list of an object, so you can add numerous types of the object to its collection.  The collection could be of a web control and if so it would be wise to inherit from a composite control as opposed to a web control.

Desired mark-up

        <aebs:ListControl1 ID="ListControl1" runat="server">
            <CustomObjects>
                <aebs:CustomObject CustomProperty="Hello World" />
                <aebs:CustomObject CustomProperty="Hello World 2" />
            </CustomObjects>
        </aebs:ListControl1>

So in design time you will see the intellisense prompt you for a tag called CustomObjects followed by nested prompts of a tag called Custom Object. 

image

    [ParseChildren(true)]
    [PersistChildren(false)]
    public class ListControl1 : WebControl
    {
        [PersistenceMode(PersistenceMode.InnerProperty)]
        public List<CustomObject> CustomObjects { get; set; }

        public ListControl1()
        {
            //
            // TODO: Add constructor logic here
            //
        }
    }

The Custom object is nothing more than a class with a property. see here

    public class CustomObject
    {
        public string CustomProperty { get; set; }

        public CustomObject()
        {
            //
            // TODO: Add constructor logic here
            //
        }
    }

A Template Control

The mark up achieved with this type of control is like the type you see with for example the form view control which allows for:

  • Item Template
  • Insert Item Template
  • Edit Item Template

All I am doing is showing the mark-up required for the design time mark-up, so when using you will need to use the ITemplate InstantiateIn method providing a web control or html control as the container.

Desired mark-up

        <aebs:TemplateControl ID="TemplateControl1" runat="server">
            <HeaderTemplate>
                Hello Header World
            </HeaderTemplate>
            <ContentTemplate>
                Hello Content World
            </ContentTemplate>
            <FooterTemplate>
                Hello Footer World
            </FooterTemplate>
        </aebs:TemplateControl>

image

The code to achieve this is as follows.

    [ParseChildren(true)]
    [PersistChildren(false)]
    public class TemplateControl : WebControl
    {
        [PersistenceMode(PersistenceMode.InnerProperty)]
        public ITemplate HeaderTemplate { get; set; }

        [PersistenceMode(PersistenceMode.InnerProperty)]
        public ITemplate ContentTemplate { get; set; }

        [PersistenceMode(PersistenceMode.InnerProperty)]
        public ITemplate FooterTemplate { get; set; }

        public TemplateControl()
        {
            //
            // TODO: Add constructor logic here
            //
        }
    }

You are going to want to control how each template is rendered but for the purposes of this example I am only showing the bare bones of how to achieve the mark-up.

A container control with specific object types as options

A good example of this type of control is when you use the object or sql data source control.  It allows you to specify parameters for the select, insert, update etc…  The options though which are provided to you are restricted so you can only choose parameter objects.  The key here is to specify a list property of the control with the type being a class other inherit from, not necessarily abstract.

Desired mark-up

        <aebs:ConstrainedCollection ID="Constrained1" runat="server">
            <AbstractProperties>
                <aebs:ConcreteOne />
                <aebs:ConcreteTwo />
            </AbstractProperties>
        </aebs:ConstrainedCollection>

image

The code to achieve this mark-up is as follows:

    [ParseChildren(true)]
    [PersistChildren(false)]
    public class ConstrainedCollection : WebControl
    {
        [PersistenceMode(PersistenceMode.InnerProperty)]
        public List<AbstractClass1> AbstractProperties { get; set; }

        public ConstrainedCollection()
        {
            //
            // TODO: Add constructor logic here
            //
        }
    }

So you can see that the only difference between this and the list control example above is that I use a type for the list which is inherited by two other types being ConcreteOne and also ConcreteTwo.

A DataPanel

I have wanted to do this for a while but could not quite put my finger on how it was achieved.  Like I said up top, this turns out to be really simple.  The same could be achieved with an ObjectDataSource and a FormView but i want a light weight container which I could throw an object at and use Eval inside it.  I have many many uses for such a light weight singular object display.  Plus I also wondered how the use of Eval was achieved in Custom Controls, turns out that it is through the use the System.Web.UI.IDataItemContainer Interface.

Desired Mark-up

        <aebs:DataPanel ID="datapanel1" runat="server">
            <%# Eval("ProjectName") %>
        </aebs:DataPanel>

So I am not doing anything more than requesting a property of the object which I throw at the control.  Throwing the object at the control I do inside the Page_Load event just for demo.

    public void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            DataPanel.Project p = new DataPanel.Project();
            p.ProjectName = "Project 101";

            datapanel1.BoundObject = p;
            datapanel1.DataBind();
        }
    }

image

So the code to achieve this is just the simple container control above but this time I implement the interface.  For the purposes of demonstration I have also banged the class inside this type as nested too.

    [ParseChildren(false)]
    [PersistChildren(true)]
    public class DataPanel : WebControl, IDataItemContainer
    {
        public class Project
        {
            public string ProjectName { get; set; }
        }

        private object boundObject;

        public DataPanel()
        {
            //
            // TODO: Add constructor logic here
            //
        }

        public object BoundObject
        {
            set
            {
                boundObject = value;
            }
        }

        #region IDataItemContainer Members

        public object DataItem
        {
            get { return boundObject; }
        }

        public int DataItemIndex
        {
            get { return 0; }
        }

        public int DisplayIndex
        {
            get { return 0; }
        }

        #endregion
    }

Well I hope this is of some use to others,  I will try and update this post soon with examples of custom DataSource controls and also custom DataBound Controls.  When you start get into List Controls from a data source it gets real fun.

Cheers

Andrew



.NET | Architecture | ASP.NET | C#
Tuesday, March 17, 2009 5:47:28 PM (GMT Standard Time, UTC+00:00)  #    Disclaimer

This morning I followed an Adobe Flex tutorial, well 3, about consuming Twitters restful API inside Flex.  After this it got me thinking about WCF and their Rest Starter Kit.  I looked and they are now up to Preview 2, so I downloaded it and in my spare time focused on this recently release white paper:

A Guide to Designing and Building RESTful Web Services with WCF 3.5

Installing the starter kit, which also installs some project templates, gives you a good starting point.  It also introduced me to some new concepts.  The starter kit actually generates a help page for your service which is an xml feed and XSLT Style Sheet e.g.

image

So It provides all the relevant information required i.e. the method, the uri template, the request and response schema.  I tested out a quick code up for the simplest form for consumption by C# and it worked out pretty well.  I focused on the fact that the info can be returned currently in two formats being XML and also JSON.  I wanted an abstract class to hold the URI’s for each method and also abstract methods which each derived object needs to override.

The idea is ultimately to have strongly typed helper methods for consuming restful apis.  So the tool, similar to the WSDL or SVCUTIL could be supplied with the following information:

  • namespace
  • language
  • url of help feed
  • asynchronous

What I would want to build on is the language part, as the interoperability of a rest api is huge.  If you make an implementation of the help generator in C# for example and use a Strategy pattern for the generation then this gives rise to the following:

  • C# Generation Strategy
  • VB.NET Generation Strategy
  • ActionScript Generation Strategy
  • C++ Generation Strategy
  • Pure JavaScript Generation Strategy
  • Jquery Generation Strategy (Yes I differentiated from the JavaScript option)
  • PHP Generation Strategy
  • Java Strategy
  • Python Strategy
  • Ruby on rails strategy

So you get the idea, it could be built then extended over time.  Am I getting ahead of myself here?  Is there one in production? WHO KNOWS? but it is fun never the less to jump in and have a go. 

So the quick Code Up I did is as follows:

Duplicate the type used in the REST Service and decorate with the namespace for XML Serialization needs

    [XmlRoot(Namespace="http://schemas.datacontract.org/2004/07/Swissmod.Service.Model")]
    public class Project
    {
        public string ID { get; set; }
        public string UserID { get; set; }
        public string ClientID { get; set; }
        public string ProjectTitle { get; set; }
        public string ProjectDescription { get; set; }
        public DateTime Created { get; set; }
        public DateTime LastModified { get; set; }
        public string Version { get; set; }

        public override string ToString()
        {
            StringBuilder sb1 = new StringBuilder();

            foreach (PropertyInfo pi in this.GetType().GetProperties())
            {
                sb1.AppendLine(pi.Name + " : " + pi.GetValue(this, null));
            }

            return sb1.ToString();
        }
    }

Define the abstract class for the Project Service

    public abstract class ProjectRestClient
    {
        protected string baseUrl = "http://test.@yoursite.com/ProjectService.svc/";

        public abstract Project GetProject(string id);
    }

Implement an XML Version of the Project Rest Client

    public class ProjectXmlRestClient : ProjectRestClient
    {
        public override Project GetProject(string id)
        {
            WebRequest wr = WebRequest.Create(baseUrl + id);
            wr.Method = "GET";
            wr.ContentType = "text/xml";
            WebResponse wresp = wr.GetResponse();
            XmlSerializer serializer = new XmlSerializer(typeof(Project));
            XmlReaderSettings settings = new XmlReaderSettings();
            settings.ValidationFlags = XmlSchemaValidationFlags.None;
            settings.ValidationType = ValidationType.None;
            settings.ConformanceLevel = ConformanceLevel.Auto;
            settings.IgnoreProcessingInstructions = true;
            settings.NameTable = new NameTable();
            settings.NameTable.Add("http://schemas.datacontract.org/2004/07/Swissmod.Service.Model");
            XmlReader reader = XmlReader.Create(wresp.GetResponseStream(),settings);
            Project p = (Project)serializer.Deserialize(reader);
            return p;
        }
    }

Implement a JSON Version of the Project Rest Client

    public class ProjectJsonRestClient : ProjectRestClient
    {
        public override Project GetProject(string id)
        {
            WebRequest wr = WebRequest.Create(baseUrl + id + "?format=json");
            wr.Method = "GET";
            WebResponse wresp = wr.GetResponse();
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(Project));
            Project p = (Project)serializer.ReadObject(wresp.GetResponseStream());
            return p;
        }
    }

Give it a whirl

At this point I know what is going to happen, but I am just protyping to give myself ideas for when I come to make a generation tool for the actual complete feed.  IF I CAN OFCOURSE! lol :-)

    public static class Program
    {
        const string XML = "XML";
        const string JSON = "JSON";

        [STAThread]
        public static void Main(string[] args)
        {
            IUnityContainer container = new UnityContainer();
            container.RegisterType<ProjectRestClient, ProjectXmlRestClient>(XML, new ContainerControlledLifetimeManager());
            container.RegisterType<ProjectRestClient, ProjectJsonRestClient>(JSON, new ContainerControlledLifetimeManager());

            ProjectRestClient xmlCient = container.Resolve<ProjectRestClient>(XML);
            ProjectRestClient jsonCient = container.Resolve<ProjectRestClient>(JSON);

            Console.WriteLine(xmlCient.GetProject("1"));
            Console.WriteLine(jsonCient.GetProject("1"));

            Console.WriteLine("Press any key to exit");
            Console.ReadKey();
        }
    }

P.S. I have used unity here for a few reasons but mainly because I love the idea of Inversion of Control and Dependency Injections.  The above simply allows me to obtain a singleton instance of either class whenever I want to execute a service method.

image

So to summarise, the only reason I am doing this is so that the consumption of the Rest service is strongly typed, I am not doing this because I think it is a necessity, simply because I think it would be extremely helpful for me.  The ability to strongly type things gives me much more happiness when working across language barriers.

Anyways,

Cheers for now,

Andrew



.NET | ASP.NET | C# | WCF
Tuesday, March 17, 2009 4:42:57 PM (GMT Standard Time, UTC+00:00)  #    Disclaimer

FlashDevelop IDE Project Source for sample application here
Working Example here

image

So I followed the three video tutorials here:

  1. http://theflashblog.com/?p=705
  2. http://theflashblog.com/?p=744
  3. http://theflashblog.com/?p=804

Lee Brimelow, the author, composed this inside Adobe Flex Builder 3.0 which is commercial and has a trial but ultimately you have to purchase.  I used FlashDevelop IDE to create the same small APP, and I have no complaints.  The biggest difference you will experience is not having design time support for the interface.  This is not an issue for me on a few levels but primarily because I am not a designer and programmatic layout is fine for me.

Watching the third tutorial in the series I found out about an amazing site called ScaleNine.  It is a community based site with designers skinning the component set provided by flex, and outputs the application to look like the above.  The normal default flex look is like this:

image

I, and I think you the reader will also prefer the above to the default one.  Using FlashDevelop IDE and the Flex SDK you can develop Flex applications totally free, with no over head apart from hosting your application somewhere.  With the FlashDevelop IDE you can also develop Adobe AIR applications which is what i want to try next.  Ultimately you will need to get learning Action Script 3.0 but once on your way, it is a really nice language to work with.  If you come from a C++, Java or C# background then the syntax will be a breeze.  The event model is similar to Java whilst Action Script 3.0 harness get and set keywords like C#.

Click here to get the Flash Develop IDE
Click here to get the Adobe Flex SDK

Cheers,

Andrew


Monday, March 16, 2009 11:13:56 AM (GMT Standard Time, UTC+00:00)  #    Disclaimer

This plug-in I made is quite handy and has a few applications.  I think JQuery is a fantastic library for javascript, as it does what it says on the tin:

WRITE LESS, DO MORE

Ok so the fader, I have written this plugin with a few options, which are:

  • slideClass
    • This is a JQuery selector syntax
  • slideDuration
    • This duration that the currently item stays visible for
  • fadeOutDuration
    • The duration it takes for an item to fade out
  • fadeInDuration
    • The duration it takes for an item to fade in

The structure which the plugin expects is simply a container element e.g. a div and subsequent nested containers which it will apply its effect to:

    <div class="slides">
        <div class="slide">
            <h1>Slide 1</h1>
        </div>
        <div class="slide">
            <h1>Slide 2</h1>
        </div>
        <div class="slide">
            <h1>Slide 3</h1>
        </div>
        <div class="slide">
            <h1>Slide 4</h1>
        </div>
    </div>

To trigger this function as soon as possible I place the following just before the end of the body tag:

...  
	<script type="text/javascript">
        (function() {
            var options = {
                slideClass: ".slide",
                slideDuration: 6000,
                fadeOutDuration: 2000,
                fadeInDuration: 500
            };

            $(".slides").fader(options);
        })();
    </script>
</body>

So if we look at the above HTML structure inline with the js, you can see the selector of “.slide” which tells the plugin which items to fade in/out.  You can apply this to many different containers with different options, the below shows an example of this with different speeds.  The html markup is as follows:

    <div class="slides">
        <div class="slide">
            <h1>Slide 1</h1>
        </div>
        <div class="slide">
            <h1>Slide 2</h1>
        </div>
        <div class="slide">
            <h1>Slide 3</h1>
        </div>
        <div class="slide">
            <h1>Slide 4</h1>
        </div>
    </div>
    
   <div class="slides2">
        <div class="slide">
            <h1>Slide 1</h1>
        </div>
        <div class="slide">
            <h1>Slide 2</h1>
        </div>
        <div class="slide">
            <h1>Slide 3</h1>
        </div>
        <div class="slide">
            <h1>Slide 4</h1>
        </div>
    </div>

This time I create a second container of class “slides2” but keep the containing elements with class of “slide.” To start the plugin on both containers I add another instance of options and select the second container.

...
	<script type="text/javascript">
        (function() {
            var options = {
                slideClass: ".slide",
                slideDuration: 6000,
                fadeOutDuration: 2000,
                fadeInDuration: 500
            };

            var options2 = {
                slideClass: ".slide",
                slideDuration: 2000,
                fadeOutDuration: 500,
                fadeInDuration: 500
            };

            $(".slides").fader(options);
            $(".slides2").fader(options2);
        })();
    </script>
</body>

The Plug-in Code

jQuery.fn.fader = function(options) {
    if (!options.slideClass || options.slideClass == "") {
        var error = new Error();
        error.message = "No slide class has been supplied";
    }

    if (!options.slideDuration || !parseInt(options.slideDuration)) {
        options.slideDuration = 4000;
    }

    if (!options.fadeOutDuration || !parseInt(options.fadeOutDuration)) {
        options.fadeOutDuration = 4000;
    }


    if (!options.fadeInDuration || !parseInt(options.fadeInDuration)) {
        options.fadeInDuration = 4000;
    }

    return this.each(function() {
        $(options.slideClass, this).hide();
        $(options.slideClass + ":eq(0)", this).show();
        var currentIndex = 0;
        var obj = this;
        var t = setInterval(function() {
        $(options.slideClass + ":eq(" + currentIndex + ")", obj).fadeOut(options.fadeOutDuration, function() {
                currentIndex++;
                if (currentIndex > $(options.slideClass, obj).size() - 1)
                    currentIndex = 0;
                $(options.slideClass + ":eq(" + currentIndex + ")", obj).fadeIn(options.fadeInDuration);
            });
        }, options.slideDuration);
    });
};

Sunday, March 15, 2009 9:57:44 AM (GMT Standard Time, UTC+00:00)  #    Disclaimer

The order in which I am constructing the points of this post are not chronological.  I was told the above statement a couple of years ago by my father who in turn heard it off one of his superiors.  It has taken some time for the actual meaning of this to make sense to me, in that I would see perfection as obtainable, maybe because my idea of perfection is not as high as others.  To rest your mind at ease I discovered that my pursuit of perfection was labour in vain and always will be.

Going completely off track for a second to compound my point, I was thinking of a book I wanted to purchase, which is “The Pragmatic Programmer” I then started thinking, well actually what does pragmatic mean.  So straight on to Google with define:pragmatic and one definition hit a chord straight away and is why this post is titled as it is:

Pragmatism - * In ordinary usage, pragmatism refers to behaviour which temporarily sets aside one ideal to pursue a lesser, more achievable ideal.

en.wikipedia.org/wiki/Pragmatism_(non-technical_usage)

As soon as I read this, the phrase which I was told by my father sprung to mind, albeit worded differently and more academic, but never the less just as meaningful.  I am also a bit surprised that the source of this definition wish to convey that it was not in technical usage.  May be so from a literal stand point, but after all my reading I have been doing of late to become a better programmer, I am thinking TDD, XP, Agile Development, Expectation Management, SCRUM etc… 

One more point I want to insert here, is one which has given me confidence that i am on the correct route in my journey of enlightenment.  In a nutshell I mean the knowledge that “IT IS POSSIBLE YOU MAY BE WRONG.”  I was reading the latest post from Uncle Bob - Let's Hear it for the Zealots! Tue 10/03/2009 21:58 .   Where he states:

There is a difference between a zealot, and a religious fanatic. A religious fanatic cannot envision themselves to be wrong. We in the agile community may indeed be zealots, but we know we can be wrong.

I totally agreed with this and I also paired this with a belief that it is very difficult, probably impossible, to know everything about a topic which fits the following criteria:

  • Large,
  • Diverse
  • Extremely detailed

I would class programming languages in this field as they also improve over time and morph.  .NET versions have gone from 1 to 4 at present, and each build brought new things.  The amount of things to learn in each is immense.  Some information is deprecated while other parts are core and always built on top of.

I will definitely not know everything but I am striving to know as much as I can at any specific time.  This could include information which is of no use what so ever but I want to rely on my growing experience to filter out this kind of information.

Right onto this free chapter of the new ASP.NET MVC 1.0 book released yesterday.

Cheers,

Andrew


Thursday, March 12, 2009 10:19:06 AM (GMT Standard Time, UTC+00:00)  #    Disclaimer

A question recently on StackOverflow.com triggered me to think that it would be nice if in JavaScript I could do this:

var d = new Date();
d.AddDays(1);

So exactly like what I can do in .NET.  I know a lot of people try and achieve date solutions by concatenating strings and parsing as a date, but this is not an option for me as JavaScript’s native DateTime is very powerful and due to this, there is absolutely no need to be hashing together strings.  So I will now paste the functionailty in C# that I based my methods on, dead simple, it is:

    DateTime d = new DateTime();

    public void Page_Load(object sender, EventArgs e)
    {
        DateTime days = d.AddDays(1);
        DateTime hours = d.AddHours(1);
        DateTime milliseconds = d.AddMilliseconds(1);
        DateTime minutes = d.AddMinutes(1);
        DateTime months = d.AddMonths(1);
        DateTime seconds = d.AddSeconds(1);
    }
So to exploit another JavaScript feature I will use prototype to extend the methods of the Date type inside javascript.  C# now has extension methods which are quite similar in what they allow you to use them like.  So the prototypes I want to create are as follows:

  • AddDays
  • AddHours
  • AddMilliseconds
  • AddMinutes
  • AddMonths
  • AddSeconds
    <script type="text/javascript">

        Date.prototype.AddDays = function(days) {
            this.setDate(this.getDate() + days);
            return this;
        }

        Date.prototype.AddHours = function(hours) {
            this.setHours(this.getHours() + hours);
            return this;
        }

        Date.prototype.AddMilliseconds = function(milliseconds) {
            this.setMilliseconds(this.getMilliseconds() + milliseconds);
            return this;
        }

        Date.prototype.AddMinutes = function(minutes) {
            this.setMinutes(this.getMinutes() + minutes, this.getSeconds(), this.getMilliseconds());
            return this;
        }

        Date.prototype.AddMonths = function(months) {
            this.setMonth(this.getMonth() + months, this.getDate());
            return this;
        }

        Date.prototype.AddSeconds = function(seconds) {
            this.setSeconds(this.getSeconds() + seconds, this.getMilliseconds());
            return this;
        }

        Date.prototype.AddYears = function(years) {
            this.setFullYear(this.getFullYear() + years);
            return this;
        }
    
    </script>

Excellent, nice clean, precise code.  So with this I can now do the following:

        <script type="text/javascript">
            var d = new Date();
            
            var output = d.AddDays(1).toString() + "<br/>" +
            d.AddHours(1).toString() + "<br/>" +
            d.AddMilliseconds(1).toString() + "<br/>" +
            d.AddMinutes(1).toString() + "<br/>" +
            d.AddMinutes(1).toString() + "<br/>" +
            d.AddMonths(1).toString() + "<br/>" +
            d.AddSeconds(1).toString() + "<br/>" +
            d.AddYears(1).toString() + "<br/>";

            document.write(output);
        
        </script>

With the output of

Sat Mar 07 2009 08:41:09 GMT+0000 (GMT Standard Time)
Sat Mar 07 2009 09:41:09 GMT+0000 (GMT Standard Time)
Sat Mar 07 2009 09:41:09 GMT+0000 (GMT Standard Time)
Sat Mar 07 2009 09:42:09 GMT+0000 (GMT Standard Time)
Sat Mar 07 2009 09:43:09 GMT+0000 (GMT Standard Time)
Tue Apr 07 2009 09:43:09 GMT+0100 (GMT Daylight Time)
Tue Apr 07 2009 09:43:10 GMT+0100 (GMT Daylight Time)
Wed Apr 07 2010 09:43:10 GMT+0100 (GMT Daylight Time)

Obviously if you want to subtract values from a date you would provide negative values into the methods, i.e. DateTime.AddDays(-10);

Cheers for now,

Andy


Friday, March 06, 2009 8:50:42 AM (GMT Standard Time, UTC+00:00)  #    Disclaimer

I think I am thinking too much about how to write a good blog post.  I think I need to master letting my brain flow while intercepting the output and tweaking things.  Well I have not yet mastered it, but I shall continue to try.  I was asked today to create a simple JQuery plug in which showed an html element containing a links title and this should be able to be styled and also follow the mouse whilst in hover state.  It is kinda like a pimped up tooltip.  The only thing out of the ordinary I did was hijack the rel attribute of the link as, if I continued to use the title attribute I got the default browser tooltip which overlaid my DHTML div.  I was thinking about creating my own attribute to add to the tag, but then again this would probably fail XHTML Validation.  This makes me wonder because from what I have read the new and upcoming version of the ASP.NET Ajax library introduce different attributes to the HTML.  Not sure if this is due to be released with the next iteration of the HTML standard.

Write to my plug in.  Here is the actual code I wrote for the plug in itself:

        jQuery.fn.popupLinkHelper = function(options) {
            var element = document.createElement("div");
            $(element).addClass(options.popupCssClass).hide();
            document.body.appendChild(element);

            return this.each(function() {
                $(this).hover(function() {
                    $(element).show();
                    $(element).html($(this).attr("rel"));
                    $(this).mousemove(function(e) {
                        $(element).css({
                            "position": "absolute",
                            "top": e.pageY + options.offsetY,
                            "left": e.pageX + options.offsetX
                        });
                    });
                }, function() {
                    $(element)
                });
            });
        };

To give an example using CSS I used the following CSS class to spruce up the popup:

        .popup
        {
            width: 150px;
            padding: 10px;
            background-color: #3366CC;
            border: black 2px solid;
            color: White;
        }

To trigger this code I use a notation publicised on the JQuery plug in authoring page.  As well I threw in some configuration options to as to be able to have more flexibility with it in the future:

    <script type="text/javascript">
        $(function() {
            var options = {
                offsetX: 50,
                offsetY: 0,
                popupCssClass: "popup"
            };
            $("a.pol").popupLinkHelper(options);
        });
    </script>

</body>

To test the following out I simply created a ul li block using the class pol (Pop out link – :-P) to identify those which I would target with the plug in.

    <ul>
        <li><a href="#" rel="This is example 1" class="pol">Example Link 1</a></li>
    </ul>

And the result:

image

Cheers for now:

Andrew,

P.S. Cross Browser Transparent Rounded Corners which is compatible with IE 6 – This is like Rocking Horse Muck, so hard to find lol.


Thursday, March 05, 2009 8:09:05 PM (GMT Standard Time, UTC+00:00)  #    Disclaimer