Singletons

I was experimenting with C# 4.0’s parallel functions (specifically parallel.foreach) and I had problems with a database-file sharing permission exception last night. What’s funny is, that’s supposed to be impossible. The Database Server object was a singleton, which meant that you cannot instantiate more than one instance of the class.
Design Pattern: Singleton
Pattern Type: Creational
First Stated in: http://en.wikipedia.org/wiki/Design_Patterns_(book)
Description: Ensure a class has only one instance, and provide a global point of access to it.

I started with this code:
public static DataManager Instance 
{
get; private set;
}
static DataManager()
{
Instance = new DataManager();
}
private DataManager() { }

Fairy standard. Line 1 exposed the instance, lines 5-8 is an internal lazy initialization, and the last line prevented the consumer from initializing the class themselves. Can you guess how the program managed to get around this limitation? It turns out that my application is a bit too fast. I mentioned earlier that I used Parallel.ForEach to access the object: this means that every cycle of the for loop is done in parallel of each other. If I had at least two objects inside the ForEach, and there’s enough CPU and RAM remaining, they would both run at the same time- initializing the object twice.

Poking around the web for solutions, I found one that used a double-locking algorithm which (guess what?) locked the instance from other parallel threads.
private static volatile DataManager _Instance;
private static object syncLock = new object();

public static DataManager Instance
{
get
{
if (_Instance == null)
{
lock (syncLock)
{
if (_Instance == null)
_Instance = new DataManager();
}
}
return _Instance;
}
}

private DataManager() { }

Line-by-line: The first line uses a keyword that I haven’t seen since college: volatile. The keyword locks the the _Instance field until it is initialized and fully accessible. Next line (2) is a dummy field of type: object which we see again on line 10- basically, we’re avoiding a deadlock by making the object always accessible, which is only possible if we don't lock the type itself (DataManager) down. The other lines are self-explanatory: A lazy initialization and a constructor that blocks the consumer from initializing more objects.

I compiled the app and it looks like everything works as expected for now :) Until the next bug, ciao~!

Reformat

I’m planning to reformat my PC in a month or so (yes, I plan that far into the future) and I was collating the programs that I need to reinstall immediately. So far, Here’s the current list (In order of installation):

  1. Microsoft Windows 7 Ultimate x64
  2. Microsoft Security Essentials
  3. Google Chrome
  4. Update EVERYTHING (Security Updates, Drivers, Virus Definitions, etc.)
    • Install Microsoft Live Suite (Writer, Movie Maker, etc.)
  5. Microsoft Office 2010 Professional Plus
  6. Microsoft Visual C# 2010 Express
  7. Microsoft Visual Web Developer 2010 Express
  8. Microsoft Live Mesh
  9. Microsoft Fixit Center
  10. TortoiseSVN
  11. Adobe Acrobat Reader
  12. CutePdf
  13. Adobe Photoshop CS5
  14. Apple iTunes
  15. SPlayer
  16. BitTorrent
  17. 7-Zip
  18. Notepad++
  19. Orbit Downloader
  20. Wizards of the Coast Character Builder
  21. Masterplan

That’s it. I don’t think I missed anything.. well, I guess except the games stuff (Magic Workstation, Mass Effect 2, Dragon Age: Origins and PCSX2) =3

Favorite Author

I was trying out http://www.youtube.com/user/SearchStories and tried to create an online video-résumé that showcases my online presence- until I found out that i had none :( So instead, I change all of my names into my favorite author, tweaked it out a bit, and here’s the end result~! Enjoy :D

The quality sux though.. I hope they do something about it.. the original google search story looked so clean and high def~

Lazy ain’t Always Bad…

You can fire up Microsoft Word, type something up quick, save (and/or publish) then close the app down, in a couple of minutes. Only the relatively quick splash screen would force you to wait as the program loads before you can start writing.

As a developer, you should (as a rule) make your software as quick as possible, and one of the more popular tactics to do this is by delaying to load an object until you actually need it. You can see this approach in Microsoft Word: Behind the splash screen, the app loads only the necessary UI (the document view, the ribbon, etc.) and after everything’s good, shows it the user. Since the user doesn’t always need, say, the font dialog box, then it isn’t initially loaded. A click in the right button however, would load the form on the fly and show it to the user. This concept is called Lazy Initialization.

Design Pattern: Lazy Initialization
Pattern Type: Creational
First Stated in: Patterns of Enterprise Application Architecture
Description: Lazy Initialization is the tactic of delaying the creation of an object, the calculation of a value, or some other expensive process until the first time it is needed
    public class DataManager
{
private Server _ServerOne = null;
public Server ServerOne
{
get
{
if (_ServerOne == null)
this._ServerOne = new Server();
return this._ServerOne;
}
}
}

As you can see from the code above, first it checks if the object has already been initialized. If it is, then it hands over the already live object, but if not- then it initializes the object on the fly before handing it over. This means that the second time the object is needed, it would be quicker since you don’t have to initialize it again.

Now, before I hit publish on this post, I just want to say that the topic is not, in any way, connected to why there wasn’t a blog post yesterday =P I'll try to get two posts up today to make up for it~

Abstract Factories

I was designing an application’s Data Access Layer when I realized that the Objects that needed to be persisted can rapidly grow. This meant that I can’t use Binary or XML Serialization due to memory limits, but I can’t use a full relational database either since some of the objects needed to be stored in the memory for quick access. So my only options are memcached key-value database, a combination of relational (for long term data) and Binary/XML serialization (for short term data) or use Db4o plus a clever design pattern called “Abstract Factories”. Of course I went with the simplest path (for me, at least).

Problem: You need to persist (save to storage) a number of related objects.

Solution: You can use Abstract Factory pattern in conjunction with Db4o.

AbstractFactoryPatternExample

Design Pattern: Abstract Factory pattern
Pattern Type: Creational
First Stated in: http://en.wikipedia.org/wiki/Design_Patterns_(book)
Description: the abstract factory pattern provides a way to encapsulate a group of individual factories that have a common theme (eg. related to each other)

First, I encapsulated all of the Db4o stuff in the Abstract Classes. The abstract server factory act as the databases while the abstract client products are basically tables, or the enumerations of the abstract data. Now, why are all of them abstractions? So that when there’s a new database, you only need to inherit the ServerFactory and it automagically works~! Same goes for the other abstractions. In fact, you can add properties to the concrete data objects (eg. add quantity to OrangeData and/or price to GrapeData) and all of it would be persisted!

As you can see in the attached C# Console solution below, the actual business logic are totally oblivious to the Db40 stuff going on in the background, while all of the Server/Client/Data objects just inherited the Data Access Layer classes in the AbstractFactory+Db4o library. Tinker with the app, add properties to the Data, add more servers/clients and see how powerful this combination of technologies really are.AbstractFactoryPatternExample_Source2

Download Source Here: http://ow.ly/1zHeI
Download Release Here: http://ow.ly/1zHgv

Preface

This is the unedited, word-for-word Preface of my upcoming book “Fundamentals in Programming”. Also, all of this is true.

I was in my third year of high school when I first got my Playstation 1.

After obsessing for over a year about Final Fantasy and Metal Gear Solid, my dreams finally came true on my birthday that year. I cannot sleep the night before, and will not sleep the night after (Do not do this at home, kids.) The next year became a blur: I played a lot of role-playing games and strategy games, from Final Fantasy Tactics to Legend of Legaia to Valkyrie Profile. My grades did not suffer much- being a high school student, there weren't any challenging subjects, and my social life… well, I'm not exactly a people person. I have my gamer friends, and they are enough.

However, one game really got my interest: Final Fantasy 7. I obsessed over it for so long that the system timer of the game became red and got stuck on 99:99:99. My friends and I discussed for hours about which optimal characters, equipment and materia combinations to use, the side quests and unlockables, ways to solve the game differently, and so on. However, almost every argument came down to one rumor: How to make the heroine survive.

In the game, Aeris, the heroine, will die in the hands of Sephiroth, the main antagonist. However, several sites and forums in the internet hinted that there is a way to avoid it. That became our quest: our mission, THE mission, of my small group of friends. We scoured the web for information, big or small, about the said rumor. We posted in forums, we asked the chatrooms, we emailed everyone (even the creators of the game) to know more. We tried everything: opening specific treasure boxes, collecting specific items (in a specific order), going through the game with only one character, as fast as possible, etc., etc…

After I finished college, I realized: THIS is exactly what Programmers do.

No, not obsess over games. Programmers gather information, both right and wrong. We analyze the information, looking for clues and solutions. Then, after that, we will try every possible angle to solve the problem, and finish our mission. No matter how many dead ends, no matter what the odds are, or what manner of Sephiroth-of-an-algorithm you are facing, you will TRY everything to save Aeris.

In the end, we found out that it is impossible to stop Sephiroth from killing Aeris. Nevertheless, the journey to that conclusion was awfully fun, and well worth playing for 99:99:99 XD

Research Proposal, Part Deux

I was at a loss on what to describe at the "Scope and Structure" part of my research proposal, so I decided to skip and create my tentative table of contents and start from there.

After I composed the ToC (attached below), I immidiately realized that the book is a bit too complex. The beginning chapters was alright, but it progressed a bit too fast and finished with a couple of modules that the students wouldn't use until their undergraduate thesis (or in the industry, in the case of team programming). I thought about compressing it further, giving more breathing room in the first few modules, but then realized that I'm not writing the book just for the freshmen (first year students). If a student buys my book, then they'll use it until their last year in the colegio just because of multiple perspectives it presents to the reader.

So, the first draft of the proposal for my book "Fundamentals in Programming" looks like this:



I still have to iron out a few things before I pass it tomorrow, but I doubt it would be changed that much. Wish me luck, I hope this gets approved ^^ tommorow then~

Laid off

*sigh*

Just two days after I start this blog.. I am now officially unemployed. Tsk~

Well, I'll still continue my ongoing projects (even though I will no longer be paid for them now) and I'm hoping that I can find a better job in the future..

For my students, the teachers of the Colegio, and everyone from my life as a professor~ Sayonara =3 I will miss you.

Research Proposal, Part One

I’m currently typing up the research proposal for my book, “Fundamentals in Programming”. It’s fairly long (and boring), but I plan to post most of the juicy parts in this blog.

 

The first part of the proposal is the name of the worktext, and the name of the proponents. Unfortunately, I’m not the sole proponent of the book because I’m not yet a regular employee of the Colegio. Dr. Cory Rebong, however, is my boss (Institution Head) and agreed that she’ll be a proponent “in paper only” and left the whole project to me :D

 

The review of literature was focused on the lack of problem solving skills of freshmen students, as well as their difficulty in understanding abstract concepts such as Variables and Memory Addresses. My proposed solution to this problem is a brute force approach- from start to finish, all examples will be problem-solving. Also, the entire first chapter of the book is dedicated to modeling abstract concepts through the use of pseudocode and flowcharting.

 

I spent a great deal of time researching the literature for the proposal, and found that the book: Information and Beyond: Part I By Eli Cohen (the famous Book of Eli, yea?) contained a wealth of research, specifically I. Milizweska and G. Tan’s work (pg. 277) which they entitled “Befriending Computer Programming”. I also found that one of their references, E. Dunican’s Alternative Delivery Techniques for 1st Year Programming Courses, is very informative.

 

The needs analysis was straightforward, with a focus on the shortcomings of current programming books in the Colegio’s library. Most of the books are outdated with only one or two copies on the shelves.

 

I’ll discuss the proposed Scope & Structure of the book on part two~ I guess my self imposed 300-word limit is a bit too short :( Anyhow, see you tommorow, Oyasumi~!

Ohayo Gozaimasu!

No, I am not Japanese. But I am a teacher.

 

Welcome to my blog! I am Erik Gaius Capistrano, more known as Sir Erik, an IT/CS Professor of Colegio de San Juan de Letran – Calamba. Aside from teaching future programmers, I’m also an application developer specializing in .Net Technologies and Design Patterns.

 

Since this blog is supposed to be my professional blog, expect it to be filled mostly with topics concerning application development and teaching at the Colegio. I’ll occasionally post something personal, but if you really want to know about me, then I suggest you follow me on twitter.

 

Right now, I’ve got a LOT of free time since its summer vacation- however, I’m planning to write a book for the first semester and document the process here. Also, I have a pretty big side-project which I’ll reveal here soon (spoiler: It’s open source!) ^^

 

I guess that’s everything for my first post, I’m looking forward to writing and blogging again! Until next time, Oyasuminasai!