Monday, July 28, 2008

Getting started with Windows Presentation Foundation

The following post describes the first section of my future talk on "Windows Presentation Foundation". Given below is the list of topics/concepts this post covers:




  1. Lifecycle of a WPF application


  2. What are the WPF-like applications possible today?


  3. How to load XAML at runtime?


  4. Working with objects loaded from XAML at runtime?


  5. How to obtain XAML from objects?


  6. Some tools of trade.



Lifecycle of a WPF application 



Leaving the long stories of how great WPF is and what WPF is useful for, we directly jump into the lifecycle of a WPF application with the assumption that readers knows what WPF is mainly used for - generating data-driven windows application with great User Experience that could easily be achieved.



As we create a new WPF application project from Visual Studio, we get a bunch of different files. The article at http://wpfwonderland.wordpress.com/2008/07/16/understanding-the-xclass-attribute-and-visual-studio-2008/ provides a details description of what happens at compile time during a wpf application build. To summarize it in my own way, let us first look at the files generated with an empty WPF application project.



 



empty wpf project



The App.xaml is the entry point file whose contents are like shown below





   1: <Application x:Class="EmptyWPF.App"


   2:     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"


   3:     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"


   4:     StartupUri="Window1.xaml">


   5:     <Application.Resources>


   6:          


   7:     </Application.Resources>


   8: </Application>




Just like in the ASPX where the markup has a corresponding code-behind, WPF applications uses a similar partial-classes strategy where a code-behind file is linked to a XAML using x:Class attribute. The StartupUri attribute indicates the page the application should first show as the application is launched. Now if we look at the Window1.xaml (it has a corresponding Window1.xaml.cs)



An empty Window1.xaml is added to the application project whose XAML is shown below.





   1: <Window x:Class="EmptyWPF.Window1"


   2:     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"


   3:     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"


   4:     Title="Window1" Height="300" Width="300">


   5:     <Grid>


   6:         


   7:     </Grid>


   8: </Window>




Again, notice the x:Class attribute pointing to the  code behind file. Now let us add a button that displays Hello World! and to the click event, we display another message box that shows your name.



A button in XAML is as shown.





   1: <Button x:Name="btnDemo">This is the buttons' content</Button>




There are numerous ways in which a button's content is set. Shown below is a couple of other ways.





   1: <StackPanel>


   2:         <Button x:Name="btnDirect">This is the buttons' content</Button>


   3:         <Button x:Name="btnContentProp" Content="Set from Content Property"/>


   4:         <Button x:Name="btnSetUsingAttachedProperty">


   5:             <Button.Content>Set using Attached Property</Button.Content>


   6:         </Button>


   7:         <Button x:Name="btnFullyQualifiedButtonProperty" Button.Content="Fully Qualified Setter"/>


   8: </StackPanel>




Also shown is a Layout which specifies the way the buttons are to be displayed. In layman terms, layout is a container with a specification on how its contents are laid out. Some of the layouts we commonly see are StackPanel, Grid, DockPanel. We look at layouts in more detail in the next segment of the talk.



Now when we compile the application project, the XAML file is compiled into a BAML (Binary Application Markup), stored as a resource inside the assembly. Also added is a .g.cs file which contains a partial class for that xaml file code-behind which hooks up the code with the XAML. There is a IConnect() method inside the generated .g.cs file which performs this form of binding the code with markup, thereby allowing the objects to react to events. These intermediate files can be found in the "obj" directory of the project folder. Note that the msbuild uses PresentationBuildTasks.dll to automate this codegeneration and XAML to BAML conversion process.



As a proof that the BAML file is embedded into the assembly as a resource, we use Reflector to examine the assembly. Note that the Reflector does not diassemble the BAML and instead we can use a BAMLViewer like add-on to view the BAML as XAML.



image



 



Notice the EmptyWPF project contains the BAML files as resources. Also shows the BAML viewer in use.



When the application is run, the CLR delegates the control to the PresentationFramework which creates an appropriate host window which renders the UI that is taken from the BAML. In order to do this, the Presentation Framework generates an object graph from the BAML (also the visual and logical trees, covered later). Please observe a portion of the call-stack for the EmptyWPF application we created shown below.





   1: PresentationFramework.dll!System.Windows.Application.RunInternal(System.Windows.Window window) Line 1901 + 0x18 bytes    C#


   2: PresentationFramework.dll!System.Windows.Application.Run(System.Windows.Window window) Line 260 + 0x9 bytes    C#


   3: PresentationFramework.dll!System.Windows.Application.Run() Line 222 + 0x9 bytes    C#


   4: EmptyWPF.exe!EmptyWPF.App.Main() + 0x4c bytes    C#




It is the PresentationFramework that takes care of creating the Window and running the application with a certain lifecycle (Like raising the Startup events, etc.)



WPF application types and wpf-ish applications



XBAP - Xaml Browser Applications, also known as XBAPs are full-fledged WPF applications that are hosted inside a browser. As with the case of other such applications (like flash and applets), XBAPS runs in a restricted sandbox environment, thereby are limited in certain functionality. When an XBAP is built and is ready to be deployed, the .exe, .manifest and .xbap files should be copied into the directory we wish to publish the application in. It is similar to a Click-Once application except that the .xbap is used instead of .application. Using Visual Studio publish wizard simplifies the deployment issues and we could later copy the files published to a different location. Few configuration settings are to be made to the server hosting the application - application mime-types shown below are to be registered within the server.





   1: MIME Type                    Extension 


   2: ication/manifest             .manifest 


   3: ication/x-ms-xbap            .xbap 


   4: ication/octet-stream         .deploy 


   5: ication/x-ms-application     .application 


   6: ication/vnd.ms-xpsdocument   .xps 


   7: ication/xaml+xml             .xaml 




One could set the trust levels of an XBAP application using visual studio project properties window. Some other restrictions in XBAP is that they cannot create objects of type Window or NavigationWindow (thereby no pop-ups or dialog boxes). They have the HostInBrowser property set to true inside the msbuild file.



A Xaml file could also be viewed directly inside a browser. When you open IE and open the XAML file, it renders the output on the IE window. The presentation framework, in this case would not create a NavigationWindow or a Window to host the XAML content instead uses the browser as a window.



Other WPF-ish application are the Silverlight applications. As of now, the talk might not constitute Silverlight content and instead if time permits, few sections of Silverlight would be posted on my blog.



Loading XAML at runtime



We now look at how XAML could be loaded at runtime. As an example to demonstrate the api and its usage, a simple XamlPad like application is developed the source of which would be posted online here. In the last section of this post (Tools of Trade), we present few tools that helps learn WPF and until then just understand that XAML pad is a XAML editor that can be used to write/learn to write XAML. You can access XAMLPad by typing "xamlpad" in Visual Studio Command Prompt.



So the requirement for our own xaml pad is that the application should be able to first read XAML written by the user, validate it and then convert it into BAML and show the output on a component inside the window. Consider the case where the user has entered just the XAML for a Label which contains a button whose content instead contains a checkbox (the motto of WPF was to enable a content element to contain anything include other controls, media, what not!). The Xaml would look as





   1: <Label   Name="lblWithButtonAsContent"


   2:          Width="80"


   3:          Height="50"


   4:          Background="Red"


   5:          Padding="10">


   6:     <Button Name="btnWithCheckBoxContent">


   7:         <CheckBox>Wow!!</CheckBox>


   8:     </Button>


   9: </Label>




At the time we render this XAML, we first need to specify the loader class we use about the schema that the XAML entered uses. So we need to use .NET XML API to add namespaces. We could add namespace to each of the elements in the XAML or just add it to the root element. Shown below is the code that adds the following namespaces





   1: private string xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation";


   2: private string xmlns_x = http://schemas.microsoft.com/winfx/2006/xaml;




The code shown below creates an XmlDocument from the XAML entered and then it adds the namespaces if required.





   1: private XmlDocument GetXamlDoc()


   2: {


   3:            ///Xaml is XML. So we load the XAML as an XmlDocument.


   4:            /// The reason XmlDocument is used instead of XDocument is that we would like to add namespaces


   5:            /// so that the parsing is performed without issues. 


   6:            XmlDocument xdoc = new XmlDocument ( );


   7:            xdoc.LoadXml ( txtCode.Text ); //txtCode.Text contains the XAML


   8:  


   9:            ///We need to add the presentation framework namespace as well as the XAML namespace.


  10:            ///This way a <Button> like WPF objects would be properly identified.


  11:            if (string.IsNullOrEmpty ( xdoc.DocumentElement.GetAttribute ( "xmlns" ) )) xdoc.DocumentElement.SetAttribute ( "xmlns", xmlns );


  12:            if (string.IsNullOrEmpty ( xdoc.DocumentElement.GetAttribute ( "xmlns:x" ) )) xdoc.DocumentElement.SetAttribute ( "xmlns:x", xmlns_x );


  13:            return xdoc;


  14: }




Once a valid XAML document is ready, we now convert this Xaml into object and set it to the Content Property of a Content Element (a button or a frame). In the sample application, we use a frame.





   1: private object GetUIFromXaml ( )


   2: {


   3:             XmlDocument xdoc = GetXamlDoc();


   4:  


   5:             ///Now we are done with modifications, so we need an XmlReader. In this case, we use a XmlTextReader


   6:             /// We build a StringReader on the updated xml.


   7:             XmlTextReader xmlReader = new XmlTextReader ( new StringReader ( xdoc.OuterXml ) );


   8:  


   9:             ///The above code is all the ground work needed to successfully load Xaml at runtime.


  10:             ///The  XamlReader.Load() does the trick here. It compiles the Xaml into BAML and then builds the Object graph.


  11:             /// At the sametime, both the Visual Tree as well as the Logical Tree is constructed.


  12:             return XamlReader.Load ( xmlReader );


  13: }




The key is the XamlReader.Load() method which is given the XmlReader object (to the Xaml Code). It returns an object which could then be set to the content property.



Working with objects loaded at runtime from a Xaml file



Now that we are ready to load UI from a XAML file at runtime, we might want to see if we can attach events on these objects. Yes, we could attach events such as Click (for button) to these objects but is not as straight-forward. The code shown below does exactly what we are talking about.





   1: private void TestEvents ( DependencyObject dependencyObject )


   2: {


   3:     ( dependencyObject as FrameworkElement ).MouseMove += 


   4:                     new MouseEventHandler ( Page1_MouseMove );


   5: }


   6:  


   7: //invoked from Parse() method in the sample


   8: private void Parse()


   9: {


  10:     //code missing ...


  11:                object obj = GetUIFromXaml ( );


  12:                TestEvents ( obj as DependencyObject );


  13:     //code missing ...


  14: }


  15:  




Getting XAML from an object



XamlReader is used to read Xaml and convert the XAML into objects. There is a XamlWriter which does exactly the opposite. Given an object, XamlWriter can generate the corresponding XAML for that object. Shown below is the code that does that. Note that this does not work in the XBAP due to limitations on Reflection (considered as a security breach).





   1: public void SetXamlToTheCenterElement ( )


   2: {


   3:         lblCenter.Content = new TextBox ( )


   4:                                 {


   5:                                      Text = XamlWriter.Save ( this ),


   6:                                      Width = 200,


   7:                                      Height = 200,


   8:                                      TextWrapping = TextWrapping.Wrap


   9:                                  };


  10: }




The output looks like the one shown below.



image 



The XAML for the above window is simple and is shown below. Also note that, the call to the SetXamlToTheCenterElement ( ) is made after the InitializeComponent() from the constructor.





   1: <Window x:Class="EmptyWPF.Window1"


   2:     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"


   3:     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"


   4:     Title="Window1" Height="300" Width="300">


   5:     <DockPanel>


   6:         <Label DockPanel.Dock="Bottom" Background="Yellow">Bottom</Label>


   7:         <Label DockPanel.Dock="Top" Background="Red">Top</Label>


   8:         <Label DockPanel.Dock="Left" Background="Green">Left</Label>


   9:         <Label DockPanel.Dock="Right" Background="Maroon">Right</Label>


  10:         <Label HorizontalAlignment="Center" VerticalAlignment="Center" Name="lblCenter">Everything!</Label>


  11:     </DockPanel>


  12: </Window>




With the information that I shared until now, we could see that designing a WPF Form Designer is not as tough as it is in case of Windows Forms or other GUI technologies. In the subsequent posts, we look at the differences between the WinForms and WPF applications with respect to architecture as well as development.



Tools of trade



Blend, Visual Studio - Until now, for a Microsoft platform, Visual Studio has been the ultimate tool required. Now with WPF, Microsoft Blend appears to replace Visual Studio for Designers and for developers its Visual Studio again. VS 2008 Cider (WPF designer) is pretty neat and uses the same engine as the Blend. But the functionality that Blend provides is way ahead than what VS provides. Though this is a developer talk, we look at using Blend in the WPF animation demo.



Mole, Snoop - While Mole is a Visual Studio Debug Visualizer, Snoop is a stand alone tool. Mole allows us visualize WPF elements at runtime, change the properties and do a lot more stuff. For a professional application development, this is a handy tool and a must have in the kit.



KaXaml - A light-weight XAML editor and a tool that looks more like Blend with intellisense, syntax highlight, color picker, xml crunching, etc. kaXaml is a good replacement tool for XamlPad. Another alternative tool is the XamlPadX which supports add-ins and also has a visual tree visualizer, which kaxaml misses out.



Books, Blogs



Programming WPF - The treasure is always the information and not the tools. Firstly, the best book you can lay your hands upon is Programming WPF the book written by Chris Sells and Ian Griffiths, both of whom are excellent resources for anything that is .NET. If you wish to use WPF, you should buy this book.



Applications = Code + Markup - As always, Petzold book on WPF is the bible for a technology he writes on. Serious cons with this book is that it makes you sleep in no time given the bad appearance of MS Press books. But content, it undoubtedly gives a solid expertise.



Blogs - Tim Sneath has a list of WPF blogs that one must follow at this page. Personally I like the set of WPF gurus who are now at wpfdisciples.com. The amazing thing is that most of the stuff the blog about is mostly discussed in the Programming WPF book!



In the next post, we look at Visual Trees and Logical Trees in a WPF application.



Friday, May 02, 2008

Writing a research paper

This post is for my personal satisfaction, just like all my other posts. I have been working on my thesis on URL redirection and I have been "trying" to write a research paper to submit on Internet Measurement Conference 2008.
Writing a research paper is altogether a different field. I am pretty good at writing code, I write decent documentation and kind-of-ok tutorials on how to use stuff. But I really suck at writing a research paper. There are so many issues that needs to be taken care of.
The problem that I face is that, every time I make a revision to the paper, I find the outcome to be good and I feel that I am almost there. But then when I meet my professor and discuss the paper, I realize the paper is not good after all. There are so many silly mistakes and at a stretch, I am only good at two revisions. After that, I really need someone to pick up the mistakes. I guess the brain gets some what saturated and after certain point, we are no good at picking mistakes, unless you are experienced. After all this, I seriously think that I am not good for a Programming Writer position at Microsoft, which I seriously aimed for.
Moreover, I am applying for CPT work authorization, after which I might possibly and hopefully work for ImageRight writing ASP.NET software. By the way, I was informed by Cheryl from Javaground that I did clear the interview and they do have an offer for me. I was informed that Alex Kral, the CEO would talk to me about the offer. I am really excited to say the least but given the Californian conditions, I am again giving it a thought. But to be frank, I think that would be a totally cool job to take up and it would be a great learning experience. I would have to hear their offer and then make a decision based on that. But right now, I am looking towards the internship at Imageright. They have an internal project which I plan to complete by end of July. And if I get the CPT work authorization, I need to work on my ADO.NET skills seriously since it has been quiet a long time since I wrote any code ado.net. Frankly, I am not so good at ADO.NET. Let us see how it goes.
From all this, I really appreciate my major professor - Kang Li (http://cs.uga.edu/~kangli) for that he has been very supportive(though tough sometimes) in all aspects from the past one year. My first course at UGA was taught by him and since then I have been working with him. People at UGa, if you are reading this and if you are from computer science - do not be afraid of Kang Li or Lowenthal. They are all great professors but a little tough at times. I think the Dept of CS at UGA itself is the most friendly department I have ever seen.

Thursday, April 24, 2008

Making make files

So final class in the CSCI 1730 and Dave has covered make files for the undergraduate students. Alas, during my undergraduate studies we did not work much with Linux at school. Frankly, none of the lab instructors in my school were knowledgeable about Windows itself, leave aside make and stuff. They used to treat the school lab systems as their secret treasure and none of us were allowed to even check our mail. That sucks, I know, that really does. (I completed my Bachelor of Engineering in Information Technology, though I consider myself more of a computer science student than an IT personnel). Anyway, I will write down what I learnt more about make files.

Sample Makefile

Note that make files should have the name "Makefile". Invoking make reads this file for rules to be executed.

Calling just make, invokes the first rule and if you want any other rule to be executed you specify it "make ruleX".

batch: a b c

a: a1 a2

touch a

b: b1 b2

touch b

.....

.....

Here batch is the target for which a,b and c are dependencies. So the batch is only executed when the modification time of batch is different from that of a b or c. Again since a is dependent on a1 and a2, it has to be run only when a1 and a2 has different modification time. A rule with no dependencies always executes it with no considerations.

Make file to compile a C++ program

Suppose we have a main.cc which depends on List.h and List.cc and we wish to compile main.cc to get a main.out

build: clean compile

clean:

rm -rf main.out

compile: main.cc List.h List.cc

g++ main.cc List.h List.cc -o main.out

So do you always need to write a makefile? Well, the answer is no. For example, if you have a C++ program called "testmyprogram.cpp" and then you just type "make testmyprogram" then based on the extension .cpp it invokes the following command.

g++ testmyprogram.cpp -o testmyprogram

Well, this is kind of nice, especially when you do not want to make a file just for testing a program and best of all, when you are lazy like me. But it does not work for java programs, at least not on my terminal machine.

make -f AnotherMakefile

The above command takes in AnotherMakefile instead of Makefile.

Using "variables" in makefiles

Well, look at the following makefile

TARGETS=foo.o bar.o driver.o
CFLAGS=-g
CC=g++

driver: $(TARGETS)
       $(CC) $(TARGETS) -o driver

CFLAGS is an implicit flags variable which you do not need to mention when the rules are defined.

Where things can go wrong in Makefile

look the following code.

#include<stdio.h>
class Example
{
public:
int f1;
int f2;
int f3;
};


The foo.cc looks like this



#include "foo.h"

void func(Example &x);

main()
{
Example obj;
obj.f3
= 7;
printf(
"f3 :%d\n",obj.f3);
func(obj);
printf(
"f3: %d\n",obj.f3);
}



The bar.cc looks like this



#include"foo.h"

void func(Example *e)
{
e.f3
= 10;
}



Your makefile to build this is pretty simple, as shown.



prog: foo.o bar.o
g
++ -o prog foo.o bar.o

foo.o: foo.cc foo.h
g
++ -g -c foo.c

bar.o: bar.cc foo.h
g
++ -g -c bar.c

So running make and running the program output is pretty easy and you get to see the output as 7 and 10. Now when you remove the dependency on foo.h from the bar.o rule, comment out the field "int f2" from the foo.h. So when you run the make again, since foo.o depends on foo.h, it runs whereas the rule bar.o does not run and there for the bar.o still knows that Example has three fields(int f1,int f2 and int f3) whereas the foo.o believes Example has two fields only. So when you change f3 to 10 in bar.cc, it does so in the "third" field whereas f3 is the second field in f2.

 

So it is always good to remember that weird things happen when your Makefile is not correct. (In the above case, you saw something like a pointer bug).

 

Working with makedepend

 

Running the command "makedepend foo.cc bar.cc", it generates a Makefile with list of all depenedencies. makedepend is useful but not optimal. It goes through each of the project file specified, identifies the #includes and then further checks these includes to find out further dependencies. It looks like great tool to generate the dependencies. GooD!

 

I guess that is it for now, I hope to write about Jboost in the next post, hopefully.

Tuesday, April 22, 2008

Making sense out of Adaboost

So, atlast I could make some sense out of the Adaboost algorithm. Atlast I could make something that runs "adaboost". Though, I did not write code for the adaboost(In the past, I have and I did not have that great success). Until yesterday,  I could not understand what Adaboost was all about. Thanks to the lecture at videolectures.net, I now know what Adaboost is and what makes it run. Before I jump into practicals of running an Adaboost application, let me attempt to explain what Adaboost is in my own words.

What is Adaboost?

You have a bunch of "weak" classifiers, and an adaboost classifier is a strong classifier that is made by cascading these weak classifiers. When these classifiers are cascaded, they are multiplied with "weights" which tells how important this feature is.

Wait a second, what is a weak classifier?

Ok, a weak classifier is a classifier that could be understood as classifier that takes one feature and based on a rule, it outputs a class that this feature falls in. For example, I have a weak classifier that takes in "age" as the input feature and based on the rule that "if age is less than 18, he is a minor otherwise he is a major", the classifier returns "major" or "minor". So my classifier in Java could look something like this.

public PeopleClass classify(int age) {
         return (age<18)?PeopleClass.Minor:PeopleClass.Major;
}

So what is the big deal?

There is nothing great that we get with a weak classifier when it is used on its own. Just an age class would not help you identify if a person is rich or poor. But you have more than one such classifiers (such as salary, property, marital status, etc.). Together when these classifiers are used, they would form a single strong classifier which tells if you if the person whose features are given, is rich or not. But you cannot just add these classifiers (for now, take Minor as -1 and Major as +1) to get a total weighted value. You have to assign some "importance" to the features you input. So how do you decide how important a particular feature is? This is where the "training set" comes into play. Before, I jump in and give training details, you should know that sign(x) is +1 if x>0 and -1 if x<0 and 0 if x=0.

How does training work?

I would like to write a disclaimer that I am not an expert on Adaboost and probably half the stuff I wrote here is wrong. But what I write here is my understanding of Adaboost and hey! it works, at least for me. Now let us look into the training. In a training set, you give different feature-sets and for each feature-set you already know the class the object whose feature-set is the input, falls into. So your training set for a Richness classifier could look something like this.

//age,status,salary,property,habits,label

23,single,12000,100000,smoking drinking,poor
35,married,500000,5000000,none,rich
45,single,400000,3023000,none,rich

We have such a list of different possible inputs for the Adaboost classifier to train itself and learn what good weights are. So, the magic of the learning works and finally you have good estimate of weights. So later, if you input some feature-set whose class you do not know, then this weights are ideal for the classifier to spit out the class.

Java Implementation of AdaBoost

The theory behind Adaboost is so-far simple and yet it is not so easy to write your own implementation of Adaboost, may be you could write one if you have more in depth understanding of the pseudo-code than what I presented. Anyway, there is a good implementation of Adaboost called the JBoost library, which not only implements Adaboost but also implements few other learning algorithms. Jboost does not have good straight-forward step-by-step example and in my next post, I intend to give a step-by-step guide with application to skin-detection in images. With very simple features like R,G,B values of a pixel, the classifier generated by Jboost does great when it comes to true positives (it identifies all the skin pixels) but it does require improvement in the false positive aspect(it identifies non-skin pixels as skin pixels). Look out for this post and it would be very helpful for a lot of CS guys who works on Computer Vision, Machine Learning and other many fields where classifiers need to be used.

Sunday, April 13, 2008

Why game development?

Well, like I mentioned earlier, I have been thinking a lot about game development as a career. So this is what I think:
  1. Game developer needs to work a lot of overtime. In fact I read that quiet a few companies are exempted from overtime law if they hire developers for game development. I am not sure if it is true. General law says, a person who works 2-4 hours overtime should be paid 1.5 times the actual money, and twice after that. Anyway the point is that you work overtime a lot and the best part is that not even 1% of the community complains about it.
  2. You as a game developer gets to work on exciting projects all the time. As a mobile game developer , you get to learn a lot about writing optimized code, making the code portable otherwise port it somehow. I was informed by one of the devs from Javaground that they tend to port over 100 odd games every year and each game is ported onto at least different devices. That is like generating over 200,00 builds in 300 working days. And if my math is right, it is over 67 builds every day. That is amazing amount of "interesting work", not to forget the semi-annually releasing game-from-the-scratch of their own. Again, the best part is to have the honor of being involved in such an amazing work. As a normal developer, you would hardly be involved in 3-4 products in your lifetime as a developer. Be a mobile developer, you could be involved with so many different products all the time.
  3. After all my ranting about game devs writing optimized code all the time, there is a question - do I enjoy writing Employee e = new Employee(); or do I enjoy manipulating bytecode? Well, I am not sure about others, but I really enjoy working with hardware, I enjoy the fact that software is more closer to a person through a mobile device than through a PC(Of course, PC software is always great). So what is it different? Firstly, I am telling this based on my personal enthusiasm and I am very eager to be termed as Game Dev. Probably, if I miss the opportunity, I would be little disappointed(to say the least). Anyway, as a developer at Javaground, I imagine, I would be learning a lot of internals about JVM, about mobile phones, about ARM Processors and others, a lot about games. I was told that the entire team is amazing and it is for that reason that they come up with super-cool games (I just watched the demos)
Why should we hire you?
This was the question asked by the CTO of Javaground during the interview. I was not expecting such a question after a series of technical questions from different people. Anyway at that moment, I answered that I am a good programmer who plans his work well, who never misses deadlines and who is really good at translating requirements into working code. I guess, when I think over the question, even now I do not have a convincing answer, yet I know I make a good hire and a good team member.

So my wellwishers, who-so-ever is reading my blog between today and 25-April-2008, please pray that I get a good offer from Javaground, and if you are reading this after that day, then please pray for my success at whatever firm I am at.

Do I really understand Java? or Computer Science, for that matter?

Like I mentioned in my previous post, I was with Javaground being interviewed for the Developer position. It was an overall amazing and a great learning experience. I am so much thrilled for having interviewed with them that I have been thinking a lot on how I could be like them. The java we write is so lame. I gave a talk on optimizations and now I feel embarassed that I am not eligible to give such a talk. And I did cover a lot of material and left out a lot. But talking with the Javaground team made me realize that I am not as good I felt I was.

I was honored to be in their guest house along with a developer from their Canada team. He was Nigel and I should say that he was amazing and very impressive, very pleasant to talk and very down to earth. He told me simple things that no one would ever find in a book, I bet. So the aspect he told me was "comparisons with a 0(zero) is much faster than with any other numbers". This was just one of the quiet a lot of information he shared with me. Though not always "java" we talked about, he told me various other things - about life as a mobile developer, how mobile game works, stuff like that.

Anyway, I decided I would look into the "comparison with zero" to understand more. So just now I wrote two simple programs - Hello and Hello2. The Hello.java looks something like this:

public class Hello{
        public static void main(String[] args) {
                 int i = 0;
                 if(i < 1) System.out.println("Test");
        }
}

The result of running javap is shown. (After compiling with javac)
javap -c -private -verbose Hello

Let me show you the output ....

Compiled from Hello.java
public class Hello extends java.lang.Object {
    public Hello();
        /* Stack=1, Locals=1, Args_size=1 */
    public static void main(java.lang.String[]);
        /* Stack=2, Locals=2, Args_size=1 */
}

Method Hello()
   0 aload_0
   1 invokespecial #1 <Method java.lang.Object()>
   4 return

Method void main(java.lang.String[])
   0 iconst_0
   1 istore_1
   2 iload_1
   3 iconst_1
   4 if_icmpge 15
   7 getstatic #2 <Field java.io.PrintStream out>
  10 ldc #3 <String "test">
  12 invokevirtual #4 <Method void println(java.lang.String)>
  15 return

I have made the lines of interest bold. Now my Hello2.java looks like this:

public class Hello2{
        public static void main(String[] args) {
                 int i = 0;
                 if(i < 0) System.out.println("Test");
        }
}

Now let us look at the javap output shown in the listing.

Compiled from Hello2.java
public class Hello2 extends java.lang.Object {
    public Hello2();
        /* Stack=1, Locals=1, Args_size=1 */
    public static void main(java.lang.String[]);
        /* Stack=2, Locals=2, Args_size=1 */
}

Method Hello2()
   0 aload_0
   1 invokespecial #1 <Method java.lang.Object()>
   4 return

Method void main(java.lang.String[])
   0 iconst_0
   1 istore_1
   2 iload_1
   3 ifge 14
   6 getstatic #2 <Field java.io.PrintStream out>
   9 ldc #3 <String "test">
  11 invokevirtual #4 <Method void println(java.lang.String)>
  14 return

As you can see the highlighted section again, we would notice an operation missing. So let me put the areas of interest together, side by side.

i < 1

i < 0

   0 iconst_0
   1 istore_1
   2 iload_1
   3 iconst_1
   4 if_icmpge 15
   0 iconst_0
   1 istore_1
   2 iload_1
   3 ifge 14

Frankly, I do not understand the bytecode so well yet, but I do can make out that in comparison with a 1, there is an instruction that creates the constant 1. Where as for comparison with 0, that instruction is missing. I could recall something similar that we learning during Computer Architecture class and the Embedded Systems course that I attended. I wish I invested more time in those classes. How foolish I was back then?

This is not a big deal when you have server class machines or a laptop for that matter. Saving a couple of instructions - no big deal. But in a mobile environment, it makes sense. So out of 200000 odd lines that we write, if we could only save 2 instructions per 100 lines, that would save us 2000 instructions !!! and it is a lot given the limited resources of a mobile device.

I am very interested in gaining such knowledge and it is only possible, at the moment, when we work at companies like Javaground. I could get a job as a web developer or as a C# developer at any point of time in my life but opportunities like Javaground does not often come. And I have worked very hard for this opportunity. I gave 3 rigorous online tests, attended around 6 interviews and after all I wish if only I could prepare better. "If" i am lucky and "if" I get an offer from Javaground which is good enough for me to make a proper living, then I would see myself learning a lot from the immense talent that Javaground possess and hopefully one day see myself as one of their core people. I know there are a lot of such firms but at the moment, the only such firm that has interviewed me is Javaground. 

The two days made me realize, there is so much I should learn!

Friday, April 11, 2008

What is my favorite programming language?

Well this was one of the tons of questions I was asked during my interview with Javaground. Anyway the environment at the company looked so serious and everyone was kind of busy all the time. I like such a challenging environment and have to see if I was "good enough" to be a part of it. I have an offer with a service company E*Trade but I am not too sure about it. Unless the pay is relatively less at Javaground, I do not want to lose an opportunity to work for them. If I work at Javaground, I would:
1. write optimized code, probably someday write a whole new book on code optimization.
2. work with one of the best minds in the software industry. great developers and everyone talks about compact and great code.
3. better future - game devs make a lot of 1. money 2. fame 3. knowledge about s/w and h/w.

Atleast from what I see, I think they are looking for a good programmer who has strong basics and knows what he writes.
What is my favorite question?
Xavier Kral, the CTO of javaground raised this question. I always felt different about different languages. So let me start one by one.
C - Definitely not my favorite.
C++ - Great language, but then not my favorite - I do not admire or adore pointers
Java - definitely a contender. Write great software in less amount of time. Java is a cool language. Come Java 7 you have closures and it would revamp the style of Java code.
C# - Right now, my best language. The language I am most good at. The C# 3.0 features are amazing.
Groovy - Definitely a great scripting language that is on top of JAva.
So what is my favorite? I feel confused. When I work on Java for a long time, I feel Java is the best thing that has happened to the developer community. But when I work on C# for a long time, I feel C# is much better than Java. So which is my best language? - I prefer C# when working on windows and I prefer Java when I want something on Linux. Both has its pros and cons.
Why game developer job?
The charisma of a game developer is totally different. A game developer is more attractive to girls than a mainframe developer. I am kidding, but I like the challenge to work on real projects which constantly puts your skill to think and code to test. It is great to actually feel as a game developer. So again the reasons I list out are:
1. Game dev make a lot of money, if not now atleast in the near future.
2. Game dev tittle is more attractive than anything else.
3. If there is a possibility that I would own my company or become a major part of a startup, then it is possible only in the Game Development Industry.
4. Even if the economy is not all that great, Game Industry will always survive -> I would always be in demand and it would only increase with time.
5. If I work hard enough, I would end up becoming a very popular developer in the community.
6. The amount of knowledge you gain as a game developer is immense. You create a form of life in the form of games and you should feel close to god!

Wednesday, April 09, 2008

What's with Orkut?


So orkut is owned by Google - nice move by Google to make itself believe that its in all domains on the internet. Agreed Google is great but what I find strange is that Orkut still runs on ASP.NET and I guess, even the newer developments in orkut are using ASP.NET. And we should not forget that google and microsoft are no friends.
So is orkut well designed?
I guess not. I show you two screen shots of my profile taken at the same time...I know what is wrong and I consider it to be a silly thing. so what is the problem? I see different scrap count in the profile page for every two clicks ... and yeah it has nothing to do with the clicks. I guess it is the problem with caching that asp.net does(actually the caching that these people has implemented.

how long does it take to fix?
Things are so sweet with asp.net that you can design a full fledged portal like orkut in no time. I bet it would take some avg dev like me to write orkut in one week with no bugs. and yeah I did one version of orkut in java servlets and I am confident about what i say. So to fix these problems, it would not take more than 30 minutes.

So my final thoughts are - if you hate something, hate it properly, if you like something then do not act as if you hate it. By the way, I do not hate orkut, I just do not like the way its being taken care of. Google, if it ASP.net sucks(along with Microsoft) then why would you want to use it. Use GWT and rewrite orkut, your "smart" developers whom you pick after 10 rounds of interviews(out of which 6 tests your english), could rewrite orkut in no less than a week. That way you would not have dummies like me pointing fingers. Rewrite orkut else make it even better. Look at facebook - its done in php and it is an awesome application.