Friday, November 11, 2011

Google+ C# client

After the hackathon, I noticed that the .NET realm is not covered by the current Google+ clients. This prompted me to write a client to facilitate the current APIs. It is strongly typed, easy to use and pretty handy. I have included basic tests to describe it’s usage. Currently it only supports the API Key. Next is the OAuth 2. Check it out if you get a chance http://ping.fm/BqNtL

 

Ciao

Tuesday, November 08, 2011

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

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.

Saturday, November 05, 2011

Google South Africa 2011–Developers day

Well after the experience of the hackathon I would be lying if I said I wasn’t nervous about attending the developers day. I decided to go anyways and give Google a chance to redeem themselves.

 

well the day didn’t start off very well although the venue was superb. The keynote address was nothing short of uninspiring. The next segment regarding Android development was just as uninspiring. Being at a developers day I was expecting a slightly more in depth presentation regarding Android and not the usual stuff you can pick up anywhere on Google. After the first presentation I decided I was going to ditch the Android track and proceeded to the Google Application Engine (GAE) presentation, hoping things would get better but not expecting it to.

 

Well I was wrong! The Google Application Engine presentation was superb. Opening my eyes to a span of horizons regarding the technology (which I am not going to get into now). With a smile on my face I proceeded to the next mobile presentation which covered some stats. The audience asked some absurd questions that took up  most of the presentation so I don’t think the speaker got to finish. I will get back to the questions in a second.

 

Once he completed his segment we started a code lab using HTML 5 and Google Chrome. YAY! Finally get to do some coding! It was super cool to code along to the presentation and watch the project start taking shape. At the end of the presentation we could finish the application and submit it. By submitting it we would put ourselves in line to win a Samsung Galaxy Ace (S5830). I proceed to keep my head down and complete the project.

 

Will working on the lab, the presentations continued around Google+ (eish) and some start up support project that Google is running with interviews and some inspiration stuff for those that are interested in starting their own business. Having tried this and failed miserably (due to some bad decisions on my part), I am fully aware of the pitfalls and pointers that these individuals were giving so I listened with half an ear. They have some fantastic ideas though, I am looking forward to seeing them come to fruition.

 

Anyways I carried on with the lab and finally finished it. Sitting around a friend of mine asked if I had submitted it for review. This was 20 minutes before the deadline! So I rushed off and had the guys have a look at the lab and they signed it off.

 

Anyways we got to the prize giving and two individuals grabbed what appeared to be two Samsung Galaxy S2 devices. Very cool! Then came the announcement for the winner of the Samsung Galaxy Ace. After going through the process of eliminating contenders, by God’s grace alone, I was chosen as the winner. I gladly accepted the prize but was then asked to demo the lab! I am not much of a public speaker, especially if I am unprepared but I did it anyway. I am not sure the audience understood what I was saying while running through the lab application but at least the one liner at the end got a bit of a chuckle. Oh and for the record, to all you Microsoft haters out there, my code lab was completed using Visual Studio 2010 and hosted on IIS 7.5. So there! Microsoft tools can also get the job done! The right tool for the job.

 

So all in all, the day was a success. Some surprises as to offerings by Google, who seem to also be adopting a cloud service offering and some really cool education regarding HTML 5

 

Thanks Google, for the time, the presentations and the prize. Only piece of advice I have is to perhaps include more labs, less rushed time slots and a little more food at lunch time Smile

 

As for the audience, I urge you to please formulate your thoughts before asking a question. Babbling along trying to create a question and sound intelligent at the same time just puts people to sleep. Make the question short and too the point. Give the speaker the opportunity to respond and leave it at that. Do not engage in a conversation with the individual, it is just rude and inconsiderate to the rest of the audience, if you want to explore your questions more in depth take it offline. Probably the most embarrassing moments for me (as a South African) was the questions around “What Google is going to do for the poor with regard to giving them mobile devices” and then the question regarding what Google was going to do about the fact that a 2 year old device wasn’t going to run the Android Ice Cream Sandwich (Android 4). Lets be honest here, 2 years in the technology space is a long time. I hate to admit it but it is. I also get upset with the fact that we toss out hardware like toilet paper but we cannot expect Google to make sure their Android OS is backwards compatible with the plethora of hardware vendors previous devices. Sure this was a Google Nexus device but let also not kid ourselves as to the maturity of the Android OS. It is a relatively new OS in the grand scheme of things and unfortunately if we are going to be early adopters these are the prices we are going to pay. Perhaps what we should do is petition the device manufacturers to work more closely together with Google.

 

Another thing to remember is that the more backwards compatible a piece of software is, the more bloated it will become. In the mobile space you cannot afford bloat. A mobile OS needs to be lean and tight. Doing only what it absolutely has to. With limited power we cannot go overboard the way we do with our personal computers. (This includes Mac)

 

Well I think I have pretty much covered everything and the next time I will 1) Prepare something for the Hackathon and 2) definitely attend the next developer day.Time to see if I can get a Microsoft developer day in somewhere as well Smile

 

Thanks again to everyone that made today what it was and I enjoyed meeting those that I did and those that I didn’t, well maybe next time Smile

Wednesday, November 02, 2011

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

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://ping.fm/XPwG6

 

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.

Thursday, October 06, 2011

Jenkins, Glassfish 3 and Windows 2008 R2

Right lets get cracking. First thing you going to want to do is grab the Jenkins files available at http://mirrors.jenkins-ci.org/. Select the package you looking for. The WAR file is the web application deployable to containers such as Tomcat or Glassfish. There is also a standalone version but seeing as I want to brush up my Glassfish skills I decided to grab the WAR file.

 

Now this is were I generally start getting extremely nervous. In my experience, deploying these things on app servers is always a nightmare requiring tweaking and additional work. So here we go.

 

In the Glassfish administration console, select the applications link. This will give you a list of currently deployed applications on the server. Right now I have zero Smile So, select the deploy button on the grid header, select the browse button and navigate to your jenkins.war file.

 

Once you have done all this you will notice that Glassfish has conveniently detected that it is a web application, suggested a context root and an application name. Select the the item “server” in the virtual servers list and make sure “Enabled” is checked. Proceed to select anything else you want the server to handle. I just want to get this deployed so I am going to keep it minimal. Once you are satisfied click the “OK” button on the bottom right of the page. I was pleasantly suppressed to see that the deployment went off with out a hitch! If successful you will be returned to the Applications list with jenkins listed there now. On the right of the grid you will see links to perform actions. Select the “Launch” link. This will take you to a web page giving you the URL for the http location and the https location.

 

Click the link you want and wait for jenkins to perform it’s initial operations. If all goes well, you will be presented with the dashboard to perform your configuration and maintenance.

 

Just as a side note, having been involved with Glassfish 1 and 2 then slacking off during development of 3 I must admit that the level of the application server has increased significantly! I am very impressed at how the admin UI has been fixed and the ease of use and deployment. Hats off to the development team.

 

Oh, just as point, for those that think they have to go buy super powered machines, this box is running 1GB RAM with one of the first AMD 64 bit processors and runs fine, so now need to empty the wallet just yet Smile Bear in mind that this is a personal machine so it isn’t subject to huge loads. Will do some stress testing and see where it gets me.

 

Other than that, have fun!

Glassfish 3 on Windows Server 2008 R2

First things first. Lets get the downloads out the way.

 

Go grab java 7 from http://www.oracle.com/technetwork/java/javase/downloads/index.html

Then go and grab Glassfish 3 from http://glassfish.java.net/public/downloadsindex.html#top (I went with the open source edition)

 

Install Java 7 (you only need to do this if you don’t have a JRE 6 or higher). Then you need to install Glassfish. Follow the prompts. I left the installation location the same (c:glassfish3).

 

Next thing you need to do is navigate to c:glassfish3bin. I had to open the asadmin.bat file and edit it. I had to change all virtual references to physical references (perhaps because the environment variables hadn’t been set yet)

 

Next thing, open a command prompt and navigate to c:glassfish3bin. We are going to create a domain now, you can do this by entering the command asadmin create-domain. This will walk you through the domain creation process. Once that is done you can run the command asadmin start-domain. To verify that the domain has started navigate http://localhost:4848 (or change the port to the admin port you stipulated). If you see the admin console everything is running 100%

 

Next post I am going to explore deploying Jenkins http://jenkins-ci.org/

 

References:

http://glassfish.java.net/public/downloadsindex.html#top

http://blogs.eteration.com/blog/?p=494

http://www.oracle.com/technetwork/java/javase/downloads/index.html

file:///C:/glassfish3/glassfish/docs/quickstart.html

Tuesday, September 27, 2011

SOAP Message validation in WCF

Well, after a bit more research it seems that Microsoft does support validating outgoing messages. It still doesn’t resolve the issues in my post (http://kenneth.gotcheese.co.za/post/Microsoft-cannot-stop-being-a-rebel.aspx) but does answer where Microsoft feels any validation should be done regarding SOAP. On one hand I agree with them but on the other I disagree. They allow for the INotify property if you enable data binding but they can’t enable the max length on field? Strange I know but I suppose they have their reasons!

 

Anyways, you are able to validate the outgoing message against the declaring XSD. Again this sounds fine but has a few issues, namely those around exposing the XSDs for public consumption. I suppose you could get round this via HTTP authentication but that means you have to push authentication backwards and forwards. The other option is to distribute the XSDs with the client proxies. I see that the Service Reference created in Visual Studio 2010 does exactly this (after rewriting your XSDs for you Smile).

 

To perform the validation you need to first create a client message inspector that implements the IClientMessageInspector.

 

Something like this:

public class MessageInspector : IClientMessageInspector


 



Once you have done that you need to implement the relevant methods (those that the interface declares).



 



The method we are going to focus on is the BeforeSendRequest method. In this method we will perform the validation using the XSD for the message. What you will need to do is check that the Message object is not a fault. If it is a fault return at this point. Next you want to get the Body of the Envelope. This can be achieved by calling GetReaderAtBodyContents()



var bodyReader = message.GetReaderAtBodyContents();


 



Next you going to need to get the XSD for your message. This might prove tricky if you have not got a naming convention that can be used to derive the name of the XSD. A way around this might be to load up the locations of the XSDs into a dictionary (perhaps even load all the XSD Schemas into that list so you can look it up via targetNamespace) but that I will leave to your imagination.



 



Once you have the body contents you open up the XSD file, load it into an XmlReader and read the XML document. If any errors occur, the callback method attached to the XmlReaderSettings.ValidationErrorHandler will be called.



 



First we configure the XmlReaderSettings:



var xsdPath = "pathtoyourfile.xsd;

using (var stream = File.OpenRead(xsdPath)) {

var schemaReader = XmlReader.Create(stream);

var readerSettings = new XmlReaderSettings
{
CloseInput = true,
Schemas = new XmlSchemaSet(),
ValidationFlags = XmlSchemaValidationFlags.None,
ValidationType = ValidationType.Schema
};


readerSettings.Schemas.Add("http://yournamespacehere.com", schemaReader);
readerSettings.Schemas.Compile();

//Attach to error event handler
readerSettings.ValidationEventHandler += new ValidationEventHandler(InspectionValidationHandler);
}


 



Then to validate the document you create an instance of a reader, attach the reader settings and read the document like so:



 



var wrappedReader = XmlReader.Create(bodyReader, readerSettings);

var startDepth = wrappedReader.Depth;

while (wrappedReader.Read())
{
if (wrappedReader.Depth == startDepth && wrappedReader.NodeType == XmlNodeType.EndElement)
{
break;
}
}


If there are any errors in the document they will be raised while reading and pushed to the callback handler.



 



For more information one solving this problem check out the references I found while solving it:



 



Microsoft cannot stop being a rebel.

Well they have done it once again. Microsoft has never been know to conform to what the world of software engineering classes as best practises. They are also known not to confirm to widely published standards.

 

This is true in their Internet Explorer browser (although with the new versions they seem to be getting there) and other products. Yes I know that is how they make money but it is also the way they are losing a great deal of potential customers.

 

I was investigating the SvcUtil tool earlier and was asked to figure out how to enforce the declarations in the XSD limiting the length of string values. Now it would make sense for a client to support this right? Well not according to Microsoft. The XSD.exe utility also doesn’t support doing this.

 

The ONLY reason I can figure Microsoft didn’t do this is because they believe that the service should truncate and enforce the maximum lengths of the strings being supplied. While this might have you nodding your head going “ah yes, well then they have a valid point” my next question to you is, why is that valid?

 

Sure the contract needs to be enforced on the server side, that is a given. If it is not enforced on the server side it is not really a contract is it? However, does this mean that we should allow huge sets of string data to be transmitted if the first 250 characters are going to be consumed? I don’t think that is viable as you are polluting a call that was probably designed to be as efficient as possible. Still not convinced?

 

Well let me throw it back to the consumer or client. If you are generating a client for a web service and you have not explicitly checked the XSD will you be aware of the restrictions? Well you won’t if you haven’t checked it. Then next thing is this. If the validation of those maximum lengths has fallen to the client to verify, how are you going to do that? How are you going to know that string you are submitting must only be a length of 200 characters? The only way you can do this is to verify that the restriction exists inside the XSD and then implement some sort of check on the field with a message letting you if the max length is exceeded.

 

While this might seem like a viable solution, I am incline to disagree. There is a significant amount of work attached to doing this and if the contract should change for what ever reason, you will have to go back and find all the places you have implemented this.

 

I will be contacting Microsoft with regard to this and try and figure out their thinking behind it and if there is a road map to fix it. Until then, if you have any ideas or suggestions please let me know.

Sunday, September 25, 2011

Airsoft AK 47 MS

YAY! I finally got myself an airsoft rifle care of the folks at http://www.kreature.co.za. Full metal so it weights roughly 3kgs which is really neat (don’t really enjoy the plastic ones that feel like I am carrying a water pistol). My initial impression is that it is pretty neat. It doesn’t quiet have the resonance our presence as the real one (but you can’t go around discharging AK 47s randomly unless you are in some North-African countries) but it seems to work cool.

 

Lets have a look at a couple pictures shall we?

 

First up the rifle with the two point sling mounted and the stock extended

IMG00081-20110925-1556

 

Pretty neat huh? Next we take a look at it with the stock folded (still with the two point sling)

IMG00083-20110925-1558

 

Right my next challenge was charging the battery. I found a really cool site that describes the formula for charging the battery. The formula goes like this:

 

(battery capacity (battery's mAh rating)/charger output (mA - usually written on the charger)) x 1.4(for NiCad batteries, 1.5 for NiMh batteries) = time (in hours).

You can view the rest of the discussion here : http://answers.yahoo.com/question/index?qid=20091013093650AAcTEBp

 

So I worked mine out and it needed 4 hours according to the formula. So I charged it for four hours and went outside to have some fun. The battery died in 5 minutes Sad smile

 

So I remembered that some batteries require a longer initial charge. So I gave the guys at Kreature a call and asked what the story was. Seems the Ni-MH type batteries require and initial charge of 8-12 hours! Ok well at least there is nothing wrong with my battery. So now it is plugged in again and this time I will leave it for 10 hours.

 

Anyways, still very excited to finally have it (been trying to get one for over a year now!) so waiting a few more hours ain’t going to kill me. Now it is time to start finding some games!

Thursday, September 22, 2011

JavaScript Hashmap and MVC 3

I was fiddling with an idea that allowed rows to be dynamically added to an html page and deleted off the page. This became a bit tricky because I couldn’t identify the row I wanted to get rid of.

 

Eventually what I ended up doing was maintaining a list of the rows in a JavaScript object that functioned the same as the hash map and as opposed to deleting one row at a time I would remove the entire list from the page and re render it. The reason for this is when submitting arrays to an MVC 3 controller based on a strongly typed model you have to name the hidden input fields sequentially. Something like this:

 

<input type="hidden" id="EventList_0_SomeId" name="EventList[0].SomeId"  value="myid" />
<input type="hidden" id="EventList_0_Capacity" name="EventList[0].Capacity" value="25" />


 



As you probably gathered the next one would increment the 0 in the id and the 0 in the name to 1. The next one 2 and so on and so forth.



 



<input type="hidden" id="EventList_1_SomeId" name="EventList[1].SomeId"  value="myid" />
<input type="hidden" id="EventList_1_Capacity" name="EventList[1].Capacity" value="25" />

<input type="hidden" id="EventList_2_SomeId" name="EventList[2].SomeId" value="myid" />
<input type="hidden" id="EventList_2_Capacity" name="EventList[2].Capacity" value="25" />

<input type="hidden" id="EventList_3_SomeId" name="EventList[3].SomeId" value="myid" />
<input type="hidden" id="EventList_3_Capacity" name="EventList[3].Capacity" value="25" />


Just as a pointer, the name and the id of the input have to be declared or the MVC 3 controller will not resolve the values. The above example is a model that contains a list of objects that contain a property called SomeId and Capacity. If you do it the way I have illustrated above, it will resolve into a nice object representation in the controller that you can manipulate.



 



The Hashmap declaration:



function Map()
{
// members
this.keyArray = new Array(); // Keys
this.valArray = new Array(); // Values

// methods
this.put = put;
this.get = get;
this.size = size;
this.clear = clear;
this.keySet = keySet;
this.valSet = valSet;
this.showMe = showMe; // returns a string with all keys and values in map.
this.findIt = findIt;
this.remove = remove;
}

function put( key, val )
{
var elementIndex = this.findIt( key );

if( elementIndex == (-1) )
{
this.keyArray.push( key );
this.valArray.push( val );
}
else
{
this.valArray[ elementIndex ] = val;
}
}

function get( key )
{
var result = null;
var elementIndex = this.findIt( key );

if( elementIndex != (-1) )
{
result = this.valArray[ elementIndex ];
}

return result;
}

function remove( key )
{
var result = null;
var elementIndex = this.findIt( key );

if( elementIndex != (-1) )
{
this.keyArray = this.keyArray.removeAt(elementIndex);
this.valArray = this.valArray.removeAt(elementIndex);
}

return ;
}

function size()
{
return (this.keyArray.length);
}

function clear()
{
for( var i = 0; i < this.keyArray.length; i++ )
{
this.keyArray.pop(); this.valArray.pop();
}
}

function keySet()
{
return (this.keyArray);
}

function valSet()
{
return (this.valArray);
}

function showMe()
{
var result = "";

for( var i = 0; i < this.keyArray.length; i++ )
{
result += "Key: " + this.keyArray[ i ] + "tValues: " + this.valArray[ i ] + "n";
}
return result;
}

function findIt( key )
{
var result = (-1);

for( var i = 0; i < this.keyArray.length; i++ )
{
if( this.keyArray[ i ] == key )
{
result = i;
break;
}
}
return result;
}

function removeAt( index )
{
var part1 = this.slice( 0, index);
var part2 = this.slice( index+1 );

return( part1.concat( part2 ) );
}
Array.prototype.removeAt = removeAt;


 



The usage is just as simple. Include the JavaScript file and then:



var map = new Map();

map.put("key", value);
map.remove("key");

//etc


 



A really nice feature is that it does not duplicate keys but performs an “update” on the object at that key. So if you want to retrieve all the keys you can do something like this:



 



for (var i = 0; i < hashMap.keyArray.length; i++) {
var value = map.valArray[i];
var key = map.keyArray[i];
console.log(key, value.toSource());
}


 



 



I found the Hashmap declaration over here http://ping.fm/YAKIX



 



Some other interesting tid bits on the MVC embedded arrays, lists and editors for:



Wednesday, September 21, 2011

Object Relation Mappers (ORM) vs Stored Procedures

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!

 

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

 

References:

Internet Explorer 8 and JQuery 1.6.x

Recently I launched a new site for a friend http://ping.fm/0u4cy. Everything was working really well till the site was opened in Internet Explorer 8.

 

So I set about trying to figure out what was going on. Every time a link was opened the tab would crash and recover. My initial thoughts where that something was wrong with the JavaScript. So I started commenting out code to try and establish what was going on. Then I thought there might be something wrong with the CSS that was causing the tab to crash. I went around in circles for about an hour till I decided to scrap everything.

 

I commented out all the styles and scripts and the site stopped crashing the tab. Then I started adding back the references one by one till the browser crashed again. This happened as soon as I included the JQuery 1.6 min file. I couldn’t figure out what to do till a ray of sunshine hit me and I thought about the JavaScript parsing engine in Internet Explorer 8. What if the parsing engine was failing on something and causing so sort of memory leak or overflow?

 

So I proceeded to download the uncompressed version of the JQuery library and added it. Holding my breath, I refreshed the page and clicked around a few times. The site was now working!

Monday, September 19, 2011

Facebook vs Google+

I logged on to www.facebook.com today and noticed something called “smart lists”. Upon closer inspection this feature is a mechanism to group friends and view only their feeds. Nice, so now you can isolate the feeds you want to see as opposed to having to sift through endless notifications from apps your friends are using that they need “an axe to chop down trees” or a neighbour “has found your long lost gold fish” or any other arbitrary rubbish that gets pushed to your news feed trying to get you to consume the application. So, yeah neat and original idea. Oh wait, it is not original! Doesn’t Google+ circles offer the same functionality? Well I suppose it does, I mean after all if it looks like a circle and acts like a circle it must be a circle “symbol crash”.

 

Upon seeing this I remembered that www.facebook.com was suing someone over a very similar infringement of their beloved news feed.

 

So after reading an interesting article about who is suing who in the mobile space I thought I would see who www.facebook.com is suing (Google Search Results) I almost wet myself laughing when I viewed the results. So I thought, why not see who else is suing who. My next stop was who is Google suing (Results). The more I went on the more I started realising that software not only makes business supposedly run better but it is currently, single handed, funding law firms. With so much effort being pushed into suing people to get money that they feel is theirs no wonder there has been no significant break through since world war 2.

 

Let me validate that statement. World war 2 saw the discovery and implementation of:

Jet aircraft

Fuel injected engines

Ballistic missiles

Nuclear Fission 

Assault Rifles

Radar

Sonar

Precursors to the computer

Devices used in household appliances

Multi track recording

Synthetic rubber

 

and the list goes on and on. So tell me, what have we discovered since world war 2? Asides from making making computers small and more powerful? Asides from increasing the capacity of previous discoveries? What have we done in the 66 years after world war 2? Well in my estimation, squat.  Argue all you want but provide me with proof. All we have done is create a society based on rampant consumerism, technological devices get upgraded and upgraded and upgraded, even though we are using less than 50% of the actual capacity of the machines.

 

Anyways this isn’t supposed to be a rant about society, it is just a pointer to how incredibly backwards we have everything. Perhaps I should do an article about creating opportunities for innovation in this space. Maybe I will if I get time. In the mean time, let carry on suing everyone because at the end of the day surely no one in the worlds population of ~6,775,235,700 people  could possibly have the same idea as me. I mean, I am just that special!

TOGAF Foundation day 1

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://ping.fm/m2J2I

 

Other interesting links

http://www.zachman.com/

http://ping.fm/o1UBG

http://ping.fm/vw3wY

Thursday, September 15, 2011

Java Hibernate Setup

Ok here we go again. Now I am struggling get Hibernate working with the persistence unit declaration.

 

The reason I am writing this is more a pointer to myself should I ever have to do this again. Oh, check out my project on github. It is an implementation of a repository pattern using hibernate. It is extendable if you download the source and implement other providers. It is defined for standalone instances, not the full Java 5 EE stack although I am pretty sure with a bit of tweeking it can be used in that instance.

 

First I was getting the dreaded "javax.persistence.PersistenceException: No Persistence provider for EntityManager named”. After a little testing I figured out that the properties file contained an inverted commas wrapped persistence unit name where it should not have been wrapped

 

datastore.database.persistanceunit = "PU1" -> wrong!
datastore.database.persistanceunit = PU1 -> resolved correctly.


 



Ok so yeah I am rusty but bare with me. After getting that right I started running into Unable to build EntityManagerFactory. Drilling down a bit further it came down to not having an initial context. So I went and manipulated the persistence.xml file to no avail. Then I started digging deeper and found a ClassNotDefined exception (doh!). Seems I had forgotten to include the Postgres driver jar file (this is one feature I really like in C#, if you reference an assembly that references another assembly you get a warning if you haven’t referenced the dependency. Although I can see how this falls through using an XML configuration when there is no type checking happening. So the driver is obviously being created using some sort of reflection. Note to the Hibernate and JPA developers – please provide more verbose or smarter messages. Perhaps I just need to wake up!



 



Ok well, now the persistence.xml looks like this:



<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0" xmlns=”http://java.sun.com/xml/ns/persistence



xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance


xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
<persistence-unit name="CommunityPlatformPU" transaction-type="RESOURCE_LOCAL">

<provider>org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQLDialect"/>
<property name="hibernate.connection.username" value="xxx"/>
<property name="hibernate.connection.driver_class" value="org.postgresql.Driver"/>
<property name="hibernate.connection.password" value="xxx"/>
<property name="hibernate.connection.url" value="jdbc:postgresql://localhost:5432/database"/>
<property name="hibernate.cache.provider_class" value="org.hibernate.cache.NoCacheProvider"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
</properties>
</persistence-unit>
</persistence>



Right, new exception to deal with. For primary keys I prefer using UUIDs or GUIDs as they are always unique. Yes I know indexing issues blah blah blah speed related issues blah blah blah. I use it for a reason. When I transform the data into XML I want globally unique Ids so I can link via Ids. Now I usually got round this with the @PrePersist annotation (because the implementations only supported the integer values) but wanted to see if there had been any improvements since my last run in with JPA. Turns out there has been.



 



This is the way you use UUIDs as PrimaryKeys



@Id
@GeneratedValue(generator="system-uuid")
@GenericGenerator(name = "system-uuid", strategy = "uuid2")
@Type(type = "pg-uuid")
private UUID id;

public UUID getId() {
return id;
}

public void setId(UUID id) {
this.id = id;
}


 



Cool!  Next …



 



This little rig didn’t seem to like the jdbc3 drivers so switching to the jdbc4 drivers seemed to resolve that.



 



So that is that! Finally my test is passing and I am able to go to bed Smile  Well almost. Next it is time to configure the caching for the database and the connection pooling. Seems most of the libraries are included in the hibernate distribution. So the final persistence.xml file looks like this:



 



<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence"


xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 


xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
<persistence-unit name="CommunityPlatformPU" transaction-type="RESOURCE_LOCAL">

<provider>org.hibernate.ejb.HibernatePersistence</provider>

<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQLDialect"/>
<property name="hibernate.connection.username" value="dev"/>
<property name="hibernate.connection.driver_class" value="org.postgresql.Driver"/>
<property name="hibernate.connection.password" value="dev"/>
<property name="hibernate.connection.url" value="jdbc:postgresql://localhost:5432/communityplatform"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>

<property name="hibernate.cache.provider_class" value="org.hibernate.cache.EhCacheProvider" />
<property name="hibernate.cache.use_second_level_cache" value="true" />

<property name="c3p0.min_size" value="5" />
<property name="c3p0.max_size" value="20" />
<property name="c3p0.timeout" value="300" />
<property name="c3p0.max_statements" value="50" />
<property name="c3p0.idle_test_period" value="3000" />

<property name="current_session_context_class" value="thread" />
</properties>
</persistence-unit>
</persistence>


Green light on the tests, creating the database structure and persisting the information. Cool, now it is definitely time for bed, big day tomorrow, Skye turns 6 Smile



 



References:



http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html/mapping.html#d0e5294



http://docs.jboss.org/hibernate/core/3.3/reference/en/html/session-configuration.html#configuration-hibernatejdbc



http://docs.jboss.org/hibernate/core/3.3/reference/en/html/performance.html#performance-cache

Wednesday, September 14, 2011

Java resources (.properties)

Ok so I am making progress on a fiddle project that I am working on. I decided I was going to store the the persistence unit name in a properties file to prevent embedding strings in the instantiation methods.

 

I sat and fought for sometime trying to get the resources as a stream and came across some interesting links that explain how to do this. Namely:

http://www.bartbusschots.ie/blog/?p=360

http://download.oracle.com/javase/6/docs/api/java/lang/ClassLoader.html

http://download.oracle.com/javase/6/docs/api/java/lang/ClassLoader.html#getSystemClassLoader%28%29

http://download.oracle.com/javase/6/docs/api/java/lang/ClassLoader.html#getResourceAsStream%28java.lang.String%29

 

After fiddling and fiddling and getting very frustrated with the NullPointerException that kept on happening I was just about to give up.

 

Then I realised something. Looking at all the examples there is something I had added that I shouldn’t have

//Spot the ERROR!
Properties configFile = new Properties();
configFile.load(ClassLoader.getSystemResourceAsStream("/za/co/codeshark/application.properties"));


 



Don’t feel bad if you don’t see the problem. Laugh at me if you do Winking smile So here is the problem. If you have a look at the string pointing to the resource it has a leading “/”. Yes, this makes the path unresolvable. So it should have look like:



Properties configFile = new Properties();
configFile.load(ClassLoader.getSystemResourceAsStream("za/co/codeshark/application.properties"));


 



Notice that there is no leading “/”. Once I made this change everything started grooving and I was able to access my resource file. Once again kicking myself for not keeping these skills fresh. I find it weird though, that with all the examples of how to do this, none point out anything about how to resolve the path. Perhaps I am just over tired but I figured it might be good to make a note of this for 50 years from now!

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

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:



Tuesday, September 13, 2011

Java porting and the Date string conspiracy

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

Wednesday, September 07, 2011

Fluent Email and Git hub

So after submitting the changes for Fluent Email to the initial developer and him suggesting that I create a fork of the repo to contribute via, I finally got round to doing it. So what I am going to do is share my experience here.

 

First thing you need to do is git installed on your machine. The installer can be found here http://code.google.com/p/msysgit/downloads/list (I went for the full installer download). Then proceed to install the package and follow the instructions. Once you have completed that install you are going to need to set up your RSA keys to be able to connect to git hub via the bash. You can add your keys at the address https://github.com/account/ssh.

 

Right the next thing you might want to get is tortoise git. Simplifies the process of using git quiet significantly! Yes I am going to learn the command line stuff Winking smile Tortoise Git can be found at http://code.google.com/p/tortoisegit/downloads/list

 

Right now we got everything set up the next thing you need to do is fork the repo you want to work on. The instructions can be found here http://help.github.com/fork-a-repo/. Once you forked the repo you can now clone it to a directory on your machine (much like SVN), then edit away and when you ready you can commit your changes and push them.

 

I updated the Fluent Email to allow use of the template parsing outside the context of the Email class. I thought this would be handy for situations like I had recently where I needed the parser but not the email. I would have created another project for the parser but figured that the credit is due to the initial developer so left it in there. Then I refactored the addressing mechanism to remove duplicate code. It now reuses a single mechanism to parse the email addresses and names. Anyways if you interested check out https://github.com/RabidDog/FluentEmail

Razor Engine, more than just web pages

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://ping.fm/q4umY



 



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 = "~";
string output;

if (fileName.StartsWith(tilde)) {
var baseDir = AppDomain.CurrentDomain.BaseDirectory;
output = Path.GetFullPath(baseDir + fileName.Replace(tilde, String.Empty));
} else{
output = Path.GetFullPath(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: