Tuesday, November 30, 2010

Add and Remove events programmatically in JavaScript

Here are a couple of functions to add and remove events in JavaScript.

var DeveloperCaster = {
            AddEvent: function (id, _event, _function) {
                _object = $(id);
                if (_object.addEventListener) {
                    _object.addEventListener(_event, _function, false);
                } else if (_object.attachEvent) {
                    if (_event.length > 2) {
                        if (_event.substring(0, 2) != "on") {
                            _event = 'on' + _event;
                        }
                    }
                    _object.attachEvent(_event, _function);
                }
            },
            RemoveEvent: function (id, _event, _function) {
                _object = $(id);
                if (_object.removeEventListener) {
                    _object.removeEventListener(_event, _function, false);
                } else if (_object.detachEvent) {
                    if (_event.length > 2) {
                        if (_event.substring(0, 2) != "on") {
                            _event = 'on' + _event;
                        }
                    }
                    _object.detachEvent(_event, _function);
                }
            }
}

How to use it:
Example 1:
<script language=”javascript”>
function myTestFunction(){
       alert(‘Clicked’);
       DeveloperCaster.RemoveEvent('mybutton', 'click', myTestFunction);

}
window.onload = function () {
       DeveloperCaster.AddEvent('mybutton', 'click', myTestFunction);
      
}
</script>
<input id=”mybutton” value=”click me” type=”button” />



Example 2:
<script language=”javascript”>
window.onload = function () {
       DeveloperCaster.AddEvent('mybutton''click'function(){
           alert('Hello World');
       });
      
}
</script>
<input id=”mybutton” value=”click me” type=”button” />

WP7 gets Visual Basic support

Microsoft released Visual Basic for Windows Phone Developer Tools early this week.
Microsoft stated, "This release doubles the developer audience for Windows Phone, by enabling Visual Basic developers to create applications for Windows Phone, as well as C#". This release is available in English, French, German, Italian, and Spanish. However, it  is currently only for Silverlight projects; the tools do not support projects built on the XNA Framework.


Download Tools Here

JavaScript dollar sign function ($)

If you have been working with JavaScript in recent years you may be aware of the wide used of the dollar sign function. Generally, the dollar sign function is use as a shortcut to document.getElementById and document.getElementByName; however, it can be use for anything. So here is the version of the dollar sign function that I will be using in other JavaScript examples within this blog.



function $() {
    var elements = [];
    var e = null;
    for (var i = 0; i < arguments.length; i++) {
        var element = null;
        var arg = arguments[i];
        if (typeof arg == 'string') {
            element = document.getElementById(arg);
            if (element === null) {
                element = document.getElementsByTagName(arg);
                if (element.length == 1) {
                    element = element[0];
                }
            }
            if (element.length === 0) {
                element = document.getElementsByName(arg);
                /* note: IE does not return this as an array so only the first element
                in the collection (only if more than one exists) will be accessible.*/
                if (element.length === 1) {
                    element = element[0];
                }
                e = element;
            }
        } else {
            element = arg;
        }
        if (arguments.length == 1) {
            return element;
        }
        if (element !== null) {
            elements.push(element);
        }
    }
    return elements;
}



Usage
Accessing an element by id:
document.getElementById('id').innerHTML = 'Hello World';
With the dollar function would be:
$('id').innerHTML = 'Hello World';


Accessing an element by name:
document.getElementByName('name').innerHTML = 'Hello Tokyo';
With the dollar function would be:
$('name').innerHTML = 'Hello Tokyo';


Accessing more than one element at a time:
for (var i = 0; i < 2; i++) {
           $('name1', 'name2')[i].innerHTML = "test";
}




Compress this code here

Saturday, November 27, 2010

How to add multiple functions to the windows.onload method in JavaScript

  How to add multiple functions to the windows.onload method.
  var DeveloperCaster = {
            OnLoad: function (_function) {
                var _current = window.onload;
                if (typeof window.onload != 'function') {
                    window.onload = _function;
                } else {
                    window.onload = function () {
                        if (_current) {
                            _current();
                        }
                        _function();
                    };
                }
            }
        };


How to use it:
<script language="JavaScript">
   DeveloperCaster.OnLoad(function () {
            alert('Function 1');
        });

        DeveloperCaster.OnLoad(function () {
            alert('Function 2');
        });
</script>

Thursday, November 25, 2010

How to get the querystring value in JavaScript

Unlike most server side programming languages, JavaScript doesn't provide a standard way of parsing these values. I have tried a couple of different methods of doing it including regular expressions; however, I decided to opt out of regular expressions because I could never get it the way I wanted it.

So after a while I came out with this function:

  var DeveloperCaster = {
            QueryString:function(key) {
                var address = window.location.href;
                var args = address.split("?");
                if (args.length == 2) {
                    var arg;
                    if (args[1].indexOf("&") != -1) {
                        arg = args[1].split("&");
                        if (arg.length > 0) {
                            for (var i = 0; i < arg.length; i++) {
                                var sArg = arg[i].split("=");
                                if (sArg.length > 0) {
                                    if ((sArg[0] == key)) {
                                        return sArg[1];
                                    }
                                }
                            }
                        }
                    } else {
                        arg = args[1].split("=");
                        if (arg.length > 0) {
                            if ((arg[0] == key)) {
                                return arg[1];
                            }
                        }
                    }
                }
                return "";
            }
        };

How to use it:

<script language="JavaScript">
   if (DeveloperCaster.QueryString("Param").length > 0) {
            alert(DeveloperCaster.QueryString("Param"));
   } 
</script>

Wednesday, November 24, 2010

F# has been released under the Apache 2.0 License

You know F#, the functional programming language aimed to .NET developers. What is functional programming you may ask? Well that's another blog post. It seems that Microsoft has decided to release the source code of the F# compiler along with the core library under the Apache 2.0 license; however, it is just a code drop which means that there won't be any collaborative interaction between the F# team and the community.

You can download it at: http://fsharppowerpack.codeplex.com/

Named And Optional Parameters in C# 4

Optional Parameters

Optional parameters have been added to C# 4 (released earlier this year). I've seen many developer claiming for this feature since VB.NET had it; yet, I always felt more comfortable using method overloads and I am not debating that.

Optional parameters allow us to set a parameter default value.

Example:

public static void ProcessFeed(int id,string feed = "default",bool isValid=true)
 {
           //TO DO:
 }

When calling this method will get:


Example 1:
ProcessFeed(1,"myfeed",false);


Method will get the following values:
  id = 1
  feed = "myfeed"
  isValid = false


Example 2:
ProcessFeed(2);



Method will get the following values:
  id = 2
  feed = "default"
  isValid = true

Named Parameters

Named parameters allow us to skip parameter that have default values. 
For example, if we want to use the default value of feed but change the value for isValid we would have to call the following:

Example 3:
ProcessFeed(3,"default",false);

or we can use named parameters which will make give us a cleaner sintax.

Example 4:
ProcessFeed(3,isValid:false);









Tuesday, November 23, 2010

Android WebView - Clear The Cache

I have been asked a couple of times how to clear the cache from a WebView on an Android application. I will briefly explain the approach I am currently using:

You need to implement two methods one to retrieve all the cache data and one to delete each directories we find  cache (technically you could do it in one method but I prefer two).

Method to delete cache file(s):


  public static boolean DeleteDirectories(File d) { 
   String[] children = d.list(); 
   for (int i = 0; i < children.length; i++) { 
   boolean success = DeleteDirectories(new File(d, children[i])); 
   if (!success) { 
    return false; 
   } 
   } 
    return d.delete(); //Delete empty directory
    


Method to retrieve all directories from cache to delete:

public static void DeleteCache(Context context) { 
     try { 
    File d = context.getCacheDir(); 
    if (d != null && d.isDirectory()) { 
    DeleteDirectories(d);  
   
     } catch (Exception e) { 
        // TODO: handle as you please 
    
     } 



I normally call these methods when the user abandons the application by overriding the onDestroy() method in my main activity.

Example:

  @Override 
    protected void onDestroy() { 
     super.onDestroy();  
   try { 
DeleteCache(this);  
   } catch (Exception e) { 
       // TODO: handle as you please
   } 
    }

C# Anonymous Type

Anonymous types may be most notably being used by the JavaScript community but they have been around C# since .NET 3.0.

Here is an example of how to declare an anonymous type in C#:

var Person = new { FirstName ="Walter", LastName="Soto" }

//Print it to the console
Console.WriteLine(Person.FullName);

The compiler will then create the object at compile type (not at runtime).

Free JavaScript Compression Tools Online

Here is  list of cool free JavaScript compression tools available online.
  1. YUI Compressor - Yahoo's offering is widely regarded as the top compression tool.  YUI Compressor is written in Java (requires Java >= 1.4) and relies on Rhino to tokenize the source JavaScript file. 
  2. YUI .NET ports - A C# port of Yahoo's tool; really good option if you are a C# programmer.
  3. JSCOMPRESSOR - A handy web front end to the YUI.NET project.