Time management and the call of procrastination

By Kenneth 'RabidDog' Clark at December 29, 2011 13:23
Filed Under: Work, Personal

Today I was feeling all flustered and had no idea why. It felt like I had stacks of work to do and didn’t know where to begin. Then half way trying to do something I felt like I had been working for hours on the same thing.

 

I took a step back and remembered a technique our scrum master has taught us called the Pomodoro technique. Yes I know it is old but I thought I would try it again. Now like any true geek I had to find an application that could do the timing (I know you can use any clock but I wanted a history of tasks done).

 

So I found a really cool Adobe Air application which has been developed free. http://code.google.com/p/pomodairo/. If you are one of the unfortunate Apple Mac users Winking smile a friend of mine uses http://pomodoro.ugolandini.com/

 

 

If you interested in reading more about the technic have a glance at http://www.pomodorotechnique.com/

 

Happy days!

TOGAF Level 1 Examination

By Kenneth 'RabidDog' Clark at December 14, 2011 22:31
Filed Under: Architecture, Work

 

It has been a long time coming. I put it off for way to long and then the expiration of the exam voucher started creeping up so a few weeks ago I decided to book the exam date and get on with it.

 

I will not lie, the stress levels were high. I found a few resources regarding revision and the best ways to prepare for the exam. I also found a significant number of practices test kindly provided by people also studying for the exam.

 

So I decided to adopt my own study still of notes and testing myself. The day before the exam my office was kind enough to give me the day off and I spent it behind the books. After a full 9 hours of studying (yes with breaks between) I went to Systema to blow off a bit of steam. I then arrived home, did some more revision, hit the XBox 360 for an hour and finished the revision.

 

This morning I headed out early and arrived at the exam center 40 minutes early. This allowed me another look at my revision cheat sheet before doing the exam.

 

Going upstairs I was greeted with some nervous faces also writing their exams. After waiting for everyone to arrive we sat down and began the process of registering and opening the test which comprised of 40 multiple choice questions.

 

I started the test and 15 minutes later was finished. Not to brag but I figured that if I didn’t know it, reading the questions over and over wasn’t going to help. So I answered the questions and waited for the results. by God’s grace alone I passed!

 

So now on to level 2!

Build now, make money later

By Kenneth 'RabidDog' Clark at November 09, 2011 10:31
Filed Under: Code, Work

After reading an interesting piece of market research around the general idea and reasons for building mobile applications, everyone always pointed out the fact that they wanted to make money off their applications, so I thought I would make an observation about it.

 

Firstly, money is needed. We need it to pay the bills, we need it survive, to remain clothed and to have a roof over our heads. There is definitely a very real need for money, I am not denying this. However if we look at successful online software products, very few of them first set out to make money. Their first goal was to attract a user base.

 

At the recent G|South Africa (Google South Africa) days, the key note speaker went a little into the methods that Google uses when building applications. He pointed out that the when presenting an idea, the last thing Google wants to hear is how you going to make money off it. The first thing they tell you to do is to get the users!

 

Why is this important? Well it is pretty simple really. If you don’t have people using your application, you won’t ever make money off it. If people cannot use the application without risk they won’t try it. Especially at the rate that applications are being released and the substandard quality of the product. I am incline to believe that the Apple App store is doing better just by virtue of the fact that people know they have quiet a rigorous quality assurance procedure.

 

So my advice to you is pretty much the same as Google’s. Build the application first. Release it for free, get the user base, then and only then try to figure out how to make money off it.

 

Just another point on the inability to monetize applications in South Africa through the Android Market. South Africa has some of the nastiest monetary policies in the world. Look how long it took us to get PayPal. So it is not because Google is not interested in South Africa, it is just incredible difficult to establish the mechanisms in South Africa.

A fool doesn’t learn from his mistakes, a smart man learns from his mistakes and …

By Kenneth 'RabidDog' Clark at November 08, 2011 21:08
Filed Under: Work

a wise man learns from the mistakes of others!

 

This is a list of things that I have learnt in my stint in the IT industry. I thought that everyone knew these things but as is often the case we take for granted the knowledge we have gained via experience.

 

Everyone knows better than you.

This might sound sarcastic but it is not. When you come fresh out of your studies you figure that University or College has prepared you for everything. Every eventuality, every possible problem until you walk into your first job. What you fail to realise is that while studying you have been given the perfect environment to build programs. You are the only person responsible for your projects. Things can be configured and set up as you please (unless the  assignment stipulates otherwise). Finally you never have to worry about the bottom line. By the bottom line I mean money. Sure you have to worry about marks but see how confident you are to make tough decisions that affect a companies bottom line. Listen to your peers, interact with them, make suggestions but be prepared to be corrected. You might very well have a good idea but it doesn’t fit the business problem. On the other hand you might have an idea that solves the problem. Business software development is a team effort. Be part of the team.

 

Learn when to keep quiet.

  1. Your opinion counts. Really it does. When you express it is a different story. There are times to speak and times to keep quiet. If you are not sure whether it is time to speak or time to be quiet then it is probably best to be quiet. Don’t be afraid to speak though but before you speak, formulate your questions. Think about what you want to say and what you are trying to get answered. When you do speak make it concise and to the point. Leave no room for ambiguity. Don’t ramble or speak for the sake of speaking. Nothing turns people of your statement, no matter how smart it is, quick than rambling or disjointed statements. I often remind myself “Light travels quicker than sound. That is why people appear intelligent until they open their mouths”.

 

Don’t get precious about your project.

This does not mean that you are to take no pride in your work! What this does mean however, is don’t get so attached to what you have done that you refuse to improve it because it wasn’t your idea. Perfection is obtained through iteration. Nothing screams insecurity more than an individual who gets defensive about their code. Never forget that a software project is a strange beast, it can turn at the drop of a hat, hence all the agile methodologies now prevailing. These are not fancy management techniques but techniques put in place to help negate the dynamic nature of business and the rigged nature of software development. If you believe you are right, converse with the individual claiming there is a better way to do it. Perhaps they might educate or their reasoning might illuminate and angle you never thought of. Then again, you might very well educate the individual point what they believe to be a problem out.

 

Be professional.

Ok seriously. We have been potty trained. All of us. We have all figure we were old enough to rule the world and we most definitely thought we knew everything at some stage or another. That being said, why is it that when we first walk into the work place we become a bunch of snivelling cry babies? If faced with a difficult situation, evaluate it. Don’t throw a temper tantrum when you don’t get your way. Always remember that your employer is your client. You are a service provider, nothing more, nothing less. Do you job and do it well. If faced with a difficult situation tackle it. This is not only in the code base but also interpersonal relationships. If you have a problem with a fellow employee resolve it amicably. You guys, after all, are going to be spending a significant amount of time together. Deliver what you commit to delivering.

 

Be disciplined with your work. Check it before you submit it. Proof read the document before you submit it. Take pride in your project. The reason I said project as opposed to work is because their is nothing stopping you from continually checking the quality of the project. If you are a more experienced developer and you identify issues don’t just bounce it back to the developer. Take them time to help them fix. I have noticed that a significant amount of errors are due to a lack of understanding as opposed to laziness or stupidity. In this dog eat do world we have created we forget that we should carry the weak. Enable someone not to make the same mistake again, actively promote developer growth and maturing as opposed to bullying. The sooner they can do your job, the sooner your work load can be lightened.

 

You going to have to wipe your own bum. 

I cannot tell you how often I have seen (and yes been one of them) guys sitting in their office fuming at the fact that they can’t do things better because their managers won’t let them. Remember that your working environment and your perception of it, rests completely in your court. If there is something you want changed and it doesn’t go against company regulations then change it. If you think there is something that will fix your development cycles and the risk is minimal to the project, change it. If there is a piece of code that you know can be better, or a piece of refactoring that would remove duplication without bubbling significant issues up the code chain then do it. Don’t expect your managers to hold your hands with everything. Be proactive. Identify issues and figure out how to solve them. There is nothing worse than someone that continually points out problems without a way to fix them. If you put yourself out there and make yourself noticed people will take notice. Don’t sit back and wait for things to happen. If you can improve things then do it. Just don’t step on toes or hurt people doing it. Hurting someone does not imply that you should not be honest with them. It implies that you should not be dishonest with them.

 

Fill the gaps you identify.

If you notice a gap, fill it. If you can assume a little more responsibility for the benefit of the team then do it. If the leadership needs help then provide it. Don’t just do what you told, do what you see is not getting done. Before you get all mad just take a minute and think about it. This statements does not mean working yourself to the bone. It means that if you can take up a little slack then do it.

 

It is a team effort.

As software development has matured so have it’s processes and methodologies. That being said, a significant number of old stable teams have been using a form of Agile before it became a catch phrase. Old stable teams have worked past all their teething issues. They have identified the optimal communication mechanism that they should use when addressing their team mates. They understand (you need to understand this so read it again if you have to) that the delivery of a section of the project is not the goal. It doesn’t matter how fantastic their piece of code is. If the project fails then the team has failed. Period. If your team does not produce the end result you have failed. Yes, don’t argue, no excuse, I don’t want to hear you did everything you were supposed to, you failed. End of story.

 

Be low maintenance.

By this I mean that you should be fluid. Adapt to your environments and situations. Look for ways to best fit in. Be a problem solver. Even if your solution is the best one, try and help. Refer to the first point though. There are ways to communicate your ideas without screaming and making a fuss. Don’t whine about things that annoy you, fix them or suggest ways to fix them.

 

Business is right.

Yes it is. Sure they know nothing technically but I got bad news for you. If business doesn’t make money, neither do you. As opposed to fighting business become an ally. Facilitate their requirements, even if they seem absurd. This doesn’t mean that they should dictate implementations or technology spaces. This just means that if they request a change then best we perform it. If they request a feature then best we create it. Business is an extremely competitive industry. Being first to market means a competitive edge. The more money business makes, the longer we get to keep our jobs. Lets work with them. The more flexible we are, I have seen this, the more flexible and understanding business becomes.

 

Get to know the network engineers.

This is something I learned very quickly because I used to be one of those guys. People, for some reason, see network and infrastructure engineers as the plumbers of the IT world. This could not be further from the truth. Remember that the machine you are working on, the telephone you use, the server you hosting on, the network transmitting all your data is because of these guys. If anything ever goes wrong you going to need them to help you fix it. If you are certain there is an issue with the network then take as much data as you can to the network guys so they can diagnose the problem quicker. It is absolutely incredible how busy they can become when you need them if you have been off towards them. I also find that network engineers are generally the funniest and comedic of any division in the IT industry. If you ever need a laugh, go chat to your network engineers.

 

I am sure there are more but this is all I can think of at this time. The reason I raised this is due to a discussion we had in the office today. If you want top excel then don’t be afraid to stand up and be counted. Fail fast, that way you can move onto the next thing. I have noticed that companies promote initiative even if the answer is not 100% correct. Believe in what you are saying, if you don’t then don’t put it out there. If you put your ideas out there expect them to get cut off. Be prepared to defend them but never defend them subjectively or emotional. Always back your statements up with facts or experience. If your idea doesn’t get accepted then don’t get down or think no one loves you. One day, grasshopper, you will have an idea that everyone loves.

 

If you don’t agree with the points above you will one day Winking smile As I always say, I am always right, most of the time.

Google Hackathon South Africa 2011–Why Facebook will pwn Google+

By Kenneth 'RabidDog' Clark at November 02, 2011 22:20
Filed Under: Code, Work

Well I must honestly say I was very disappointed. Perhaps I expected to much or didn’t know what a hackathon is about but I didn’t picture it being what happened today.

 

From wikipedia:

“A hackathon, a hacker neologism, is an event when programmers meet to do collaborative computer programming. The spirit of a hackathon is to collaboratively build programs and applications. Hackathons are typically between several days and a week in length. A hackathon refers not simply to one time hacks, but to a specific time when many people come together to hack on what they want to, how they want to - with little to no restrictions on direction or goal of the programming.” http://en.wikipedia.org/wiki/Hackathon

 

Let me walk you through the day. We got there and made ourselves comfortable. It was hosted at Wits university and the venue seemed pretty impressive and I prepared for a good time with like minded people. Then it started. First we got a presentation from one of the GTUG members (Google Technical User Group or something). The presentation made me feel like I was back in high school being subjected to an English speech that was not prepared before hand.

 

Then we moved on to a video call from one of the Google developers in the UK or somewhere. Myself and others spent most of the time lip reading what the guy was saying as we couldn’t hear anything! So you sit wondering what you missing and people started getting distracted and then the whispering and conversations start. Things are going down hill fast. Video call ends and then we move on.

 

Next we get what can only be described as a whirl wind trip through using OpenAuth presented in Ruby. I still cannot remember anything from the explanation other than the individual presenting was a Ruby expert of sorts.

 

Moving one we were issued with the orders to build something using the Google+ API. Cool! Lets get cracking. Start investigating the Google+ API and get the fright of my life. The API only supports read requests. I kid you not, the social application said to be Facebook’s major competitor only has read access via the API. WHAT! So I mean really how hard can it be to make an HTTP request, receive a JSON formatted response and render that data. This is where things get really interesting.

 

I was under the impression that a hackathon was an event where everyone starts from scratch and starts nailing things together. How wrong I was. It seems that terms in the software industry are nothing more than marketing hype. Upon beginning development I started noticing that groups were getting ready to deploy their applications. What is going on here? Well it seems that there where a few groups who had actually developed their applications prior to the “hackathon” and merely brought them along to present. Now, again, I am not sure if I am just the idiot, but I am certain the title of the event was hackathon not exhibition?  The event then proceeded to run an hour over time with myself and a few others extremely disillusioned about the entire event. Towards the end of the day I couldn’t help but look forward to being told the day was over so I could go home.

 

Sorry Google but I think you missed the mark with this one. Your Google+ API is wafer thin and offers nothing. If you are hoping to regain the traction you initially had I would recommend you start allowing developers to push and pull data from different applications and platforms. There is nothing that separates your social network site from Facebook and by virtue of the fact that the majority of the market is on Facebook, you really need to give people a reason to use Google+. I signed up for it with great expectations when it became available. Since then my usage has steadily decreased to next to nothing.

 

That being said, I am really hoping that the developers conference on Friday makes up for today because today was truly disappointing. That being said, the gapping holes in the API and client interfaces has given me an idea for a new open source project.

Object Relation Mappers (ORM) vs Stored Procedures

By Kenneth 'RabidDog' Clark at September 21, 2011 15:21
Filed Under: Code, Hibernate, Methodologies, nHibernate, Work, Architecture

Recently I was tasked with doing some investigations as to the best route to go. Now before you go getting all excited I am not going to be posting performance comparisons or declaring an outright winner. What I am going to point out is how to make the decision based on other factors.

 

As I was looking for feed back on the respective technologies it became very clear that this is a holy war that no one can win due to the emotional attachment to our egos and having to be right and the lack of really clear distinctions between the two.

 

First lets look at some basic best practise in writing maintainable software:

  1. Make code readable
  2. Use automated testing
  3. Use version control
  4. Ensure software is well designed
  5. Use less code
  6. Encapsulate
  7. DRY – do not repeat yourself
  8. Loose coupling
  9. Write unit tests

 

This is the essence of what I feel the articles in the reference section encapsulate. The primary reason for writing maintainable code (asides from having to maintain it) is to facilitate change. Businesses are becoming more dynamic and cannot afford to wait for months or years for the implementation of a vision they had. First to market is more important than ever with smaller businesses finding it easier to compete due to software and the internet.

 

Now the generally preferred structure of a software application is view layer, business logic layer and data layer. If designed properly one can very easily attach multiple views for different platforms to the solution without having to reengineer the business logic. The data stores can also be swapped out with relative ease or perhaps extended to include other data stores.

 

So what is a stored procedure? According to wikipedia: “A stored procedure is a subroutine available to applications accessing a relational database system. Stored procedures (sometimes called a proc, sproc, StoPro, StoredProc, or SP) are actually stored in the database data dictionary.”

 

Now the benefits claimed with using stored procedures have always been related to performance. It is a common belief that stored procedures run quicker than generated SQL. While this might be the case with an experienced writer, I have had the distinct displeasure of seeing it go horribly wrong as well. This does not mean that I have not seen it happen in code but generally it is easier to fix the code than the stored procedure due to the unit tests. When changing a stored procedure inevitably you are going to have to change code. When changing DB structure you will have to change all the procedures that use that dataset and the code that maps to it.

 

Now let us get out of the emotional stuff and start comparing apples with apples.

 

If we have a look at the the description above on how to write maintainable code let see how stored procedures match up.

 

  1. Make code readable – Well no, it is a structured query language. While it looks like bad English sometimes it can be difficult to read.
  2. Use automated testing – I haven’t seen a way to automate the testing of stored procedures
  3. Use version control – I have not seen a way to handle versioning of stored procedures with ease
  4. Ensure software is well designed – Being procedural in nature there is very little design that can happen
  5. Use less code – There are certain things you can do in code you can’t do in SQL. So you might end up having to write far more SQL to facilitate it.
  6. Encapsulate – While some might argue that the procedure is encapsulated in the database I would argue that the logic is not encapsulated where it should be.
  7. DRY – do not repeat yourself – With having to name tables and operations continually there is a great deal of replication happening
  8. Loose coupling – Can stored procedures be interchanged between database vendors? Well yes, if you haven’t used vendor specific functions. It is also tightly coupled to the database unfortunately.
  9. Write unit tests – I would if I could! Haven’t seen this in Stored procedures.

 

I am not going to run the code through the same assessment as we all know that code supports all the above. Right lets get into the next point. While stored procedures might perform better, does the saving from the performance increase compliment the additional cost of maintenance attached by using stored procedures? The next question we need to ask is this. How safe is it to have business logic reside inside the database as opposed to the code base? What the you had specific rules for the same entities in a database? You would have to replicate the initial procedure and fine tune it for each entity. Now should the shared logic change you have multiple places you need to go and change. Not good!

 

I am not going to go into data parity mismatching either as that is a seperate article all toghether! Just know that it is there.

 

Lets look at it from the other side. Yes generating SQL to query a database has a certain amount of overhead. That is the only concern that people have. Let me say that again, the only con that using code over using stored procedures has is the performance aspect. So what do we do? Well lets have a look at another definition: “"Premature optimization" is a phrase used to describe a situation where a programmer lets performance considerations affect the design of a piece of code. This can result in a design that is not as clean as it could have been or code that is incorrect, because the code is complicated by the optimization and the programmer is distracted by optimizing.”

 

Is this not what we are doing when we allow the decision to use stored procedures affect our system designs? How about we try this from now on. Lets write the application first, get it working properly (even if it is a single featureSmile) and release it. Once we identify bottle necks we begin to optimise the bottle necks. This might very well include using stored procedures! Lets get out of the dark ages folks. There is no right or wrong in this realm. There is only deliver on time or don’t. Lets deliver on time Winking smile Perfection is generally a refining process any way, expecting it on the initial iteration is absurd.

 

Just to clear up any ambiguity. This article does not serve to prove or disprove the use of SQL and stored procedures. The point of the article is to make you aware that using stored procedures needs to be handled the same as writing code, carefully, with a liberal serving of caution and most of all making sure that what you are gaining is worth what you spending to gain it. Store procedures have their place, as do ORM, procedural languages and hot dogs (in my tummy!)

 

References:

TOGAF Foundation day 1

By Kenneth 'RabidDog' Clark at September 19, 2011 19:08
Filed Under: Architecture, Work

What an interesting day. For a while now I have wanted to do some sort of certification in the enterprise architecture realm. Mainly because I want to see if what I say all the time is actually the case and having a certification proving you know what you talking about never hurts!

 

Well I was extremely pleased with day one of the two day training presented by http://www.realirm.com. The supporting documents are clear, there are no gaps in the presenters knowledge and the environment is fun and interactive yet professional.

 

I was very please to find that my ideas are correct but today also filled in a few gaps I have been struggling with. The thing that has become glaringly clear is that the role of enterprise architect is one often misunderstood. While a technical background is a good idea, a great deal of the initial work is done outside the context of any specific technologies. This is the part I absolutely love! Being presented with a problem or in TOGAF terms a “concern” then finding solutions to that concern. Problem solving is something I thoroughly enjoy, whether it be code based or business based.

 

Really looking to tomorrow and once I have finished the foundational aspect I will most definitely be doing the next level.

 

For more info on TOGAF check out:

http://www.opengroup.org/togaf/

 

Other interesting links

http://www.zachman.com/

http://www.isaca.org/Knowledge-Center/COBIT/Pages/Overview.aspx

http://www.itil-officialsite.com/

The importance of rigid definitions – or why a verbose explanation is sometimes a good idea.

By Kenneth 'RabidDog' Clark at September 14, 2011 00:20
Filed Under: C#, Java, Architecture, Work, Code

So I have been wiping the cobwebs from my Java skills and kicking myself for neglecting them. I suppose with work being focused on .NET development, two young children and a training schedule that leaves very little time for exploration on personal projects, it was bound to happen.

 

Anyway, things have changed now and I am able to squeeze in personal development time by sleeping less Open-mouthed smile. Right, lets get to the point of this article. While designing an API in Java I noticed that I was finding it very difficult to package my classes the way I was doing it in .NET so I started doing some digging.

 

My first thought was to have a look at the access modifiers available in both languages. Do a like for like comparison and see if there were any equivalents. So the C# language has the following access modifiers:

 

C#

  • Public: This is pretty much a free for all. The class can be accessed by everything inside the assembly and anything referencing the assembly. This applies to types and type members.
  • Private: This makes members of the class only accessible to operations in the definition of the class. Kinda like private parts Surprised smile
  • Internal: This allows the the types or type members to be visible from the within the same assembly. So even if a different assembly shares the namespace (for whatever reason) it will not be able to access the internal types or methods of the referenced assembly.
  • Protected: This is a member access modifier that dictates that only types that extend the declaring type can access this member. So a shared property, field, method or function that you want to be visible inside a type extending the type declaring the members but not available internally to the assembly or publically.

 

Right lets move on shall we?

 

Java

  • Public: Pretty much the same as C#. Free for all on everything declared.
  • Private: Again, pretty much the same as C# and the private parts.
  • No Access Modifier: This means that anything declared in the type or the type itself will only be visible in the package space it is declared in. Remember this! It is the topic of this post.
  • Protected: Available to types extending the declaring type.

 

Right lets get to the point of this article. Now that we have established each languages modifiers, lets have a look at this http://www.javacamp.org/javavscsharp/internal.html

 

Looking at that you will see that the C# access modifier “internal” is implied to be the equivalent of the Java default or no access modifier declaration. Does the Java definition behave the same as the C# internal definition? Well have a look at the definitions again:

  • C# Internal: Accessible to everything inside the assembly. This means namespaces moving up to the root namespace and down to the last namespace node.
  • Java No Modifier: Only available inside the package it is declared in.

 

Can you see it yet?

 

Lets have a look at a code sample real quick:

C# Code sample

//Assuming this is inside assembly my.cool.dll
namespace my.cool.project{
  internal class Cheese(){}
}

namespace my.cool{
    public class StartTheCheese(){
        var cheese = new Cheese(); //valid
    }
}

namespace my.cool.project.goes.on{
    public class DigestTheCheese(){
        var cheese = new Cheese(); //valid
    }
}
//end assembly

//Assuming this is inside assembly my.ref.dll
namespace my.cool{
    public class DoWeHaveCheese(){
        var cheese = new Cheese(); //invalid
    }
}

Java Code Sample

package my.cool.project

class CatchMe(){ // note that no access modifier is declared
 //body
}

package my.cool

public class TheCheese(){
    CatchMe catchMe = new CatchMe(); //fails!   
}

You can see it now right? The primary, intrinsic difference is that the C# internal modifier can span multiple namespaces in the same assembly. The Java declaration with no access modifier cannot be seen outside the package my.cool.project. This means that there is no equivalent “internal” in Java. So here is the crux of the matter. If making comparisons, like in maths, we have to find the lowest common denominator before comparing or performing operations of logic in deciding the equivalents. Compare apples with apples to avoid confusion. Things we might take for granted will drive other people mad!

 

References:

Java porting and the Date string conspiracy

By Kenneth 'RabidDog' Clark at September 13, 2011 00:10
Filed Under: Work, Java

It has been a while since I have been able to write some Java code outside the context of Android. So I decided to take my C# NewsFeedParser (https://github.com/RabidDog/C--News-Feed-Parser) and port it to Java just as an exercise. While I have just finished the RSS content parser I have also picked up a few issues with the C# version so will be cleaning that up soon.

 

Most of the concepts where the same but I must admit, I missed the internal key word available in C# Smile. I still have to do a few tests to verify that I haven’t accidentally exposed anything in the library.

 

The one thing that was a bit upsetting is Java’s handling of date strings. The parsing of date strings requires a format to be stipulated if you are using the framework parsing mechanism. Examples can be found at http://techtracer.com/2007/03/28/convert-date-to-string-and-string-to-date-in-java/ and http://javatechniques.com/blog/dateformat-and-simpledateformat-examples/ and many other places on how to parse a date using a format. While this works when you have control of the format, it can be quiet tricky when you don’t have control over the format.

 

A bit more searching led me to http://stackoverflow.com/questions/3389348/parse-any-date-in-java and then a little piece of gold. http://darthanthony.wordpress.com/2009/05/29/java-date-parsing-with-an-unknown-format/ pointed to a project called the POJava Project. The article also pointed out that there is a handy DateTime object that has the capacity to parse dates from most strings.

 

Usage is something like

import org.pojava.datetime.DateTime;

//rest of the class definition
Date date = DateTime.parse(myDateString).toDate();

 

So now you can parse many strings into date objects. Big thanks to the guys over at the POJava project. You can find them at http://www.pojava.org/.

 

Time to go clean up the C# project Smile

Razor Engine, more than just web pages

By Kenneth 'RabidDog' Clark at September 06, 2011 00:37
Filed Under: C#, Code, Work

Will working with a pet project I came across the need to populate a standard message with certain data values. Enter templating.

 

First thing anyone might do is add the templating mechanism to the message distribution stack. I take a slightly different stance on this. I believe the message distribution stack should have no knowledge of the templates being used. All it should effectively do is distribute the formatted message according to the specified communication channel.

 

Classes

 

This means that the piece of code creating the message would have to assign the formatted body to the message object. Something like this:

 

Message myMessage = new Message{
    From = "from@domain.com",
    To = "to@domain.com",
    Subject = "My Subject",
    Body = "This is where my super long message that needs to be formatted will go"
};

MessageGatewayFactory.CreateGatewayInstance(MessageType.Email).SendMessage(myMessage);

 

As you can see the Body is is looking a bit smelly. This could be rectified by using an external resource. Good idea! The problem is that we might (well probably) will have to add dynamic data to the body.

 

So I started researching some templating solutions. There are some really heavy weight solutions out there. I didn’t want anything heavy weight though and I wanted to use the Razor Engine. My travels led me to a project called Fluent Email. A write up of the project can be found here http://lukencode.com/2011/04/30/fluent-email-now-supporting-razor-syntax-for-templates/

 

When running through the examples and having a look at the code I noticed that it did everything I needed it to do but not in the fashion I wanted it done. Don’t get me wrong, this project has a great deal of potential and will prove very useful to many projects, it just wasn’t exactly what I was looking for. Digging a little deeper into the source I found the Email class which contained a method to parse a Razor formatted string template and a method to read a Razor formatted file of the disk. BINGO!

 

So I extracted the two methods and went ahead and changed them accordingly and lined them up with some best practises. This is what came out:

 

Template

 

and the code looks something like this (remembering our DRY principle Winking smile)

 

Our Interface definition:

public interface ITemplateParser{
    string ParseFromFile<T>(string fileName, T model);
    string ParseFromString<T>(string template, T model);
}

 

Parser factory:

public static class ParserFactory {
    public static ITemplateParser TemplateParser {
        get { return new RazorParserImpl(); }
    }
}

Parser implementation:

class RazorParserImpl : ITemplateParser {

    public RazorParserImpl(){
        InitializeRazorParser();
    }

    /// <summary>
    /// Parses from file.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="fileName">Name of the file.</param>
    /// <param name="model">The model.</param>
    /// <returns></returns>
    public string ParseFromFile<T>(string fileName, T model){
        var path = GetPath(fileName);

        using (var textReader = new StreamReader(path)){
            var template = textReader.ReadToEnd();
            return ParseFromString(template, model);
        }
    }

    /// <summary>
    /// Parses from string.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="template">The template.</param>
    /// <param name="model">The model.</param>
    /// <returns></returns>
    public string ParseFromString<T>(string template, T model){
        var result = Razor.Parse(template, model);
        return result;
    }

    //Some weirdness pointed out by lukencode. Will be validating this further when I get a chance
    /// <summary>
    /// Initializes the razor parser.
    /// </summary>
    private static void InitializeRazorParser(){
        dynamic temp = new ExpandoObject();
        temp.PlaceHolder = String.Empty;
    }

    /// <summary>
    /// Gets the path.
    /// </summary>
    /// <param name="fileName">Name of the file.</param>
    /// <returns></returns>
    private static String GetPath(string fileName){
        const string tilde = "~";
        var baseDir = string.Empty;

        if (fileName.StartsWith(tilde)) {
            baseDir = AppDomain.CurrentDomain.BaseDirectory;
            fileName =  fileName.Replace(tilde, String.Empty);
        }

        var output = Path.GetFullPath(baseDir + fileName);

        return output;
    }
}

Usage

//Previous look ups left for brevity
var body = ParserFactory.TemplateParser.ParseFromFile("~/Templates/MyTemplateFile.cshtml", response.Profile);

var response = messageManager.SendMessage(new MessageRequest {
            Body = body,
            MessageType = MessageType.SayHello,
            Subject = "Just popped in to say hello",
            ToId = id
        });

 

I decided to define the template parser as an interface to allow expansion on parser and templating engines at a later stage. When this comes about, obviously I will have to change the factory method to return the correct implementation. Yes it might be over kill for now but lose coupling is something I try do from the beginning.

 

I did submit these changes to the project in case you where wondering. When testing it in the scenarios I needed it in it worked really nicely. I really big thanks to the original author!

 

Hope you find it useful as well.

 

References:



I am South African. Always have been always will be. I love my country. I love my wife and two children.


I also really enjoy solving problems. I currently work as a Software Architect exploring new solutions for business problems. Having been round the block a few times I enjoy showing new developers how best to solve problems, how to find answers and how to approach solution development.


In my spare time I enjoy riding my super bike, training in Systema and horsing around with my family.


Month List

Visitors

Twitter Feed

6. February 18:01
Unit tests don't check if code works. They PROVE the code works!

12. January 23:34
@Annaling horrific. People like that should face sever punishment. Unless of course they tried to find the cat :(

12. January 08:28
@Annaling to fix cat problems u need a dog :)

9. January 15:34
@UnexpectedPippa my boy is 2. They rock! My daughter, son and myself have endless fun with them!