free geoip Jayson's Blog -
A conduit to the voices inside my head.

Jayson's Blog

  • Singleton Pattern Implementation in C#: One Global Object Instance, One Entry Point

    This post is going to explain how to implement the Singleton Pattern in .Net/C#. In most other programming languages/frameworks, global variables are allowed. In modern day programming this is extremely frowned upon, hence where this design pattern comes in handy: It provides a global object with only one point of reference. Once it is instantiated, all references to it are guaranteed to be to a single object instance which is available throughout the lifetime of the application.

    So, where would this be useful? Keeping an application-wide cache of objects to avoid expensive calls to non-local resources. .Net makes this fairly simple. Here’s the basic UML diagram for a singleton object:

    We create a static constructor (thus making sure only one object is created in the AppDomain) so the object can’t be created directly, a private backing store called instance of type of the singleton class, and a public accessor property (or method) that returns the private instance type. Your class must be declared as static (which implies sealed) otherwise subclasses can create new instances.

    I cannot repeat this enough: Global variables are evil. Global objects are not. .Net uses the singleton pattern for the classes contained in the System.Runtime.Caching namespace, and I suspect this pattern is used on top of the Flyweight pattern (another post for later) for String Interning within the .Net framework..In my experience, the singleton pattern comes in most handy for creating a global class encompassing a variety of collections…really, just a global cache of resources that are expensive to recreate on a regular basis (e.g. an object gets garbage collected, then has to be recreated on a regular basis). Usually this data should be largely static in nature, but using the classes in the Caching namespace, you can easily create a singleton object that maintains itself via callbacks, expirations, etc., which is something I routinely do in my applications: Create a global Cache object, write the plumbing for it to tidy itself up, keep a global instance…et voila, all of the tedious/expensive code to expensive resources takes care of itself. I’ll provide a further example of the caching pattern I’ve developed in a future post.

    Regardless, there are a couple of simple ways to implement this pattern in .Net. The first example is eager initialization, with a single lock check:and is thread safe:

       1: public sealed class Singleton
       2:  {
       3:      private static Singleton instance = null;
       4:      private static readonly object padlock = new object();
       6:      static Singleton()
       7:      {
       8:      }
      10:     public static Singleton Instance
      11:      {
      12:          get
      13:          {
      14:              lock (padlock)
      15:              {
      16:                  if (instance == null)
      17:                  {
      18:                      instance = new Singleton();
      19:                  }
      20:                  return instance;
      21:              }
      22:          }
      23:      }
      24:  }

    Note: Always create a separate threadlock object, don’t lock on the class instance itself as that’s just begging for a deadlock/race condition. Locking a static private object will prevent deadlocks since it will not allow new threads to access the object until the lock is released: Calling code can pulse/queue as much as they want, but until the lock is released, they have to wait.

    In .Net 4.0, it’s even easier to get thread safety and lazy instantiation via the Lazy<T> class:

       1: public sealed class Singleton
       2:  {
       3:      private static readonly Lazy<Singleton> lazy =
       4:          new Lazy<Singleton>(() => new Singleton());
       6:      public static Singleton Instance { get { return lazy.Value; } }
       8:     private Singleton()
       9:      {
      10:      }
      11:  }

    Very few lines of code, and we get thread safety, lazy initialization, and type safety. What’s the difference? It depends on what the object needs to acquire, and how expensive those resources are to acquire. I would lean towards lazy instantiation, mainly because I believe resources should be acquired as needed. A caveat though: code needs to be written to maintain the singleton’s references and memory usage. This tends to be a pattern that is overused in place of globals, and can be just as detrimental.

    Next post, a simple caching wrapper utilizing the singleton pattern.

  • Template Method Implementation in C#: An Easy Way to Make Your Code Hum Along

    A pet project I’ve been working on (on and off, time permitting) has been in need of some serious refactoring, so I finally sat down to eliminate some redundancy, and work on some design pattern work. A common problem in software design is making sure base class implementation is always called from overrides, but also deferring finer grained details to subclasses without changing the base class implementation, without having to always specify base.<implementation> in every single override in subclasses. Enter, the Template Method design pattern, which encompasses the polymorphic aspect of Object Oriented Design (which in my opinion is the most important of the 3 pillars: Encapsulation, Inheritance (aka Specialization) being the other two).

    The premise is simple, and here’s a very simple UML diagram that outlines the functionality:

    The base class specifies stubs (abstract methods, or protected virtual method implementations that all subclasses need base functionality for), and a public method that provides the “template” that must be followed. I’ll use a simple example for the sake of brevity. Let’s say you need a Data Access Object that connects to a database and fetches some data. The members common to all derived classes would be something like connecting to the database, then providing tidy cleanup code for the disconnect. Deriving classes would need to implement their own logic for fetching and processing the data, but all derived classes need to follow the same order of operations:

    1. Connect/Authenticate
    2. Fetch
    3. Process
    4. Disconnect/Cleanup

    This very simple example provides our template. So, our base class stub would look something like the following:

       1: abstract class DataAccessObject
       2:     {
       3:         protected string connectionString;
       4:         protected DataSet dataSet;
       6:         public virtual void Connect()
       7:         {
       8:             // Make sure mdb is on solution root directory
       9:             connectionString = 
      10:                 "provider=Microsoft.JET.OLEDB.4.0; " +
      11:                 "data source=..\\..\\..\\db1.mdb";
      12:         }
      14:         public abstract void Select();
      15:         public abstract void Process();
      17:         virtual public void Disconnect()
      18:         {
      19:             connectionString = "";
      20:         }
      22:         // The "Template Method" 
      24:         public void Run()
      25:         {
      26:             Connect();
      27:             Select();
      28:             Process();
      29:             Disconnect();
      30:         }
      31:     }

    Now we declare subclasses that implement the stub functionality of the abstract methods, Our base class will defer the fine grained details to the derived classes, but still guarantee that the core functionality is implemented. A simple class that selects a DataSet of Products from our fictitious database could look something like the following:

       1: class Products : DataAccessObject
       2:     {
       3:         public override void Select()
       4:         {
       5:             string sql = "select ProductName from Products";
       6:             OleDbDataAdapter dataAdapter = new OleDbDataAdapter(
       7:                 sql, connectionString);
       9:             dataSet = new DataSet();
      10:             dataAdapter.Fill(dataSet, "Products");
      11:         }
      13:         public override void Process()
      14:         {
      15:             Console.WriteLine("Products ---- ");
      16:             DataTable dataTable = dataSet.Tables["Products"];
      17:             foreach (DataRow row in dataTable.Rows)
      18:             {
      19:                 Console.WriteLine(row["ProductName"]);
      20:             }
      21:             Console.WriteLine();
      22:         }
      23:     }

    We could create as many subclasses as we need for various data fetching tasks, then from our main class, simply instantiate the specific subclasses and call the “Run()” method, which is a hook into our template. That would look like the following:

       1: static void Main()
       2:         {
       3:             DataAccessObject dao;
       5:             dao = new Products();
       6:             dao.Run();
       8:             // Wait for user
       9:             Console.Read();
      10:         }

    The beauty of this is that we are guaranteed the template behavior from all subclasses, and it makes our code much less brittle as we know that the inheritance chain will always return the desired implementation. If you combine this with Factory Method Pattern, you can start to harness some real power of polymorphic programming. But, that’s another post.

  • Visual Studio 2012/TFS 2012: A Breath of Fresh Air

    Visual Studio 2012 hasn’t been released to the general public yet, but a friend of mine was nice enough to lend me his MSDN copy of both VS and Team Foundation Server (I run Sharepoint 2010 on my intranet, which is a requirement for TFS…the integration is incredible). While you’re at it, do yourself a favor and install the new (and free) decompiler from JetBrains: DotPeek, which also integrates into Visual Studio. But, I digress.

    First off, I swore I would never migrate my source control over to TFS. For the better part of a decade, I’ve been using SourceGear’s Vault solution to house my code, and provide versioning control; the single license version is free. But after watching several webcasts on TFS 2012, I decided to take the plunge (getting it installed is not for the faint of heart by the way, block off half a day to get it up and running). It is leaps and bounds beyond any previous version of TFS, and the Sharepoint integration is nothing short of amazing, especially the reporting piece. The performance of the remote build server has increased drastically, and the client portion (Team Explorer) has much better integration into Visual Studio, and is more intuitive (VSS anyone?). I find it easier to use than Vault actually, so definitely a worthwhile plunge if you have the opportunity to do so.

    Visual Studio 2012: Wow. Just, wow. It’s hard to believe that we used to get programming done with Visual Studio .Net (or 2003, 2005, 2008, 2010). It is finally a mature product in this author’s humble opinion. This may sound silly, but thank you Microsoft for FINALLY including a dark theme! My eyes are quite grateful for that inclusion. And, thanks for bringing back some color to what was an extremely boring Metro-esque theme in the betas. The VS GUI is slick looking, and doesn’t detract from getting work done like previous versions. Also, Intellitrace is badass: Being able to unwind a stack trace on the fly is pure awesomeness. And everything just feels faster than previous versions. I will be uninstalling 2008/2010 soon for sure since they are just sitting on my machine chewing up disk space.

    Next on my list of new products to tackle: .Net 4.5, the new C# language features (async/await code candy generation keywords), which means I need to rip out some threading frameworks on pet projects. And the big one that’s looming over my head: SQL Server 2012 (and soon, Sharepoint 2013 and Office 2013). And certainly not least, Windows Server 2012, though I might hold off on upgrading my servers as I’ve been less than impressed with Windows 8 (Sidenote: If you are having Windows 8 woes, read this great article by Scott Hanselman on Windows 8 productivity), though it is growing on me…s-l-o-w-l-y, but that’s another post for another day.

    Microsoft have really dropped a lot of new products on us these past few months, Jayson has been a busy little bee trying to absorb it all. Alas, that’s the life of a software developer though, have to reinvent ourselves every couple of months or so. I’m still tackling F# in my spare time as I want to use F# for low level libraries in future projects (DAL/BL type stuff). F# has a huge learning curve, even though I come from a functional programming background…it’s a work in progress. So much to learn, so little time. Back to the books for this developer.

  • Adding DISQUS to Community Server Sites is awesome. Finally, a centralized location for comment conversations to occur. Plus, they manage all the comment spam for you. Here’s how to add it to Community Server blog (I have not done this for the forum section, but I assume it’s just as easy).

    In your theme folder, in themes\blogs\NAME\ you are using, find the post.aspx file and add the code supplied by disqus. just below the </CSBlog:PostAttachmentData> tag. Also, disqus doesn’t play nice with the default <!DOCTYPE> in Community Server, so change/add a META tag to <meta content='IE=edge' http-equiv='X-UA-Compatible'/> in the themes\NAME\Common\master.Master file.

    What disqus accomplishes is something I touched on in my last post: Consolidation of information on the web. I look forward to having a better way to keep up with discussions.

  • Are Personal Websites/Blogs Passé?

    I have a love/hate relationship with my personal website/blog. When I started this site almost 9 years ago, social networking wasn’t even in the vocabulary of the internet, and personal branding was a must have. Fast forward to 2012, and Twitter, Facebook, and LinkedIn are ubiquitous, and Tumblr is a great turnkey solution. I purposely left out Google+ because like so many other companies, they are way too late to the party. This website is a labor of love, but a little more laborious as of late than loving. Running a personal website is a lot of work: Hosting costs, infrastructure work (DNS entries, SLR’s, dealing with the daily deluge of comment spam, bug fixes, trolls…*sigh*).

    There are so many options out now, which also creates new problems: Store your content on one site, photos on another, and if you are a coder like myself, do we use CodePlex, GitHub, etc. for our code? How do we integrate all of these into one cohesive entity to brand ourselves now? And what about syncing all of our stuff amongst different networks? Sneakernet (aka thumb drives), or the pains that I’ve taken to enable folder redirection, offline file sync’ing, and my own internal SharePoint implementation, and paying out the nose for hosted Exchange Server for email/contact/calendar sync’ing amongst my literally dozens of devices?

    There are just too many moving parts these days. Which brings me to “the cloud”…it’s so confusing to get the cloud to play nice with one another. Where one solution excels, it lacks in other areas. All of the solutions combined ALMOST solve the problem, but not one single one does anything quite well. We’re going back to the thin client days, where our computer is just a screen that displays information. Mainframe days if you like.

    Sometimes I feel that all of this complexity has re-introduced us to the stone ages. Introducing all of these extra layers sets us back and makes more work than it solves. I spend so much time keeping up w/ disparate information sources, and my own infrastructure. So, the million dollar question is could there ever be one “site”/”network” to rule them all?

    As computer professionals we have to brand ourselves. I guess what makes me a little sad is that it’s not the name that matters anymore, or the work you put into the branding. But, the amount of disparity makes things worse. I have a twitter account (@jaysonknight) which is pretty much read only, I rarely tweet. And the amount of info I receive in my feed is way too much to keep up with. Facebook, of course…but that’s mainly for personal stuff. G+? A joke. LinkedIn is the most valuable of all my social networks as it helps pay the bills w/ contract/job leads.

    The internet has matured quite a bit, but is compounding the underlying issue: In the end, we just want to post content under one name. Whomever can solve that issue will be the next big thing. One domain, all content, and simple tools to enable publishing. I love the social networks, but I also feel they’ve set us back a bit. They’ve generified branding, and handcuff us to “their” way of doing things.

  • Guess What? I’ve Moved Again–Hello Lexington Kentucky!

    I just can’t seem to sit still lately. Just under a year after I moved back to Charlotte NC, I’ve picked up yet again and moved to Lexington KY. Whilst the IT market here is fairly small, it’s also quite focused and concise. And it’s just damn pretty up here as well: Horse country. There are probably more horses than people residing in this area, which is fine by me. So, here’s to a new life in new digs and loving every second of it. I’ll try to get this blog back on track at some point, but I’m not as all consumed by technology as I used to be. It’s all about being well rounded.

  • Back to the Daily Grind

    Time to fire this site back up after sporadic posting over the past couple of years. I’m back in Charlotte after my tenure in NYC, and am happy to be back home with my friends and family. I’ve also made my (re)debut into the IT realm after completing my studies at Columbia University. Coding for me is like riding a bike, and I feel as comfortable as ever sitting behind the wheel of Visual Studio, and I’m also ramping up on Sharepoint 2010 (it’s a different beast than MOSS 2007). Outside of Microsoft technologies, I’m in the process of learning Ruby, and in turn Ruby on Rails. So far I’m pretty impressed with Rails, and Ruby reminds me a lot of Smalltalk. One of the great things about Rails is that it forces MVC, and you can get a workable website up without writing a ton of code, and not much configuration (hence RoR’s motto of “Convention over Configuration.” I’m a strong advocate of stepping out your comfort zone, and in this case learning the RoR way of things will make me a better all around developer.

    So here’s to round 2 of my IT career. .Net 4.0 has some great new features such as thread safe collections and parallelism, and continues to become a better all around framework for GPP. And finally, my pet project for the year is to learn F# and incorporate it into some of my existing projects (can you tell that I prefer functional programming languages?).

  • Happy Seventh Blog Birthday To Me

    Seven years ago, I started this blog as an experiment; little did I know that after all this time I’d still be doing this. I haven’t posted nearly as much as I’d like since I got out of the IT industry, but it’s amazing how much has changed both in my life and the internet in general after all these years. I wouldn’t have it any other way to be honest. Who knows what the next few years hold in store for me…I’m looking forward to the journey though.

  • Windows Live Writer Beta

    It took me a couple of tries to get the new Windows Live beta package installed on my machine; the secret fix for me was to enable the Windows Firewall service (I disable it since I’m behind other firewalls), so if your install is failing, turn on the Firewall service. You can turn it off again after you’re done.

    The previous version of Windows Live Writer hasn’t worked on any of my machines for quite some time now, so it’s nice that the new version actually works again. I might actually start keeping up with my blog again, although in a completely new mode of content since my tech days are long behind me (professionally at least). If you want to test drive the new Windows Live Essentials beta, you can download it from here. The new Windows Live Messenger is worth the download alone in my opinion. Much more polished, and you can plug it into social networks like Facebook, etc.

    So let’s see if this new version actually works, and if it does look for more updates in this space. I have my blog linked to my FB notes, so this post should show up on my FB profile as well.

  • Matriculating Into Columbia University, Moving to New York

    I have the proud distinction of being able to say that I have been accepted to Columbia University (yeah, that Columbia...the Ivy League one) and will be finishing up my degree there. I'm still in shock that it's actually happened, that I get to fulfill my lifelong dream of attending an Ivy League institution...and Columbia at that which is IMO the coolest of the Ivies, namely due to its location in Manhattan. I have busted my ass over the past year in my studies, and it's great to see this hard work paying off. So long as all the logistics fall into place, I will be moving to the Morningside Heights neighborhood of Manhattan in early January to begin classes. All of my credits transferred, so I'll be enrolling as a Junior. I'm excited and apprehensive at the same time, but I have no doubt that this was meant to be. I have a philosophy of believing that things happen for a reason, and the more effortlessly they happen, the more they were meant to happen.

    And it would seem that I'm not the only one making a big move these days. My good friend Keyvan Nayyeri (Facebook profile) has also fulfilled a lifelong dream and is finally making it stateside to complete his Ph.D in Mathematics at the University of Texas: San Antonio. The internet sure does make the world seem awfully small sometimes, and the prospect of finally getting to meet this guy in real life is astounding. I'm so happy for him as I know he's wanted this for a long time now. I know he's going to do great, and I wish him the best of luck.

    Any readers of this blog (if there are any left actually) located in and around the NYC area, please feel free to drop me a line. Next post will be from the Big Apple!

< Previous 1 2 3 4 5 Next > ... Last »

Copyright © ::
External Content © :: Respective Authors

Terms of Service/Privacy Policy