Archive for October 2011
A Microsoft KB Article–Example of How not to write code
Couple of weeks back I was doing some parsing of xml string and want to replace the special characters in the data. I didn’t remember the list of special characters, like others I fire up a search in Google. One of the google search result leads to a Microsoft KB article. I got what I wanted, list of special character I have to deal with. The article also provided a special character replacement logic, to my surprise the code was very lengthy and looks odd to me.
I decided to scan the code in little more detail. Below is the code from the article.
Dim filepath As String = "C:\customers.xml" Private Sub ReplaceSpecialChars(ByVal linenumber As Long) Dim strm As StreamReader Dim strline As String Dim strreplace As String Dim tempfile As String = "C:\temp.xml" Try FileCopy(filepath, tempfile) Catch ex As Exception MessageBox.Show(ex.Message) End Try Dim strmwriter As New StreamWriter(filepath) strmwriter.AutoFlush = True strm = New StreamReader(tempfile) Dim i As Long = 0 While i < linenumber - 1 strline = strm.ReadLine strmwriter.WriteLine(strline) i = i + 1 End While strline = strm.ReadLine Dim lineposition As Int32 lineposition = InStr(strline, "&") If lineposition > 0 Then strreplace = "&" Else lineposition = InStr(2, strline, "<") If lineposition > 0 Then strreplace = "<" End If End If strline = Mid(strline, 1, lineposition - 1) + strreplace + Mid(strline, lineposition + 1) strmwriter.WriteLine(strline) strline = strm.ReadToEnd strmwriter.WriteLine(strline) strm.Close() strm = Nothing strmwriter.Flush() strmwriter.Close() strmwriter = Nothing End Sub Public Function LoadXMLDoc() As XmlDocument Dim xdoc As XmlDocument Dim lnum As Long Dim pos As Long Dim Newxml As String Try xdoc = New XmlDocument() xdoc.Load(filepath) Catch ex As XmlException MessageBox.Show(ex.Message) lnum = ex.LineNumber ReplaceSpecialChars(lnum) xdoc = LoadXMLDoc() End Try Return (xdoc) End Function
The user calls the LoadXMLDoc() function, the function loads the xml file located in the disk. The weird thing is, the function does a recursive call in the catch block until all the special characters are replaced. Have a look at the line in red.
Let’s go to the ReplaceSpecialChars() function. It creates a temp copy of the original xml file and does the character replacement with several number of IO operation. Think a scenario where we need to deal with an xml data that has some thousand line and each line has special character, we end up doing IO operation thousands of time. Wow what a logic.
Refactored Approach
I rewrote the logic, I used C# as my choice. My approach is simple, read the xml file then format it the way we need it and load it to XMLDocument. Let see my piece of code.
public XmlDocument LoadXMLDoc() { XmlDocument doc = new XmlDocument(); string xmlToLoad = this.ParseXMLFile(); doc.LoadXml(xmlToLoad); return doc; } private string ParseXMLFile() { StringBuilder formatedXML = new StringBuilder(); StreamReader xmlReader = new StreamReader("CustomerData.xml"); while (xmlReader.Peek() >= 0) formatedXML.Append(this.ReplaceSpecialChars(xmlReader.ReadLine())); return formatedXML.ToString(); } private string ReplaceSpecialChars(string xmlData) { int grtrPosAt = xmlData.IndexOf(">"); int closePosAt = xmlData.IndexOf("</"); int lenthToReplace = 0; if (grtrPosAt>closePosAt) return xmlData; lenthToReplace= (closePosAt<=0 && grtrPosAt<=0)?xmlData.Length:(closePosAt-grtrPosAt)-1; //get the string between xml element. e.g. <ContactName>Hanna Moos</ContactName>,
//you will get 'Hanna Moos' string data = xmlData.Substring(grtrPosAt + 1, lenthToReplace); string formattedData = data.Replace("&", "&").Replace("<", "<")
.Replace(">", ">").Replace("'", "'"); xmlData = xmlData.Replace(data, formattedData); return xmlData; }
I took reactive approach rather than waiting the XMLDocument to throw error and rectify it then try loading. ReplaceSpecialChars() function formats the xml string and return it. I spend just 10 minute to come up with this function, so may not be the best one but definitely better than what mentioned in KB article.
Point to note In my approach
- The IO operation is only once, first time to read the xml file.
- XMLDocument will get a clean formatted xml to do it’s operation.
- No recursive call in catch block.
- LOC is less, so easy to understand.
If you find any better approach, update that in the comment section.
Note: I send a feedback to Microsoft couple of weeks back about the issues in the code but no response yet.
Happy coding …..
Think twice before buying Samsung Galaxy Tab 10.1
A month ago I bought a brand new Samsung Galaxy Tab 10.1 (Wi-Fi model, Android 3.1) from UK. Every thing was fine until I reached Bangalore, my luck ran out and it started showing the famous OIL SLICK (Newton Ring) issue. I called up Samsung Customer Care also sent a mail regarding the issue. I got a reply from Customer care that, I should visit a Service center in Bangalore. As per the instruction I went to the Service center to try my luck. Service center told that my issue is a Manufacturing Defect and my Tab 10.1 doesn’t have international warranty so they cant do any thing with my tab. This states one thing that Samsung’s Customer care and Service center are not in sync, pathetic.
I regret my decision of buying Galaxy Tab 10.1, I could have buy iPad2 or any other Android tab. I bought an Android tab because I wanted to do some development in Android world. Galaxy tab 10.1 showcased as one of the best tablet in Android world and I fall into that trap.
Samsung should have guts to admit that their Tab has manufacturing defect and will replace from any where. But till now not a single word from Samsung about this issue, how pathetic.
My advice to others are don’t buy Galaxy Tab 10.1, today or tomorrow your tab also shows Oil Slick issue. If you still want to buy then.
-
Make sure you have a room that’s very cold like refrigerator, research shows that keeping Tab 10.1 in refrigerator for 5 minutes will remove Oil slick for some time. So if you have a very cold room and you work on your Tab in that room, Oil Slick issue may not arise again.
-
Try to win a lottery or wait until you win the lottery. So that you can make sure that you are lucky and the probability of getting Tab without Oil Slick is high (Just buy a low cost lottery, it is to make sure you have luck)
-
Wait until Samsung declares that the Oil Slick issue is permanently resolved.
If you are not specific about Android OS better go for iPad2. I can guarantee that Apple’s customer support is wonderful. I bought an iPhone 3G when it first launched and my phone’s touch screen has some defect. I went to a Apple’s customer care center, after the examination they simply replaced it with a new one. They haven’t asked a single question, no bills, no warranty card just gave me a new phone. As a customer we expect these kind of Customer support what Apple provides not the pathetic and unprofessional support what Samsung is providing.
I am not Alone
Google search shows that I am not alone, couple of links talks about this issue. You can search your self and search will come up with more than 10 page search result.
http://galaxytablife.com/2011/07/galaxy-tab-10-1-moisture-oil-slick-problem/
http://forums.cnet.com/7723-13973_102-540466.html
Some owners replaced their Galaxy tab several times, that shows how wonderfully Samsung manufactured the Tab 10.1. Please spread the awareness to keep people away from purchasing this buggy Galaxy Tab 10.1
Spread the Awareness
Friends spread the news, you may save your friends or family falling into the trap of Galaxy Tab 10.1. If you own a Galaxy Tab let me know your experience by updating in comment section.
All the best if you still considering to buy a Galaxy Tab 10.1
Edit: see the response from Samsung Customer Support UK
Continuous learning and Pet projects
As a software professional we are living in a world of knowledge explosion. A new framework will introduce in a matter of time to solve our hardship or another vendor introduce a framework superior to the existing ones. Our world is changing day by day, so how we will cop up with the ever changing world of Software industry. Simple answer is Treat programming as a passion not just a profession and Continuous learning.
Learning is not just reading some books or blogs, it also includes implementing what you read by writing a simple application. I can fly an aero plane using Microsoft Flight simulator but how foolish I am If I think that I can fly a real plane because I can fly in simulator. Same applies to software world as well, we have to practice what we read using language of our choice.
In hiring process if I ask about WCF or any xyz prominent framework, one answer I hear most of the time from candidates are “I read about it but never used it, because my current project is not using it”. To succeed in Software industry are we relying only on our official project? Its like a F1 driver telling that I will touch the driving wheel only in F1 Race track, does he win the race?
Pet Projects
One of the best way to expand our horizon is working on pet projects. It gives immense opportunity to learn new things that we wont get in official projects. The advantages of a pet project is
-
Their wont be any deadlines.
-
Opportunity to implement what ever you are learning in day to day life.
-
You can scrap the project and start it from the scratch with a new improved design.
-
Test different frameworks and use the best one.
-
Knowledge you gained from pet project can be used in official one.
-
You are the boss do what ever you want with it.
-
And a lot….
A year or two back I was doing some research in Collective intelligence, and I learned couple of algorithms as part of it. I never knew that I will be using what I learned in those days in a completely different context, I used it for counting colors in an image just like how human does. I implemented it it in an official project. Yes time spend in Collective Intelligence paid me off.
Most of my pet projects wont even see the light, but all of those are high learning curve for me. I learned WPF through a pet called iTraveller. Three years later I scrapped that project and developed in MVVM using Caliburn Micro with a new architecture. It helped me to learn a lot other frameworks, you can see the details of iTraveller here.
Recently I read a post of Ayende and that invites lot of negative feedbacks. Most of the commenters tells lack of time outside official work to do some pet projects or want to spend time with family, etc. With all respect I strongly disagree that, I think most of us can spend an hour every day to sharpen our knowledge. In a long run it will definitely help you.
Learn new Languages
As Pragmatic Programmer book says, learn a new language every year. It’s a wonderful experience and full of challenges. I was working in .NET for so many years and one day got an urge of learning Scala. It was very challenging, I got introduced to new semantics, new IDE, a completely new world. But I learned functional programming. I may not use Scala in my day to day life but I learned lot of good stuff that I may can use in .NET. If you are a WP7 developer, do some thing in Android. Trust me it’s will be a new experience.
Once we start broaden our knowledge, it will shatter our ego and will realize how less we know in the ocean of knowledge.
I was like a boy playing on the sea-shore, and diverting myself now and then finding a smoother pebble or a prettier shell than ordinary, whilst the great ocean of truth lay all undiscovered before me. – Isaac Newton
Share what you learn
It will help others if you share what you have learned. If you don’t have a blog start one. A blog is not just for others, it will also help you if you want to look back and find how you solved a scenario before. I consider my blog as a log of solutions, where I can read it when ever a similar situation arise.
The post is just a repetition of all other great minds said. I just portrayed through my experience.
Happy coding…