Monday, December 6, 2010

The singleton pattern in C#

In software engineering, the singleton pattern is a design pattern used to ensure that an object has only one instance and provide a centralize point of access to itself. This pattern is needed when exactly one object is needed to coordinate actions across a system.

Example 1 – Generic singleton object:
A basic singleton object using lazy initialization (the object is not created until it is needed)
  public class MySingleton
    {
        private static MySingleton _instance;

        private MySingleton()
 {
 }

        /// <summary>
        /// Create an instance
        /// </summary>
        /// <returns>MySingleton</returns>
        public static MySingleton Create()
        {
            if (_instance == null)
            {
                _instance = new MySingleton();
            }
            return _instance;
        }
    }

Usage:
MySingleton o = MySingleton.Create();

Example 2 – Static singleton object:
A static singleton object does rely on the .NET CLR to initialize itself. A static singleton class needs to be sealed to ensure it won’t be derived.  This implementation also satisfies the design pattern; however, we lose some control over how our instance is initialized.
public sealed class MyStaticSingleton
{
        private static readonly MyStaticSingleton instance = new MyStaticSingleton();

        private MyStaticSingleton()
        {
       
        }

        public void SomeMethod()
        {

        }

        public static MyStaticSingleton Instance
        {
            get
            {
                return instance;
            }
        }
}

Usage:
MyStaticSingleton.Instance.SomeMethod();

Example 3 – Thread safe singleton object:
If our singleton object will resided in a multithreaded environment we will need to find a way to ensure that only one instance of our object will be created (in the presence of multiple threads).
The recommended solution for this problem is to use a Double-Check locking (http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html) .  By using the lock block in C# we ensure that only a single thread enters the initialization area.

    public sealed class MultiThreadedSingleton
    {
        private static volatile MultiThreadedSingleton _instance;
        private static object _safeobject = new Object();

        private MultiThreadedSingleton()
        {
       
        }

        public static MultiThreadedSingleton Create()
        {
                 if (_instance == null)
                 {
                    lock (_safeobject)
                    {
                        if (_instance == null)
                        {
                            _instance = new MultiThreadedSingleton();
                        }
                    }
                 }

                    return _instance;
        }

    
    }


Thursday, December 2, 2010

Parse an RSS feed using Java



Here is a quick example of how to parse an RSS feed in Java. It may come handy when doing Android or Web apps.
The following example is being implemented as an static method in a console application; however, for a real project you may want to create a set of classes to provide a more OO approach.

private static void Rss(String feed) throws ParserConfigurationException,IOException, SAXException{

              URL url = new URL(feed);
              HttpURLConnection conn = (HttpURLConnection) url.openConnection();
              if(conn.getResponseCode() == HttpURLConnection.HTTP_OK){
                    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                    DocumentBuilder db = dbf.newDocumentBuilder();
                    Document doc;
                    doc = db.parse(url.openStream());
                    doc.getDocumentElement().normalize();
                    NodeList itemLst = doc.getElementsByTagName("item");
                   
                    for(int i=0; i < itemLst.getLength(); i++){
                         
                          Node item = itemLst.item(i);
                          if(item.getNodeType() == Node.ELEMENT_NODE){
                                Element ielem = (Element)item;
                                NodeList title = ielem.getElementsByTagName("title");
                                NodeList link = ielem.getElementsByTagName("link");
                                NodeList description = ielem.getElementsByTagName("description"); 
                                                              
                                System.out.print(title.item(0).getChildNodes().item(0).getNodeValue());
                                System.out.print("\t\n");
                                System.out.print(link.item(0).getChildNodes().item(0).getNodeValue());
                                System.out.print("\t\n");
                                System.out.print("\t\n");
                          }
                         
                    }
              }

 }

Usage:
Rss(“http://rss.cnn.com/rss/cnn_topstories.rss“);

Output:
Clinton hits phone to patch relations    
http://rss.cnn.com/~r/rss/cnn_topstories/~3/VBH1WQQ1mAI/index.html     
     
The secret life of Julian Assange  
http://rss.cnn.com/~r/rss/cnn_topstories/~3/4gGd2WPMSaE/index.html     
     
House to vote on Bush tax cuts     
http://rss.cnn.com/~r/rss/cnn_topstories/~3/c2AgZMKetoo/index.html

Round double number to two decimal places in Java

Round a double to two decimal places in Java

 private double TwoDecimalRound(double d) {
      try{
            DecimalFormat twoDForm = new DecimalFormat("#.##");
            return Double.valueOf(twoDForm.format(d));
      }catch(NumberFormatException ex){  
            //TODO: handle error
      }
      return 0;
    }

Wednesday, December 1, 2010

Create And Read Cookies In JavaScript

Cookies in JavaScript can be manipulated via the document.cookie object so to make life easier I've been using the following functions.


JavaScript Code:


     var DeveloperCaster = {
            Cookie: {
                Set: function (key, val, days) {
                    var expires = "";
                    if (days) {
                        var d = new Date();
                        d.setDate(d.getDate() + days);
                        expires = "; expires=" + d.toGMTString();
                    }
                    document.cookie = key + "=" + val + expires + "; path=/";
                },
                Read: function (key) {
                    key = key + "=";
                    var c = document.cookie.split(';');
                    for (var i = 0; i < c.length; i++) {
                        var con = c[i];
                        while (con.charAt(0) === ' ') {
                            con = con.substring(1, con.length);
                        }
                        if (con.indexOf(key) === 0) {
                            return con.substring(key.length, con.length);
                        }
                    }
                    return "";
                },
                Remove: function (key) {
                    DeveloperCaster.Cookie.Set(key, "", -1);
                },
                Accepts: function () {
                    var _cookie = '_developercaster_cookie_test_';
                    DeveloperCaster.Cookie.Set(_cookie, '1', 1);
                    if (DeveloperCaster.Cookie.Read(_cookie) !== "") {
                        DeveloperCaster.Cookie.Remove(_cookie);
                        return true;
                    }
                    return false;
                }
            }      
        };


Usage:
Setting a new cookie
DeveloperCaster.Cookie.Set("cookie_name", "cookie_value", 4); //4 days


Reading an existing cookie
DeveloperCaster.Cookie.Read("cookie_name");


Check if browser accepts cookies
if(DeveloperCaster.Cookie.Accepts()){
  
}

Compress this code here

Add and Remove CSS classes programmatically in JavaScript

Here are a couple of functions to add and remove CSS classes programmatically in JavaScript.
Note: Get $() function code here if needed.


var DeveloperCaster = {
            AddCssClass: function (id, className) {
                if ($(id).className.length <= 0) {
                    $(id).className = className;
                } else {
                  if ($(id).className.search(className) == -1) {
                     $(id).className = $(id).className + ' ' + className;
                  }
                }
            },
            RemoveCssClass: function (id, className) {
              if ($(id).className.length > 0) {
                 if ($(id).className.search(className) != -1) {
                   $(id).className = $(id).className.replace(className, "");
                  }
              }
            }
        }

Example of how to use it:


CSS
    <style type="text/css">

        .mystyle
        {
            border:1px solid #333333;
            width:100px;
            height:50px;
        }
    </style>

JavaScript


window.onload = function () {
    DeveloperCaster.RemoveCssClass('a', 'mystyle');
};


HTML
<div id="a" class="mystyle"></div>