Feb 112010
 

The first meeting of the Singapore Silverlight User Group at HackerspaceSG went pretty well yesterday.

We had Michael Sync talk about the new features of Silverlight 4.0. We had a bunch of guys who came from Microsoft Singapore to witness the formation of this group. We had about 10 people who turned up just to join the group! After that, we had a great discussion on MEF with Silverlight, F# and C# language features, and various other discussions on the side. I thought it was a great night with a good mix of discussions, random thoughts, Mac vs Windows clashes, and I hope that the community loved it.

Our next meeting will be sometime in March, so look out for the announcements! :)

Take a look at some of the photos.

Jan 072010
 

I want to bring in the new year with this code that doesn’t seem all very harmful, but could be written in a more elegant way. I just hope this will educate people on some of the new functional additions to C#.

[sourcecode language="csharp"]
public List<int> GetListOfIntegers()
{
List<int> list = new List<int>();
for(int i = 0; i < 24; i++)
{
list.Add(i);
}
return list;
}
[/sourcecode]

At its very core essence, this is simply creating a list of numbers from 0 to 23. However, try to find out the various possibilities of mistakes one can make with this code. I’ll leave it as an exercise of the reader to figure out all the possibilities of mistakes in this code. (side note: In fact, there was an error made in the original code. Yes, it looks simple, yet error-prone.)

Here’s a simpler and elegant way to do something like the above.

[sourcecode language="csharp"]
public List<int> GetListOfIntegers()
{
Enumerable.Range(0, 24).ToList();
}
[/sourcecode]

One of the interesting things with Enumerable.Range is it returns an IEnumerable. This effectively generates the numbers lazily. However in this example, in order not to change the signature of the method, ToList() is called to generate the numbers instantly, instead of lazily.

With ranges, you can create various interesting sets of numbers with Linq in a more functional way. I hope this week’s “Code You Should Not Be Writing” helps someone out there.

Dec 312009
 

This is my last post of the year, and I hope to make it special by giving you a piece of code that just amazes me. Staying within the whole “new year” feel, this code is for validating a date.

[sourcecode language="csharp"]
string strMessage = string.Empty;
int index = 0;
bool IsInputValid = true;

string strDate = TextBox_Date.Text; // TextBox_Date is just a textbox to get the date from.
DateTime date;
if (strDate.Length == 10)
{
int year = Int32.Parse(strDate.Substring(6, 4));
if ((year > 1900) && (year < 3000))
{
string strMonth = strDate.Substring(3, 2);
string strDay = strDate.Substring(0, 2);
date = Convert.ToDateTime(strMonth + "-" + strDay + "-" + strDate.Substring(6, 4));
}
else
{
index++;
strMessage += index + ". Date format(dd/mm/yyyy) is not correct.<br/>";
IsInputValid = false;
}
}
else
{
index++;
strMessage += index + ". Date format(dd/mm/yyyy) is not correct.<br/>";
IsInputValid = false;
}
[/sourcecode]

Remember the code you saw in Part 2 about the try-catch, using exceptions to do your data validation? Yes, that code surrounds this code. Imagine the double whammy I got when I saw this code, and the satisfaction of deleting it all.

I don’t know if you realise this, but do you have to take time to actually try to figure out what this developer is trying to do? As in understanding the code? How long do you take to figure out this code and what it is doing, and how flawed it is?

I hope you enjoy this edition of Code You Should Not Be Writing. Till next year, I have more to share! :)

Dec 302009
 

Finally, all 13 chapters are done. Now I can compile them into 1 big post with all the videos. I highly recommend every developer to watch these videos even though you’ll not be writing Functional code.

Edit: I totally forgot to link back all the chapters. Click on the links on each chapter for the original page and details to download the videos.

Chapter 1

Get Microsoft Silverlight

Chapter 2

Get Microsoft Silverlight

Chapter 3

Get Microsoft Silverlight

Chapter 4

Get Microsoft Silverlight

Chapter 5

Get Microsoft Silverlight

Chapter 6

Get Microsoft Silverlight

Chapter 7

Get Microsoft Silverlight

Chapter 8

Get Microsoft Silverlight

Chapter 9

Get Microsoft Silverlight

Chapter 10

Get Microsoft Silverlight

Chapter 11

Get Microsoft Silverlight

Chapter 12

Get Microsoft Silverlight

Chapter 13

Get Microsoft Silverlight

Play
Dec 292009
 

I encourage everyone who is still sitting on the fence about whether to learn a functional language to read this Beautiful Code – The Manifesto article written by Lau B. Jensen.

To summarize, his point of writing beautiful code essentially avoids a lot of the pitfalls you get from Imperative languages.

Beautiful Code is…

  • Concise – Free from both obvious and hidden ceremony
  • Expressive – Compartmental in its architecture, showing intent
  • Safe – Being explicit about state and time, defaulting to immutability

Of course, functional languages do all that. Therefore, functional languages create beautiful code. Trust me, you want to learn a functional language.

Try Haskell for size and read this book Real World Haskell which is a fantastic book to learn Haskell.

Or learn F# for those in the Microsoft space. I highly recommend Chris Smith‘s Programming F# book to learn F#.

Dec 242009
 

This is a special Christmas Eve “Code You Should Not Be Writing” post that I think is special enough to flip over your chair.

This is a common mistake C# developers make, which is forgiveable. You should use string.IsNullOrEmpty() method instead, which was introduced only in .NET Framework 2.0. It is understandable that most developers haven’t gotten up to speed yet.

[sourcecode language="csharp"]
string duration;
// … some code assignment for duration
if (duration == string.Empty || duration == null)
{
// … some error handling code
}
[/sourcecode]

But this just blew my mind. Can anyone guess why this is so very wrong?

[sourcecode language="csharp"]
string finalTitle;
// … some code assignment for finalTitle
if (finalTitle == string.Empty == null)
{
// … some error handling code
}
[/sourcecode]

Yes. You should never write code like this. Heaven’s me, this is valid code! The condition is just WRONG.

Merry Christmas everyone, and I hope you like this edition of “Code You Should Not Be Writing”.

Dec 172009
 

Well, this is part 3 already. I hope you’ve enjoyed and appreciated the last 2 part and understand my pain. Well, here’s something that doesn’t seem all too convoluted, but could have been achieved with just 1 line of code. By the way, just for those who don’t know, there isn’t really anything syntactically wrong with any of these code.

[sourcecode language="csharp"]
for (int i = 0; i < 24; i++)
{
string strIndex;
if (i < 10)
{
strIndex = "0" + i.ToString();
}
else
{
strIndex = i.ToString();
}
// … do more stuff with strIndex
}
[/sourcecode]

It’s slightly tougher to understand why this is bad code for those inexperienced. For those you understand why you should not write this code, good for you! You’ve got some developer sense in you. Till the next part, I hope you enjoy this code. Learn not to write like that, please.

Dec 152009
 

I thought I’ll post this in case anyone else encounters this problem. The purpose of the method is to get back a set of ClientContacts filtering based on the ClientID and select only those active if the onlyActive parameter is true, else ignore the IsActive filter and return all the records.

Here’s my LINQ query with a simple if-else shortcut within it:

[sourcecode language="csharp" highlight="5"]
public IQueryable<ClientContact> GetClientContactByClient(int clientID, bool onlyActive)
{
return from clientContact in this.db.ClientContacts
where clientContact.Client_AutoID == clientID &&
onlyActive ? clientContact.IsActive : true
select clientContact;
}
[/sourcecode]

Notice line 5? Here’s where I got this code wrong. The above code generates the following SQL statement:

[sourcecode language="sql"]
SELECT *
FROM [dbo].[ClientContacts] AS [t0]
WHERE (
(CASE
WHEN [t0].[Client_AutoID] = @p0 THEN CONVERT(Int,[t0].[IsActive])
ELSE @p1
END)) = 1
[/sourcecode]

If you actually work it out, this SQL statement will always return all records.

Here’s the change I made on the code to fix it.

[sourcecode language="csharp" highlight="5"]
public IQueryable<ClientContact> GetClientContactByClient(int clientID, bool onlyActive)
{
return from clientContact in this.db.ClientContacts
where clientContact.Client_AutoID == clientID &&
(onlyActive ? clientContact.IsActive : true)
select clientContact;
}
[/sourcecode]

Notice the brackets I added? This resulted in the generation of the following SQL statement:

[sourcecode language="sql"]
SELECT *
FROM [dbo].[ClientContacts] AS [t0]
WHERE ([t0].[Client_AutoID] = @p0) AND ((
(CASE
WHEN @p1 = 1 THEN CONVERT(Int,[t0].[IsActive])
ELSE @p2
END)) = 1)
[/sourcecode]

Again, if you work it out, this is the correct SQL statement to achieve what I want. I didn’t know a set of brackets make such a huge difference in the SQL code generation. Do take note of this when you’re finding out why your LINQ query doesn’t work as you might have thought.

Dec 102009
 

I hope this series becomes popular enough for bad developers to notice code like this. Because these code is really what’s out that! I’m serious! Next up, abuse of try-catch. This is how type validation is done. Wonderful, isn’t it? And look at the wonderful booleans associated with the try-catch logic? Doesn’t that just make you cringe?

[sourcecode language="csharp"]
DateTime newDateStart;
DateTime newDateEnd;
string errorMessage;
int index = 0;
bool isInputValid = true;
bool isSingleDayLeave = true;

try
{
// dateStart is a string assigned from above this code snippet
newDateStart = Convert.ToDateTime(dateStart);
}
catch
{
index++;
errorMessage += index + ". Date start should be given.<br />";
isInputValid = false;
}

try
{
// dateEnd is a string assigned from above this code snippet
newDateEnd = Convert.ToDateTime(dateEnd);
isSingleDayLeave = false;
}
catch
{
isSingleDayLeave = true;
}
// … more of similar code below.
[/sourcecode]

Dec 092009
 

Infer.NET is a framework for running Bayesian inference in graphical models. You can use it to solve many different kinds of machine learning problems, from standard problems like classification or clustering through to customised solutions to domain-specific problems. Infer.NET has been used in a wide variety of domains including information retrieval, bioinformatics, epidemiology, vision, and many others.

Recently, they have released their Infer.NET 2.4 Beta 4 with support for F#! It’s pretty interesting how using Infer.NET in F# will be like in this very interesting Bayesian inference framework. I’m very sure syntax and the terseness of the language will start to show once it starts making full use of the language features of F#. Have a go at it. I’ll be playing with this in my limited free time.

You can learn more from their PDC 2009 talk Infer.NET: Building Software with Intelligence. Here’s the synopsis for the talk.

Would you like to write software that can adapt to the user, learn from examples or work with uncertain information? Infer.NET is a machine learning framework that lets you build these capabilities directly into your .NET application. The framework allows you to combine detailed domain knowledge with the latest machine learning algorithms to generate tailored code to solve your problem. An API based on random variables lets you call Infer.NET code from within your application. We provide examples of using Infer.NET in search and gaming.

Source: Infer.NET

 Posted by at 09:30  Tagged with: