Showing posts with label c#. Show all posts
Showing posts with label c#. Show all posts

Monday, May 27, 2013

Using Actions to clean up your code

I am a firm believer of DRY “If you are doing the same thing thrice, you are doing it wrong” . Within reasonable effort ofcourse.

So when I see code like this:

List<string> permissions = new List<string>();
// The ones we care about:
if (Session.HasPermissions(Permission.AdministrationSetPoints))
{
    permissions.Add(Permission.AdministrationSetPoints.ToString());
}
if (Session.HasPermissions(Permission.Administration))
{
    permissions.Add(Permission.Administration.ToString());
}

There is no wonder that I want there to be a function to abstract out the if conditions. But creating a new function at class level looks a bit dirty. Not only do you have a new function that is only called from one place but you need to pass in a ref argument (permissions list). Later on its unclear at first sight (without reading xml comments perhaps) why this new function was created. Additional constraints like making sure your private functions are at the end may increase the distance between your original function and this new function. 

Lucky for us C# 3.0 gave us an excellent solution with inline lambdas:

List<string> permissions = new List<string>();

Action<Permission> addPermission = (Permission p) =>
    {
        if(Session.HasPermissions(p))
            permissions.Add(p.ToString());                   
    };
           
// The ones we care about:
addPermission(Permission.AdministrationSetPoints);
addPermission(Permission.Administration);

Notice that:
  • the action (addPermission) does not need to be passed in the permissions object since the outer scope variable is available.
  • The function is declared closer to where it is used and you can tell at first look why it was created.


To be honest. For this I was inspired by JavaScript closures.

Monday, March 4, 2013

CodeMaid : You should hire one for free

A perfectly innocent line of code


But in the eyes of Style Cop it is evil. And justifiably so. This is a simple example but perfect spacing, removing and sorting usings and other small simple tasks start to accumulate. These are all still important things you should do for others and your own future convenience.

However these are things you would rather have your code editor do so you can focus on solving the actual problem you are trying to solve. Enter CodeMaid (http://www.codemaid.net/) .

It does these and more for you on file save. So your code looks the way code should look everytime.
If you use stylecop (which you should) you need a code maid.

Thursday, February 28, 2013

Typescript interface syntax

Typescript offers two distinct flavours for declaring the same syntax. Both of these interfaces are identical:


The reason for providing these two ways is because :
C# / classic languages people would like the first syntax as that is how they would most likely use the interface:


The JavaScript folk might prefer the second syntax for it resembles JSON object syntax:


Since types are structural in typescript instace1 can be used anyplace where instance2 can be used.

Friday, November 23, 2012

.NET 4.5 Authentication and Authorization Trick question

I love the new ClaimsIdentity and ClaimsPrincipal classes added into .NET 4.5 : http://msdn.microsoft.com/en-us/library/hh873305.aspx

Using federated security used to require somewhat configuration in WCF with its SecurityContext handling : http://msdn.microsoft.com/en-us/library/ms731814.aspx and it was not integrated into the IIdentity and IPrincipal classes that come as a part of the .net core framework. Its nice to see these merge up.

That said. Here is a gotcha. Guess the output of this :


If you use GenericIdentity it is Authenticated by default. Whereas with Claims you can have users that are not authenticated! Here is the output:
This is actually more intuitive since we should be able to claim things about anonymous users. The moment you specify an authentication type for Claims Identity the user becomes authenticated.

Enjoy the new features. 

Thursday, September 20, 2012

My web stack of love, Great MVC / Javascript libraries

Found on nuget : 
  • Elma : described by scott hanselman as tivo for yellow screens of death 
  • dotless : automatically compiles your less files into css files. Does caching of the compiled files as well. 
  • MVCHtml5Templates : modifies your scaffolding to churn out html5. Does this by added EditTemplates into your views folder,  the magic is in MVC. 
  • Glimpse: Firebug for your MVC application. Shows you the routes that were triggered , where the view was searched etc. Really cool 
  • ASP.NET Web API : get the latest version on nuget! 
  • SignalR: Gives persistent web connections (web-sockets or otherwise. You do not need to think about whether web-sockets is supported). 
  • ASP.net Web API Self Host : changes your webapi project into a desktop application! 

Javascript: 
  • jquery : ... 
  • modernizer : get new browser features on old browsers 
  • knockout.js : MVVM for HTML/JS! 
  • upshot.js : seemless data transfer b/w server client. Client / Server data filtering as well against IQueryable. 
  • history.js : for browser window navigation (history). This is used by nav.js wrapper provided by Microsoft. 
  • holder.js : http://imsky.github.com/holder/ for image placeholders in mockups 

Jquery: 
Tools:
  • Fiddler : For composing HTTP messages. Great for testing your actions.  

Tuesday, June 26, 2012

Monotouch Gotcha : Dispose all outlets

If you have used winforms than you should be familiar with this pattern. Whenever you are done with a window be sure to call Dispose of any other windows that you have a reference to. The reason is that the windows are natively linked to OS windows and in your Dispose you are supposed to release any references to native resources.

In monotouch, even outlets are native objects. So be careful with them. In fact the default monotouch templates point you in the right direction as shown : 


The ReleaseDesignerOutlets automatically adds the code to release any outlets that are created using Interface Builder inside of Xcode:



Of course non-native (managed) resources are not your responsibility : http://stackoverflow.com/a/6620835/390330 

Saturday, October 8, 2011

Actionscript for C# developers

I've been learning Actionscript for some while now. The reason being the ability to target iOS / Android / Facebook gaming with a single platform.



C# for me is what my brain likes to think in (when it is not thinking in pseudocode or python). Here is a document that I made during the process of learning ActionScript as a language when you know C#.

Note: This document is a constant work in progress thanks to Google docs ability to sync between various computers I own I can chose to start and stop work on it from anywhere :)

You can download the word document file here.

Or view it here:

Friday, October 7, 2011

Razor View Engine Cheat Sheet for C#

C# Razor view engine is the most beautiful templating syntax I have ever seen in the MVC frameworks (rail and django included ... sorry for bringing django up).


Here is a quick cheatsheet that I made when revising if there was anything about the syntax that I didn't get the first time. I am sure there are still syntax related things that I am missing. If you feel that anything needs to be added to this let me know.


Monday, July 11, 2011

C# 101

This came up on my reader.google.com :

And I thought I had added c# expert blogs :)

Saturday, June 25, 2011

Best tutorial of C# Async

This is by far the best tutorial of C# Async you can possibly find for the simple reason that the code is all concise and runs in the browser right in front of you!

http://www.wischik.com/lu/AsyncSilverlight/AsyncSamples.html

The examples are also quite nicely / concisely written e.g. here is a sample of a CPU intensive task made async :


public async Task AsyncResponsiveCPU()
{
    Console.WriteLine("Processing data...  Drag the window around or scroll the tree!");
    Console.WriteLine();
    int[] data = await ProcessDataAsync(GetData(), 16, 16);
    Console.WriteLine();
    Console.WriteLine("Processing complete.");
}

public Task<int[]> ProcessDataAsync(byte[] data, int width, int height)
{
    return TaskEx.Run(() =>
    {
        var result = new int[width * height];
        for (int y = 0; y < height; y++)
        {
            for (int x = 0; x < width; x++)
            {
                Thread.Sleep(10);   // simulate processing cell [x,y]
            }
            Console.WriteLine("Processed row {0}", y);
        }

        return result;
    });
}


And heres a sample that uses the CancellationTokenSource (The CancellationToken is polled once per iteration of the y for loop to see if cancellation has been requested, and if so an OperationCanceledException is thrown.)

private CancellationTokenSource cts;

public async Task AsyncCancelSingleCPU()
{
    cts = new CancellationTokenSource();

    try
    {
        int[] data = await ProcessAsync(GetData(), 16, 16, cts.Token);
    }
    catch (OperationCanceledException)
    {
        Console.WriteLine("Processing canceled.");
    }
}

public Task<int[]> ProcessAsync(byte[] data, int width, int height, CancellationToken cancellationToken)
{
    return TaskEx.Run(() =>
    {
        var result = new int[width * height];

        for (int y = 0; y < height; y++)
        {
            cancellationToken.ThrowIfCancellationRequested();
            for (int x = 0; x < width; x++)
            {
                Thread.Sleep(10);   // simulate processing cell [x,y]
            }
            Console.WriteLine("Processed row {0}", y);
        }

        return result;
    });
}


And the best of all report progress sample

(Pings several sites, with an EventProgress object passed in to receive progres notifications.

Note that all calls into the ProgressChanged lambda are occurring while AsyncProgressPolling is suspended awaiting GetAllDirsAsync.)


private CancellationTokenSource cts;
public class GetAllPingsPartialResult
{
    public IList<string> Pings;
    public int Count;
}
public async Task AsyncProgressPolling() { cts = new CancellationTokenSource(); var progress = new EventProgress<GetAllPingsPartialResult>(); try { progress.ProgressChanged += (source, e) => { ProgressBar.Value = e.Value.Count % 100; //e is of the type GetAllPingsPartialResult }; foreach (var item in await GetAllPingsAsync(@"c:\", cts.Token, progress)) { Console.WriteLine(item); } } catch (OperationCanceledException) { Console.WriteLine("Operation canceled."); } } public async Task<string[]> GetAllPingsAsync(string root, CancellationToken cancel, IProgress progress) { var sites = new List<string>(); for (int i = 0; i < 30; i++) { sites.Add("http://www.microsoft.com"); sites.Add("http://msdn.microsoft.com"); sites.Add("http://www.xbox.com"); } var results = new List<string>(sites.Count); foreach (var site in sites) { cancel.ThrowIfCancellationRequested(); var time = DateTime.UtcNow; try {await new WebClient().DownloadStringTaskAsync(site);} catch {} var ms = (DateTime.UtcNow - time).TotalMilliseconds; results.Add(String.Format("[{0}] {1}", ms, site)); if (progress != null) progress.Report(new GetAllPingsPartialResult() { Pings = new ReadOnlyCollection<string>(results), Count = results.Count }); } return results.ToArray(); }

And if you want to read here is an excellent article : http://msdn.microsoft.com/en-us/library/vstudio/hh191443.aspx

Enjoy!

Monday, June 6, 2011

If null give default value

All this time I did not know about this lovely operator (null coalescing operator) : ??
It does one simple thing, If the value is null use the default value given as rvalue to the operator
On MSDN : http://msdn.microsoft.com/en-us/library/ms173224(v=VS.100).aspx

Friday, April 22, 2011

What great .NET developers ought to know

This is a very old post by scott hanselman : http://www.hanselman.com/blog/WhatGreatNETDevelopersOughtToKnowMoreNETInterviewQuestions.aspx
I was just googling .NET interview questions and it came up.

While searching for some of the answers this came up:
http://jingyeluo.blogspot.com/2005/06/what-great-net-developers-ought-to_03.html

A good read :) Even if you know the answers it is nice to know another developer's opinion.

PS: I did not know about .NET shadowing (actually c# uses the new keyword for it)!  Makes me think I should go through the C# keywords for VS2010 again :) http://msdn.microsoft.com/en-us/library/x53a06bb.aspx

Thursday, April 21, 2011

Singleton in C#

Just went though the implementing singleton in c#.
http://msdn.microsoft.com/en-us/library/ff650316.aspx
In short the ideal code :


using System;

public sealed class Singleton
{
   private static volatile Singleton instance;
   private static object syncRoot = new Object();

   private Singleton() {}

   public static Singleton Instance
   {
      get 
      {
         if (instance == null) 
         {
            lock (syncRoot) 
            {
               if (instance == null) 
                  instance = new Singleton();
            }
         }

         return instance;
      }
   }
}


Things of note:

  • The instance is marked volatile. If its multithreaded it might as well be volatile.
  • This will not work in JAVA since double checking is broken problem in Java :
    http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html
  • C# ensures that static variables are initialized BEFORE you can use a property. 
  • Instance is created only when it is requested. This is lazy initialization. 
  • Because of lazy initialization we need another reference type (we use an object) to carry out the lock.
  • We really don't want anybody inheriting our data and messing with it ... so sealed. 


Enjoy!

Monday, April 11, 2011

Reference Types inside a Value Type

Everybody should be clear that it is a bad idea. This is because we no longer get the "Copy Allocates new memory and therefore new values that are completely separate from the original" principal. 

However if you use an immutable reference type you can get away with it. But you should never do so simply because there really isn't any benefit from it and you might at sometime forget that it is actually a struct you are dealing with and mistakenly add a mutable reference type. 

Here is some weird sample code to show what happens when you add a reference type to a value type: 

public class MutableClass
    {
        public int SomeProperty { get; set; }
        public override string ToString()
        {
            return SomeProperty.ToString();
        }
    }
    public struct BadStruct
    {
        public string SomeProperty { get; set; }
    }
    public struct BadBadStruct
    {
        public MutableClass SomeProperty { get; set; }
    }


    class Program
    {
        static void Main(string[] args)
        {
            //BAD STRUCT
            var badStruct = new BadStruct();
            badStruct.SomeProperty = "10";
            var badStructCopy = badStruct;
            //This will actually assign a new string because they are immutable.
            badStructCopy.SomeProperty = "20"; 
            Console.WriteLine("ORIGINAL:" + badStruct.SomeProperty) ; 
            Console.WriteLine("COPY:" + badStructCopy.SomeProperty) ; 

            //BAD BAD STRUCT
            var badBadStruct = new BadBadStruct();
            badBadStruct.SomeProperty = new MutableClass() { SomeProperty = 10 };
            var badBadStructCopy = badBadStruct;
            //This will acually modify the original. 
            //Therefore the BadBadStruct no longer behaves like a value type 
            badBadStructCopy.SomeProperty.SomeProperty = 20;
            Console.WriteLine("ORIGINAL: "+badBadStruct.SomeProperty.ToString());
            Console.WriteLine("COPY: " + badBadStructCopy.SomeProperty.ToString());

        }
    }

And the output : 


Friday, April 1, 2011

How WCF will deal will dynamic

Yes. WCF can serialize dynamic as long as the underlying type passed as dynamic supports serialization.

This is soo cool.

So I made a test WCF project will the following Operation Contract in the Service Contract :

[OperationContract]
        dynamic AcceptDynamic(dynamic cool);
And the following service implementation: 
public dynamic AcceptDynamic(dynamic cool)
        {
            if (cool is string)
                return cool + " DAMN COOL";
            if (cool is int)
                return cool + 10;
            return "";
        }

After I import this at the client I get the following method signature: 
public object AcceptDynamic(object cool) {
            return base.Channel.AcceptDynamic(cool);
        }

Notice the dynamic has been changed to object. Means I pass in anything I want. It get stored in object. Serialized to server. Deserialized into dynamic. And used as necessary. In retrospect its obvious. But the repercussions for potentional dynamic service design are enormous. More on that latter (basically it could have been something that inherits from DynamicObject and implements INotifyPropertyChanged/IErrorInfo and been a kickass dynamic data model). 

Sample client:

static void Main(string[] args)
        {
            ServiceReference1.Service1Client svc = new ServiceReference1.Service1Client();
            Console.WriteLine(svc.AcceptDynamic("asdf"));
            Console.WriteLine(svc.AcceptDynamic(10));
        }

And the output: 
Enjoy!


Thursday, March 31, 2011

Default constructor can be suppressed. But it is required for XAML instantiation

Well the title really say it all doesn't it. If you create a class with a constructor that takes any parameters then the compiler will not create the default constructor for you. In such a case if you try to create the object in XAML your code will compile (actually the BAML will be made so the compiler really doesn't know that you tried to call a default constructor when there isn't one) but you will get a runtime error in InitializeComponent(). Just so you know.

Enjoy!


Saturday, March 26, 2011

Swap two numbers without using a temp variable

A friend of mine asked this question while we were in college. I didn't pay much attention to the question, didn't believe it was possible (because we were taught how to swap variables ... and taught to use a temp variable for it). I thought he joking and moved on.

But in my first programming job test this question was there: "How can you swap two numbers without using a temp variable. Hint: think of a mathematical operator"
And the hint gave it away :) I was quite proud of figuring it out myself. You basically just need to store the sum and subtract alternately. Here .. look at the code :

Some C#ish notes: 
Notice that it works even beyond int.MaxValue :) But for it to work you need to make sure that the assembly is not built with checked option and the code is not in a checked scope : http://msdn.microsoft.com/en-us/library/74b4xzyw(v=VS.100).aspx

And Just out of curiosity:
Know that in python being a super cool language you can just do :
[x , y] = [ y , x ]

Now ain't that super cool!


Live and learn....and Enjoy! 

Tuesday, December 14, 2010

ValueTypes cannot be modified by extension methods

I was converting a WPF code to silverlight when I noticced that Silverlight does not have the Offset Member method to the point structure. I thought I could get away with a dead simple extension method :

namespace ConsoleApp 
{ 

    public static class SlUtils
    { 
        public static void OffsetSL(this System.Windows.Point p, double CenterX, double CenterY)
        { 
            p.X += CenterX; 
            p.Y += CenterY; 
            // p = new System.Windows.Point(p.X, p.Y); does not help either
        } 
    } 

    class Program 
    { 
        static void Main(string[] args) 
        { 
            System.Windows.Point p = new System.Windows.Point(0, 0);
            p.OffsetSL(10, 20);
            Console.WriteLine("{0},{1}", p.X, p.Y); // prints {0,0} // FAIL 
            p.Offset(10, 20);
            Console.WriteLine("{0},{1}", p.X, p.Y); // prints {10,20} 
            Console.ReadKey(); 
        } 
    } 
} 
I was so wrong :) The extension method cannot modify a value type. What you can do is return from an extension method (instead of void) the value you want... ah well you can't have Everything.

Enjoy!

Monday, December 6, 2010

Exam 70-502 Passed

The exam was great. Really I am not saying that because of my score. I am saying that because it was much more fun (for me at least) than 70-536. WPF (and now Silverlight) is a technology I am deeply passionate about. Maybe its because of my love for beauty and elegance. Maybe its because I hate to say to someone that adding a really classy button just the way you want it to your application will take me three days.

PS: I sincerely believe that 70-536 made me a better programmer. You will not catch me asking around about StreamReader or how to determine drives in c#.  Although a quick google search would help you ... but I will not need one ... I hope :) Oh not to mention : http://msdn.microsoft.com/en-us/library/system.io.path.getfilenamewithoutextension.aspx or http://msdn.microsoft.com/en-us/library/wz42302f.aspx (these weren't asked of me ... but I remembered them).

Now how did I prepare for this exam. 
Well I have had an eye on WPF for three years. Recommended it to a colleague two years ago (I myself was experimenting with python + flex)  and did a project in WPF about a year and a half ago. Simultaneously I had read the book WPF unleashed (http://www.amazon.com/Windows-Presentation-Foundation-Unleashed-WPF/dp/0672328917).This book is basically what got me really motivated to start doing Microsoft certifications in the first place (I devoted myself to a technology I loved). The official book would not be sufficient without this. Everyone will tell you that. Without this I wouldn't know what {Binding} meant (bind directly to datacontext) or that a style without an explicit key but a targettype gets an implicitly set key.

It wasn't until mid of this year that I finally got the time to start doing it. First I applied for exam 70-536. Just then the new certifications came out (VS2010). But I really wanted the title WPF technology specialist, so I decided to go with the old certifications anyways. Additionally I don't feel comfortable about doing a certification without an official "book" (VS2010 book isn't out yet). For this I read the book cover to cover one and a half times (second time just the highlights to memorize what I thought deserved memorizing the first time I read it). This is the "book" http://www.amazon.com/MCTS-Self-Paced-Training-Exam-70-502/dp/0735625662/ref=sr_1_5?ie=UTF8&s=books&qid=1291632845&sr=1-5 I loved this book. Without this book I wouldn't have known that there are EnterActions for property triggers.

I still had time (about a month due to prometric test center being booked in my city) ... I decided to read WPF Unleashed 4 http://www.amazon.com/WPF-4-Unleashed-Adam-Nathan/dp/0672331195 I intend to finish it someday but just got curious about silverlight as it is now. And then I picked up Silverlight 4 Unleashedhttp://www.amazon.com/Silverlight-4-Unleashed-Laurent-Bugnion/dp/0672333368 Now note that I am reading this book after preparing 70-502. This meant I know the value of learning ... really learning every single API that is exposed. And I couldn't put this book down. I simply love it. It showed me how to make my own controls in the very first chapter. I can see XAML now (just like I could see c#). Make my applications Blendable. And I really feel comfortable with MVVM (and yes I have made applications without MVVM ... I am not proud ... and I don't intend to do that ever again). This alone made it the best book on WPF (yes WPF... even though it does not claim it) ever!

And that's it ... the exam was today morning at 10:30 am ... and the rest is history. Thanks for everyone who waited patiently while I prepared for this exam. Love you mom for tolerating my eternal business and keeping me well fed and energized.

Monday, November 8, 2010

Why .NET?

The question is "Why .NET". Well it really starts with why a Virtual Machine (VM) runtime. The answer for me was :

When you think of your software running unattended for large periods of time and factor in the time you have to develop said software ... VMs help. 

Goodbye C++ / C. Hello .NET / JAVA. 
Now, "Why .NET". Really once you have settled on VM the only options you have for mass consumer targeting are .NET and JAVA. Really. 

So why .NET is actually a question of "Why not JAVA?" or "What makes .NET Better than JAVA?" 
Before I continue. Note that a major part of my final year project for BE Telecom was made in JAVA. (A SIP Proxy server). So there was a time that I "Loved" JAVA. 

JAVA as a language:
Java still doesn't have true getters / setters. You need to type GetName SetName yourself. If its a standard push it to the compiler please. 
The reason is that language features need to go through JCPs and it can still take years before it makes it to mass distribution. A non evolving language is either a dead language or a dying language albeit really really slowly (A note on JCP's lack of progress : http://blogs.apache.org/foundation/date/20101209 ). 

So here are the features I love in C# as it Evolves:
Properties
Linq
Dynamic Types
Yield (oh it is so hot!)
Async Programming
WPF ... okay its a library ... But an AWESOME one at that. Swing just does not come ANYWHERE close anymore

These will take a long time to make it into JAVA (if ever). JAVA is more focused on APIs rather than the Language itself. And the Desktop APIs still suck. More on that later. 

Now for the annoyances that already made it to the language. 

Exception me please:
You cannot add a new exception throw all of a sudden without the compiler complaining. All for the supposed claim that it will prevent unwanted exceptions. And the fun part. It can be bypassed. Virtualize or late bind much? I do. 
PS: Mostly people are just forced to catch and ignore exceptions. The compiler actually breeds BAD code. 

Return:
Okay I am being sloppy here. But while testing I like to return prematurely from a function sometime. Or maybe I write half the code. Then to test something else I put up a mock return. In JAVA I need to Comment out the remainder of the function just to compile. I prefer the C# version of the warning me but not getting in my way. Just run the code. 

Swing:
For those that don't know Swing is the THE premier JAVA GUI framework for the Desktop. What got me was Windows Vista going into the Windows classic look and feel stating "A running program isn't compatible with certain visual elements of windows". I would hate to explain this to my clients. http://www.hanselman.com/blog/SunsJavaJRESwitchesVistaAeroIntoBasicUIScheme.aspx

Jeff Atwood pretty much explained everything wrong with this in 2007. Its funny how a bad Desktop UI will almost always have a mention of JAVA.
 Oh did I mention desktop applications are what made me fall in love with programming and before Flex (yes it came first)/Silverlight desktop apps are the only place I would be found. Other than "really" trivial PHP scripts :).  PS: JavaFX has terrible penetration for a reason :) 

I like applications full of power. Desktop is the way. AUTOCAD / MAYA / MAPINFO / MATLAB / MS Office / TEMS  all great applications that are primarily on the Desktop for a reason. And if you are going to go to a runtime. You know which one to choose :). Plus I do Telecom Software. We love the Desktop. Its our home :)

Java and Lawsuits. So much for "Open": 
To be fair. Java defends "http://en.wikipedia.org/wiki/Write_once,_run_anywhere" very strongly. But their J2ME is no treat either. 

Microsoft:
Well for quite a while (a long long time ago) Microsoft's implementation of JAVA was awesome with great Developer productivity. Till Microsoft got sued for it: http://en.wikipedia.org/wiki/Microsoft_Java_Virtual_Machine
So Microsoft came up with .NET. Maybe Redmond already had such plans but I don't know. 
Microsoft responded for being sued by Sun: http://www.internetnews.com/ent-news/article.php/988071/Sun-Sues-Microsoft-Over-Java.htm Java still doesn't come preinstalled in windows. Your hardware vendor might do so. 

Google:
Yes. For android. Oracle sues Google for Java derived runtime: http://news.cnet.com/8301-30684_3-20013546-265.html . Google does not attend JavaOne : http://googlecode.blogspot.com/2010/08/update-on-javaone.html

Oracle is a financial institution
Oracle defends its profits VERY diligently. 
They did make MySQL InnoDB commercial as well : http://www.cloudave.com/7356/internal-email-on-why-a-software-company-migrates-away-from-mysql/ (Note the CEO also warns against JAVA). But I saw that (thanks to other intelligent folk on the internet) coming from a mile http://basaratali.blogspot.com/2010/05/free-for-commercial-use-high.html . Postgresql is the future MySQL. 

Finally Some JAVA love:
Java is not all that bad. I wouldn't be caught dead writing a JAVA app for the desktop....never again. But for the server of the top of my head GWT is cool. Well at least the results are ... I haven't tried it myself. Pentaho is very cool. JasperReports are amazing. These are not "JAVA" goodness per say but hey a runtime is valued by what it runs. So I guess its third party love :) But for my raw code I still doubt I would ever go there. 

Fun Java Quotes by People I Respect: 
If you feel these are taken utterly out of context. Well Quotes usually are so I link to the complete context :)
Everything on this page is my opinion. I am in no way legally liable for anyone else's actions.
The last update time for this page should help, since technology changes and JAVA might get these features :)