Posted by: rhwilburn | August 1, 2011

Adding a controller to JQueryMobile

JQuery Mobile highlights the power of HTML5 data attributes. An example div element with such an attribute could be:

<div data-role="header">

This new feature introduced in HTML5 – but backwards compatible with previous versions – is able to provide us with the flexibility to say what we mean rather than impreatively tell the code to do something. Im talking about declarative vs imperative programming.

Why Controllers in javascript?

Controllers are a part of the MVC pattern and are quite common in many areas of programming, however in my experience not so common in javascript development. This is possibly due to the requirement of javascript growing more and more as time goes on, and possibly due to the small scale in which it is usually used. Mobile development with phone gap tends to challenge this perspective of javascript by enabling large javascript applications to be developed in the mainstream.

Proposed approach

The Html

<a data-action="postForm">

The JQuery

$('a[data-action*=""]').live('click', function () {
      Log("Click -> Action");
      pageController.processAction($(this));
});
var pageController = new PageController();

function PageController() {
    this.processAction = function (itemWithAction) {

        var action = itemWithAction.attr('data-action');

        //Log("action = " + action);

        //Do something with the action here!!!
}

Performance benefits

Subscribing one click event to all necessary elements of the DOM for an application will be quite the performance hit. Instead this solution is subscribing to the root element of the DOM once. For more information see: http://api.jquery.com/live/

Reusability

The actions are able to be reused across multiple pages. They are fully separated from the page, with a reference to the triggering element.

Readability

Html elements that use data attributes to call actions make tracing event-action mappings much easier
Posted by: rhwilburn | April 9, 2011

Jquery Mobile – Dynamic Pages

Recently, I decided to make a mobile application. I have chosen to use a combination of Jquery Mobile and phone gap in order to achieve this goal.

I have found Jquery Mobile to be a good framework for making mobile applications however it is not long before discovering its abilities to dynamically generate content are not well documented. This is possibly because at the time of writing this, Jquery Mobile is in alpha status.

After googling round for quite a while, I discovered that there is a function called page(). That when applied to the end of an HTML fragment, it will convert the HTML into JQuery mobile appropriate HTML. The concepts of using this that are important are as follows

  1. Jquery mobile does not restrict functionality of Jquery.
  2. Jquery mobile parses an HTML document with the page() function to convert HTML to jquery mobile HTML (for better control/css theming etc).
  3. Jquery mobile will not parse updated html fragments added to the document unless you explicitly call the .page() function on that HTML fragment.
  4. In modern browsers, Jquery/java-script often  treats html blobs as a ‘documentFragment’ type which has virtually no functionality[W3C]. This can cause some confusion when calling the page function as the page function will fail on documentFragment types as discussed by me [Jquery Forum].
  5. Jquery mobile allows us to build phone gap and internet browser applications, allowing us to reach many markets with one solution.
  6. Jquery mobile is built on HTML 5. It uses the new meta data functionality for tags, i.e. <div data-tag=”taginfo” /> is valid in HTML 5 as any attribute on any tag that starts with data- is treated as meta-data (its not executed, but is recognized as valid by HTML 5 browsers).
  7. Jquery mobile has good examples but not always a good discussion of the concepts behind it, maybe I skipped over that part in my enthusiasm to get developing.
  8. Regular Updates. Currently they seem to release a new version of the alpha every 3 months.

An example of how to use the page function:

1) make sure you have a “page” on your html document:

<body>
   <div id="MyFirstMobilePage" data-role="page"></div>
</body>

2) add the following to the head of the document:

<head>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.0a4/jquery.mobile-1.0a4.min.css" />
<script src="http://code.jquery.com/jquery-1.5.min.js"></script>
<script src="http://code.jquery.com/mobile/1.0a4/jquery.mobile-1.0a4.min.js"></script>
<script type="text/javascript">
   $(function(){
      $('<select><option>test 1</option></select>').appendTo('#MyFirstMobilePage).page();
   });
</script>
</head>

If you run this code with firebug etc. installed in your browser you will observe that the HTML gets updated, not only inserting the select tag, but also other tags that are required by the mobile framework.

Posted by: rhwilburn | December 1, 2010

WCF Windows Service Deployment

I recently started work on a personal project to make a WCF Windows Service using the following tutorial: [1]. I soon realised that I would need to write a batch file to not be hugely disadvantaged by manual deployment. I also wanted my deployment batch scripts to be re-useable by other developers on the project.

The batch files I came up with were:

Install.bat:

@ECHO OFF

:: Known issues -
:: 1) if services window is open (ie the one when u start->run->services.msc) then the process will not close. You must close this window.
:: 2) if you don’t do a clean build then it will just install old version of service. Make sure you uninstall then do a clean build.

cd..

SET projectDirectory=%CD%

cd /d “%WinDir%\Microsoft.NET\Framework\v4.0.*”

SET net4Path=%CD%

@ECHO ON

%net4Path%\installutil “%PROJECTDIRECTORY%\bin\Debug\OrderServices.exe”

net start OrderServices

Uninstall.bat:

REM @ECHO OFF

cd..

SET projectDirectory=%CD%

cd /d “%WinDir%\Microsoft.NET\Framework\v4.0.*”

SET net4Path=%CD%

net stop OrderServices

%net4Path%\installutil /u “%PROJECTDIRECTORY%\bin\Debug\OrderServices.exe”

pause

Reinstall.bat (untested):

@echo off
CALL Unistall.bat
CALL Install.bat

Those batch files assume the following file structure in your service project:

ProjectStructure

Update:

The following link adds reference information as to how to forcefully play with services with the SC command: http://ss64.com/nt/sc.html

Posted by: rhwilburn | March 5, 2010

Dependency Property Basics

When working with WPF it can be necessary to extend a control to enable data-binding to a property that isn’t bind-able (because it is not a dependency property etc.). The following code demonstrates an example I have made where I override a Text property and give it a dependency property to enable data-binding.

 

public static readonly DependencyProperty TextProperty = DependencyProperty.Register("Text", typeof(string), typeof(TextEditorControl), new FrameworkPropertyMetadata(OnTextPropertyChanged));

 

private static void OnTextPropertyChanged(DependencyObject dp, DependencyPropertyChangedEventArgs e)

{

    //TODO: action handler here

}

 

public override string Text

{

    get

    {

        return (string)GetValue(TextProperty) ?? string.Empty;

    }

    set

    {

        base.Text = value;

 

        SetValue(TextProperty, value);

    }

}

 

The code also shows how to handle the event raised when the binding source (the view model) is updated. I recommend using dependency properties for WPF controls; as for view model classes I recommend implementing the INotifyPropertyChanged interface instead.

Posted by: rhwilburn | December 17, 2009

Using Castle’s Dynamic Proxy

As a user of Rhino Mocks, Ninject and certain parts of the Castle Project, I found myself wondering what the Castle Project’s dynamic proxy was. I have since learned and love the idea of, dynamic proxies.

What does a dynamic proxy do

A dynamic proxy is a way of generating a subclass from a class or interface of which is generally a model. That subclass overrides every method that it can (make your methods virtual to allow to do it). This provides the ability to intercept calls to all methods on your class/interface because the sub-classed methods route requests to an interface which dictates whether a call can proceed. You could implement that functionality yourself, however you would need to cater for all method calls. The dynamic proxy provides one interceptor handler for all methods, and you can have many interceptors on one class.

Cross cutting concerns

One of the major benefits of using proxy objects is the ability to separate cross cutting concerns such as logging. Take the following diagram as an example. It shows how the logging interceptor which takes care of the logging can log calls made to the person object without the person object having a reference or knowing about the logging interceptor. The person object also doesn’t know about the dynamic proxy library.

DynamicProxyDiagram

An argument for separating out logging from our classes could be that we might want to turn logging on or off, or that we want to replace our logging library at a later date. Both of those scenarios could be catered for by having a logging class which is directly called by our Person object. The advantage of doing that could be minor performance gains, and the disadvantage of not using a proxy is that the person object would be polluted with unnecessary code. Ideally a class would have a single purpose, and logging would not conform to the purpose of the person business object in my opinion because logging is an environmental aspect regarding person as opposed to actually defining what a person is. A strong example of this is using a dynamic proxy to add permission based access to calls on third party libraries without modifying the external library.

Interceptors

The following code shows how a logging interceptor might look. It logs the method name of the method that is currently being accessed, then it allows the method request to proceed. Without invocation.proceed, the call would not proceed to the person object in the previous example, and would instead be consumed.

    public class LoggingInterceptor : IInterceptor

    {

        public void Intercept(IInvocation invocation)

        {

            Console.Write("Log: Method Called: "+ invocation.Method.Name);

            invocation.Proceed();

        }

    }

 

Boxing and Un-boxing proxies

To create a proxy you can do the following:

ProxyGenerator generator = new ProxyGenerator();

Person person = generator.CreateClassProxy<Person>(new LoggingInterceptor());

 

If you are developing in a situation where you have a network boundary and you need to send your business objects across a network you will probably want to shed your proxies and possibly recreate the proxies on the other side of the network boundary.

var proxyTarget = personProxyObject as IProxyTargetAccessor

var person = proxyTarget.DynProxyGetTarget() as Person;

 

More Information

Posted by: rhwilburn | July 14, 2009

C# Actions part 2: Lazy evaluation

Lazy Evaluation example:

In a previous post I talked about C# Actions and how they are a useful feature that could provide new shorthand for lazy evaluation. I have since found an excellent article [1] which demonstrates lazy evaluation with LINQ. The advantages in that article show how LINQ queries can minimize memory usage by evaluating upon enumeration rather than just allocating memory for everything the query would return.

Func

Actions are delegates that have a void return type. This makes sense if you are using Actions as event handlers, but for other use cases you will want a return type. In these cases you will want to use Func. One issue I have seen with Func is when you want don’t know how many parameters your function is going to take. If the number is variable then you must implement up to the amount of parameters you want (if overloading). I noticed a few examples of that in the Ninject 1.x source code. To generalize Func and Actions you can use the ‘Delegate’ type (note: the captialization).

A real world use case

A reason for lazy evaluation could be that you want to perform a group of service calls at one time. The service calls could be a transaction style interaction which would want to be disposed afterwards and some of the service calls could be surplus to requirement. If I had a user interface which required a list of products to be loaded, then that screen may not need that data reloaded if it is moving from a screen which has that data loaded. That service call could be pre-evaluated (ie lazy evaluation) to check to see if it is necessary.

Posted by: rhwilburn | July 13, 2009

Observable Dictionary

As a fan of ObservableCollections, I have created an observable dictionary. I have provided the code below. I have implemented interfaces that should allow for WPF databinding. The reason I needed such a class is because I needed an event to indicate when the dictionary was updated. I kept this class small (it is just a wrapper over a dictionary).

public class ObservableDictionary<TKey, TValue> :

        IDictionary<TKey, TValue>,

        INotifyCollectionChanged,

        INotifyPropertyChanged

{

    public event NotifyCollectionChangedEventHandler CollectionChanged;

    public event PropertyChangedEventHandler PropertyChanged;

 

    readonly IDictionary<TKey, TValue> _dictionary = new Dictionary<TKey, TValue>();

 

    public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()

    {

        return _dictionary.GetEnumerator();

    }

 

    IEnumerator IEnumerable.GetEnumerator()

    {

        return GetEnumerator();

    }

 

    public void Add(KeyValuePair<TKey, TValue> item)

    {

        _dictionary.Add(item);

 

        if (CollectionChanged != null)

            CollectionChanged(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add));

 

        if (PropertyChanged != null)

        {

            PropertyChanged(this, new PropertyChangedEventArgs("Keys"));

            PropertyChanged(this, new PropertyChangedEventArgs("Values"));

        }

    }

 

    public void Clear()

    {

        int keysCount = _dictionary.Keys.Count;

 

        _dictionary.Clear();

 

        if (keysCount == 0) return; //dont trigger changed event if there was no change.

 

        if (CollectionChanged != null)

            CollectionChanged(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));

 

        if (PropertyChanged != null)

        {

            PropertyChanged(this, new PropertyChangedEventArgs("Keys"));

            PropertyChanged(this, new PropertyChangedEventArgs("Values"));

        }

    }

 

    public bool Contains(KeyValuePair<TKey, TValue> item)

    {

        return _dictionary.Contains(item);

    }

 

    public void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex)

    {

        _dictionary.CopyTo(array, arrayIndex);

    }

 

    public bool Remove(KeyValuePair<TKey, TValue> item)

    {

        bool remove = _dictionary.Remove(item);

 

        if (!remove) return false; //don’t trigger change events if there was no change.

 

        if (CollectionChanged != null)

            CollectionChanged(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove));

 

        if (PropertyChanged != null)

        {

            PropertyChanged(this, new PropertyChangedEventArgs("Keys"));

            PropertyChanged(this, new PropertyChangedEventArgs("Values"));

        }

 

        return true;

    }

 

    public int Count

    {

        get { return _dictionary.Count; }

    }

 

    public bool IsReadOnly

    {

        get { return _dictionary.IsReadOnly; }

    }

 

    public bool ContainsKey(TKey key)

    {

        return _dictionary.ContainsKey(key);

    }

 

    public void Add(TKey key, TValue value)

    {

        _dictionary.Add(key, value);

 

        if (CollectionChanged != null)

            CollectionChanged(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add));

 

        if (PropertyChanged != null)

        {

            PropertyChanged(this, new PropertyChangedEventArgs("Keys"));

            PropertyChanged(this, new PropertyChangedEventArgs("Values"));

        }

    }

 

    public bool Remove(TKey key)

    {

        bool remove = _dictionary.Remove(key);

 

        if (!remove) return false;

 

        if (CollectionChanged != null)

            CollectionChanged(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove));

 

        if (PropertyChanged != null)

        {

            PropertyChanged(this, new PropertyChangedEventArgs("Keys"));

            PropertyChanged(this, new PropertyChangedEventArgs("Values"));

        }

 

        return true;

    }

 

    public bool TryGetValue(TKey key, out TValue value)

    {

        return _dictionary.TryGetValue(key, out value);

    }

 

    public TValue this[TKey key]

    {

        get { return _dictionary[key]; }

        set

        {

            bool changed = _dictionary[key].Equals(value);

 

            if (!changed) return; //if there are no changes then we don’t need to update the value or trigger changed events.

 

            _dictionary[key] = value;

 

            if (CollectionChanged != null)

                CollectionChanged(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Replace));

 

            if (PropertyChanged != null)

            {

                PropertyChanged(this, new PropertyChangedEventArgs("Keys"));

                PropertyChanged(this, new PropertyChangedEventArgs("Values"));

            }

        }

    }

 

    public ICollection<TKey> Keys

    {

        get { return _dictionary.Keys; }

    }

 

    public ICollection<TValue> Values

    {

        get { return _dictionary.Values; }

    }

}

 

A link to another (Larger) implementation of an Observable Dictionary: http://www.drwpf.com/Blog/Default.aspx?tabid=36&EntryID=8

CC0
To the extent possible under law, Richard Wilburn has waived all copyright and related or neighboring rights to Observable Dictionary. This work is published from New Zealand.

Posted by: rhwilburn | July 5, 2009

C# Action’s

When playing around with UI events it is sometimes handy to use lambda notations of actions to do a tidy inline event-action handler definition such as:

Button1.Click += (sender, args) => Debug.WriteLine("Button Click");
 

If we delve a little deeper into Actions, we can use them to pass around code snippets/functions.

Action<String> action = (input) => Debug.WriteLine("Testing" + input); 
 

I have heard many arguments against functional features such as actions in C# however I do feel that they are very useful in edge cases. One such case could be the mass adding of items to a dictionary, such as:

var namesDictionary = new Dictionary<int, string>();
 
namesDictionary.Add(1,"One");
namesDictionary.Add(2,"Two");
namesDictionary.Add(3,"Three");
 

If we wanted to keep our code maintainable we might want to reduce our dependency to the Add method (especially if we had lots of dictionary add statements).

Action<int,string> addAction = (key,value) => namesDictionary.Add(key,value);
//Action<int,string> addAction = namesDictionary.Add; //short syntax

addAction(1, "One");  //etc
 

Note that this dictionary example is a bad example as the collection initialization could be used here which is likely the most optimal solution. The following shows how the collection initialization could have been used:

var namesDictionary = new Dictionary<int, string> {{1, "One"}, {2, "Two"}, {3, "Three"}};
 

This example also could have been solved more optimally using extension method(s), by extending the dictionary, dependency injection, lambda foreach statement, foreach loop etc. With that said, Actions are important in allowing for lazy evaluation/delayed invocation. I am not going to get into lazy evaluation in this post, but I recommend checking out the Haskell language community for lazy evaluation ideas. I highly recommend the following link for understanding how evaluation/manipulation of lambda expressions work.

http://msdn.microsoft.com/en-us/library/bb397951.aspx

Posted by: rhwilburn | March 6, 2009

Boosting Visual Studio Performance

Visual Studio has always worked fairly well for me at home, but at work where many of our projects/solutions are very large Visual Studio struggles. At home I still find that my Visual Studio is better than the one I use at work and I believe this is because at home I have my hard-drives in a performance RAID (Raid 0) and my OS is Vista x64 rather than XP x86.

Two things I suspect are:

Vista manages memory much better and doesn’t struggle with the out of memory exceptions that I frequently get at work. Note: Out of memory exceptions are actually to do with the .NET runtime not being able to garbage collect all of its generations properly. But the size of Visual Studio and the number of objects it is using is the cause of this.

Hard-drive speed affects Visual Studio more greatly than CPU and potentially even RAM. When I get out of memory exceptions at work (we all get this too btw) my PC is not using all of its 2 gigs of ram. Visual Studio is limited by default to 2 gigs, but this can be overcome.

Remedies:

 

Faster harddrives, lowerlatency hard drives:

On Vista with my RAID 0 my experience is better but is still latent. My IDE can load lots of data fast but often takes a while to do so. This means waits are still a small amount of time due to latency issues but large amounts of data are not really an issue.

I am starting to think that the ideal solution is a performance raid of Solid State Drives (SSD).  A link on performance improvements for a Java IDE are available here: http://jexp.de/blog/archives/18-On-Boosting-My-IDEA-Jetbrains-IntelliJ-IDEA-is-fast-again.html

If you have an infinite money pool, a RAID card would be recommended too. These can have RAM on them to cache disk access which would further reduce latency.

Upgrade OS:

Upgrade to Vista and make sure you upgrade to the 64 bit version. It is silly not to take advantage of your CPU being x64.

Myths:

 

Resharper:

Myth: Reshaper significantly degrades performance, and causes out of memory exceptions.

Interestingly resharper shows the out of memory exceptions (which can be a pain) where as Visual Studio virtually hides it from the user. Resharper is not causing these issues, and from what I have seen there is no significant performance difference apart from when the project is being loaded. That is because resharper loads its cache then by analysing assemblies.

RAM:

Myth: Increasing RAM will increase Visual Studio’s performance

I think that if Visual Studio is running out of memory then a RAM increase will help, but for us at work our RAM is not being fully utilized so on XP increasing our RAM won’t help us as the OS will not use it. On Vista however the OS endeavours to use as much free RAM as it can to cache and pre-allocate so it is possible this will help a little bit. I think the biggest myth about personal computing is that upgarding CPU and RAM makes the biggest difference. My computer at home is 4 years old and my computer at work is 6 months old. My computer at home that is 4 years old is faster in practical usage. If it came down to a number crunching war then the new computer would win but there is virtually no use case for that in personal computing.

Posted by: rhwilburn | February 15, 2009

Updating an item in a list without a reference with lambdas

I have to confess I am enjoying lambdas a bit much. I am making this post to show a cool way of avoiding code loops (there are still loops in CLR of course).

private void UpdatePerson(Person updatedPersonObject)
{
    var outOfDatePerson = _people
            .First(person => person.Id == updatedPersonObject.Id);
    int index = _people.IndexOf(outOfDatePersonObject);
    _people[index] = updatedPersonObject;
}

private void UpdatePerson_OldCSharp(Person updatedPersonObject)
{
    int outOfDatePersonIndex = 0;
    for (int i = 0; i < _people.Count ; i++ )
    {
        if (_people[i].Id == updatedPersonObject.Id)
        {
            outOfDatePersonIndex = i;
            break;
        }
    }
    _people[outOfDatePersonIndex] = updatedPersonObject;
}

From the two code samples it is worth noticing the difference in the number of lines and in the hierarchical nature of the code. The traditional C# for loop approach (the second method) leads me to cringe from a maintenance point of view. Each line of code is highly contextual and relies heavily on multiple levels of language constructs.

The first method (the lambda way) to me is much more readable and also maintainable. There is a flat hierarchy which is much easier to read as it doesn’t involve following the loop through code. I argue it is easier to maintain as the lines can change order more and will still be doing the same thing. It is also easier to update as there is less code.

Older Posts »

Categories

Follow

Get every new post delivered to your Inbox.