Sunday 30 December 2012

Job Execution API v0.1b is now available!

I have been working on this for a while and now I have finally released it. This is 0.1 beta so it may contain bugs. However, I am working on it constantly and am trying to improve the API.

Job Execution API is all about job execution in Java. You have jobs which comprise of tasks. Each task is a class implementing the ITask interface. For now, the task is not Async so tasks are executed sequentially, in linear pattern. I intend to provide basic tasks which you can use to create standard jobs. You can later extend these tasks and make your own.

Download the API here and let me know how it goes:
https://www.box.com/s/6cnn93gkrjmuf39sp12d

Monday 27 August 2012

API for recognizing gestures in Android

I have been busy lately. For most of the time, I have been working on gesture API for android. Android already has a built in gesture API but to actually use it, you have to apply mathematics which makes it a bit comlicated for a normal Android developer. AGAPI (Accelerometer Gesture API) adds a layer of abstraction over the existing gesture API to make it easier to recognize gestures. Using AGAPI is very simple. Implement the ShakeListener or any gesture listener class. Register your listener to ShakeManager or corresponding gesture manager instance. Write your code in OnShake or in corresponding event methods and BAM! Your gesture rich application is ready! At this stage of development, the Shake gesture is ready to use. You can get the API here.

Note: This API is licensed under Apache License 2.0.

Friday 27 April 2012

Linux - Windows comparison


Well, I wrote the following article a year ago. A YEAR AGO! I'm actually amazed that I wrote such a thing. Well, so... Here it goes...

Linux, as you all know, is a free-open source operating system. Inspire of having number of advantages over Windows, Linux is still free and of course open source. Now, you might be thinking why I'm using terms 'free' and 'open' source separately. 'Free' means that Linux is freely available and downloadable from internet. Some of the vendors like 'Ubuntu' offer CDs loaded with Linux absolutely free of cost. Open source means that if you know kernel programming and mechanics of operating system, then you can actually tweak Linux and also program Linux from a scratch. That's open source and Linux provides that flexibility. Unlike Linux, Windows is not open source. It does not allow user to modify its kernel or components. This is one of the reasons why Linux is hot favourite among young developers.

What separates them?
The main difference between Linux and windows is their build. Practically, Windows is created only by Microsoft Corporation while Linux has been created and tweaked by entire world! Why entire world? Because, it's open source. If I have Linux and I find a bug, then I can tweak and remove that thing myself. I also tell the organization about the bug which I fixed. So, they verify it and tell their rest of the consumers about the fix. So, that's how it all works. With windows, it is not like that. I must appreciate Microsoft’s efforts in improving windows because in new versions of windows – The Vista Series – they have put an improved version of error reporting like Problems Report and Solutions. With that you can just submit the error report. You cannot tell them how to fix that even if you know. Of course, you cannot fix grave errors in windows even if you think because it's not open source!



Who's better on performance?
Practically, on considering stable releases of Linux offered by several organizations like Ubuntu, Debian, Fedora, etc., no doubt Linux outperforms Windows. Windows has always been a bulky operating system taking several minutes to boot up, then a minute to get stable and so on. While with Linux, running on an average PC, booting up is a child's play for Linux, 10 – 15 seconds is a limit. Even if 'background processing' indicator on mouse cursor is on, you can still get your stuff by clicking. Exploring your computer is just with double-click of a button. You'll never find this speed on Windows!
Also, shutting down your PC is a matter of 5-6 seconds for Linux. And what's more? Linux works on a 1 GHz PC with 128 MB RAM and even 10 GB Hard Drive!

What's your colour today?
Unlike Windows, Linux provides a lot of customization features. It is so flexible that you can customize almost everything. From changing your wallpaper to behaviour and animation of minimizing/maximizing a window, you can change and tweak everything. Linux also provides various desktop effects – some of which even require a 3D card – which are super cool.
For Linux, wallpapers are billions, themes are millions, and yet there are thousands of programs that help even more to customize Linux. Also various types of desktop environment are available on Linux like GNOME (Most common with cool GUI), KDE (High end graphical interface), and Xfce (Fastest of all). These desktop environments not only handle the look and feel of the Linux environment but also provide you with lot of other flexibilities. Instead of trying out new desktop environments, I prefer to GNOME and its cool Compiz-Fusion Desktop effects which tweak almost all aspects of the operating system. In customization, Linux easily overcomes Windows.

Applications?
This is where Linux gets outperformed. Almost 91% of the applications available in the market run on windows. 5% work on Mac OS X, 3% of it in Linux and the rest are for other OS. Windows has its roots wide-spread all over the world because it was the first OS to offer the idea of multi-tasking and a lot more new features that were not even thought of at that time. While Linux – which is not that old but still is not as old as windows – has relatively very less number of applications available worldwide. Linux is rapidly getting wide spread in the world of computing because it is a lot more flexible and offers a lot more possibilities than Windows. Linux offers its developers great flexibility of working with applications. Previously, Linux was called non-user friendly because it was difficult to operate but now that it has been tweaked and is available in several forms, Linux has removed this badge of dishonour from itself.
Organizations like Ubuntu etc. have made Linux user friendly and easy to use operating system that provides its users with number of options which makes it easy to use.

Running Windows on Linux?
Also, now you can run Windows applications on Linux. With 'Wine' – an application for Linux – you can run windows applications and programs on Linux. Wine uses its DLL library to run Windows applications. If you dual boot Windows and Linux, then it'll be better. Wine uses Windows library and its own library in combination to run the application smoothly. Wine also has configuration screen where, you can select in which mode Wine should work. There are several modes available based on Windows OS Released. On my Linux, there are following modes:
• Windows Vista
• Windows XP
• Windows Me
• Windows 98
• Windows 3.0
And several others including server editions which I cannot recall right now.
Each of these modes create a separate environment for the application to run smoothly. Here, environment does not mean that your Linux look would change. You won't even notice that! So, are you thinking of running Windows Games on your Linux? Don't dream that! It won't run. Games are called as hefty softwares that require large amount of resources and also they have some of functions which are accessible to them in Windows but not in Linux. However, these people are trying a lot to make each and every application of Windows run on Linux. Good luck to them!

Where's the security?
Linux has security from viruses. Don't think that an antivirus system has been integrated to it. It isn't in this case. Because, Linux does not support viruses! Yes, Viruses don't run on Linux because they find it hard to harass you while you are logged in. Surprised? Ok, let’s be frank. There's one virus on Linux and that's – Bliss. But just think of it. Linux has just one virus to support while Windows is entirely surrounded by viruses. Viruses for Windows – maybe billions – Viruses for Linux – Just One!! And that too is not going to do any big thing to your computer! So, here we have arrived to the point where we must say that Linux is too stout to respond to viruses. Consider a case where a burglar has entered a bank, he shows a gun, fires in the air and expects people to panic. But what happens? People ignore him! He shoots at the cashier but finds that his guns do not work against him. Bullets just fall down touching the cashier! This is the case when virus enters into Linux. Virus would try hard to do harm but Linux won't execute any operations that virus has told. Virus will try to infiltrate your files but that also would not work because unlike windows, Linux is not having applications chained.

Little things that matter!
Yet, there are a lot of little things offered by Linux that provide great advantage over Windows. First of all, Linux has a 'Force Quit' feature. If you find any misbehaving application (Though you'll rarely find) that's taking too long to respond, you can use Force Quit. Force quit is a utility provided in Linux which immediately exits a non-responding application. So, you won't need to wait minutes for a non-responding application to end. Sometimes, you'll find that in windows, when an application does not respond, then your computer will also not respond. This happens because in windows, all applications are chained. When running applications are chained, they all get affected if one of them stops responding. This is not the case in Linux, In Linux, applications work independently, meaning, that they are not chained. So, if any damn application gets 'hanged' your computer and other applications will continue working in full swing. Second advantage in Linux, that it has an in-built archive manager. With archive manager, you can handle multiple types of archives without installing a separate program for it. Linux also has a highly advanced calculator with three extended modes which are 'Advanced', 'Financial' and 'Programming'. Linux also comes with Password and Encryption key manager which allows you to create passwords for applications and folders. It also allows you to create encryption keys whose strength ranges from 2048 bits to 4096 bits. With that, you can encrypt archives, files and folders to ensure that they are safe. Many Linux editions also allow you to change the way login screen looks and behaviour of the boot loader and its appearance. Linux also allows you to scale CPU usage. Meaning, you can set how much of the CPU power Linux should use. This helps you a lot in saving power. Suppose, you are reading an eBook on your Linux PC during a journey, if you were using windows, and even in power saver mode, you'll drain a lot of battery. But in Linux, it dims the display automatically. Now, reading an eBook does not require processing power. So, you can set the value to least mode. In this way, Linux will stop most of background processes which drain battery and will ensure that the battery is saved. Now, as were discussing about battery, it reminds me of an amazing feature that Linux provides. Linux has an in-built system that provides detailed information on the battery installed on your laptop. It includes details like your battery model, version, status, and vendor. These details are common in windows. Excluding these, it also tells you details about battery technology, serial number, current charge capacity of battery(in %), current charge(in watt-hour), last full charge(in watt-hour) and design charge(in watt-hour). It also provides you with information based on graphs too! I'm sure that these features are not available on windows.
If you refer to new versions of windows, in Vista line, you’ll find that they are having preview panes. The moment, you select an item, its preview (if available) is shown in the preview pane. Previews are available for pictures, music, videos and some other types. Suppose, I click a music file. If my computer or rather Windows media player has that plugin, then it will show a mini media player in the preview pane with a play button. If I click play button, it will search the plugin in Windows Media library and then it will play the file. On my VAIO BZ, windows music preview does not work correctly. For the first file I play on starting the computer, it takes a lot of time in loading the preview pane. After that it plays the file. Now, Ubuntu Linux 9.04 has something new to offer. Now, unlike windows, Ubuntu has a 'Movie Player' as default player. While exploring my computer, if I stumble upon a music file which I want to preview, I simply hover my mouse over it and immediately, it'll start playing the file. But unfortunately in this technique, pausing is not possible. If I move down my mouse from that music file, the file immediately stops playing. Ubuntu also does not offer a seek bar!
Also, there's one thing where Linux surrenders. It's Silverlight Experience! At Windows, you have Silverlight integrated in Windows Internet Explorer as well as many other web browsers like Firefox. But, in Ubuntu (or I assume in most of Linux operating systems) Silverlight isn't available. Yes, if you do visit a website featuring Silverlight, it'll tell you to download an alternative version of Silverlight as moonlight but even after downloading moon light, I can't get Silverlight experience – It still says that Silverlight is missing.
So, what do you learn from this? Most of all high-end Microsoft technologies aren't shared by Microsoft.
For all Photoshop editors, Linux is a disappointment because there's probably no Linux edition for adobe Photoshop.
Now, Linux also has an in built application called Disk Analyser. It is an application which tells you what folder has been eating, rather reserving your disk space. It is very useful application in that way because it lets you know what to delete to free your space. It not only tells you about your file system but tells you the 'free space sharing' on any other device that you connect. In this case, windows gets defeated. It's not having an in built application for this, so, you'll have to wander-on-the-web to get one!
I've heard that Linux produces outstanding graphics but I haven't seen it in action and therefore I tell you about that so sure. But I think that it would be able to produce out-standing graphics because it's swift. Windows and other operating system themselves allocate very high memory and therefore they have relatively less to dedicate for graphics. Whereas in Linux, this case is totally different. Linux itself uses very less of your RAM as well as your hard drive. So, it can dedicate more graphics to your games and all that stuff. This is just a guess and I am not so sure about it. Built-in games of Linux are very standard – sort of only two-dimensional and therefore, you cannot judge its actual capacity. However, some of real 3D games are available but aren't satisfactory because they aren't developed that passionately. I purely do not mean to discourage or hurt the Linux game developers but despite of such nice capabilities of Linux to handle the resources you won't get any game on Linux that can compete the one on windows. This might be because the real 'expert' game developers are looking for money and hence they are moving towards development of games for windows as most of the high-end games in windows aren't free. Now, you might be wondering about 3D modelling software like Maya? As of now, I haven't encountered any such software but I am still looking for it. There must be some sort of software available on Linux. Don't worry, you'll obviously find one.

Speed with appearance?
This is very easy question to answer – You compromise speed, you'll get speed. But after you use Linux, you'll probably disagree with this. Even after using themes and effects, you'll observe that your working speed has been little affected. Shocked? I was too but I soon discovered this myself on my computer. Of course, you might suffer from a sort of decrease in speed at first but this decrease in speed will be rather unnoticed by you unless you are using a computer that's got a configuration which is just on the minimum system requirements of Linux. Now, if you know this, then there are different window managers in Linux. Most popular and used is GNOME. Still, there are two other types called KDE and Xfce. GNOME is for a computer user who wants both speed and appearance. KDE is for one who wants very cool appearance, mostly for high-fi users. Xfce us mostly used by users who have very low system requirements and want speed. Now, this is not always true because some users who just don't care about appearance even after having a high-end system use Xfce. Another one, which is not a window manager (Though most of users think it is), is Compiz Fusion. It accelerates the appearance of your system and allows you to perform a lot more tweaks like changing the open/close/minimize/maximize animations, window borders, various effects and things like modifying the application switcher method. All these will be better understood by you if you use hands on approach and get at least a Live CD of Ubuntu Linux. Different window managers provide their own options of modifying the appearance on Linux while on windows? You know, you'll have to stick to the like or not Windows own window manager. Now this is mostly attracting to users but if you consider old versions, then they weren't attractive. But now, considering Windows Vista and Windows 7, they seem to be cool. Still, you don't get options of really 'modifying' them. Don't tell me about the 'themes' option. That's of no use. If you want to change desktop background and other sorts of things without affecting the real appearance, then it's better to do it yourself rather than depending on it.
Still thinking of Windows? Think again! Because Linux is used by huge servers and supercomputers. It's their choice because they rely on the usability, flexibility and resource management of Linux. Shouldn't you rely on it?

Sunday 22 April 2012

Concurrency and thread synchronization in Java

There are various problems while working with multiple threads. One of them is resource access. If both of the threads are trying to access a single resource, chances are that they will wind up. If the resource is shareable, then it might cause glitches in the system. For instance, picture a situation where two threads are trying to print two different files on a printer. It might happen that printer would print one character from one file and another character from another file. This would result in a jumbled up situation. Solution to this is concurrency. It is to make sure that only one thread accesses one resource at a time. Luckily, Java has pretty straight forward solution for this. If you have a method and if you wish to make it such that only one thread can access it at a time, put keyword 'synchronized' in it. So, if I have a method to print a line, it will be:

public synchronized void print(String s)


The word 'synchronized' in the method signature makes sure that only one thread uses that method until it finishes execution. If two threads are trying to access it, the other one will have to wait while the first method finishes its execution.

Watch the video here:

Tuesday 17 April 2012

How to use Timers in Java?

Well, this post will be similar to the one about Threading. However, it is an important concept and thus needs to be covered. First of all, to time a certain task, you will have to make a Timer object. However, a timer object needs to have a TimerTask object. Now, TimerTask is an abstract class and has a run method which gets called on set frequency. So, for instance, if the frequency of the task has been set to 2000 ms, then the run method gets called every 2000 ms. To use Timers, you will have to create your own class which extends the TimerTask class. This would be something like:

 public class SomeTask extends TimerTask{
    @Override
    public void run() {
        //Something to do here...
    }
}


If you are going to access UI elements of a particular JFrame from your SomeTask class, then you will have to pass a reference of that JFrame in its class constructor. This is because all your UI elements are private and thus cannot be accessed by an external class. You will also have to make methods which would access your private UI elements in the NewJFrame. For a JFrame called NewJFrame, the code would look like:

public class SomeTask extends TimerTask{

    NewJFrame parent;
    public SomeTask(NewJFrame frame){
        parent = frame;
    }
   
    @Override
    public void run() {
        //Do work here
    }
}


If you want to type Hello every five seconds to a JTextArea in NewJFrame, then you'll first have to create a method that would do that in your NewJFrame. This method can be as simple as:

public void type(){
     jTextArea1.append("Hello\n");
}


Now, access this method from the run() method of your timer task simply by:

parent.type();

To run this task, you will have to make a timer by:

Timer t = new Timer();

Then, create a new object of SomeTask class that you just created.

SomeTask st = new SomeTask(this);

Notice 'this' in the constructor. It is because we asked for it in the class constructor as the task needs to access the UI elements. Now schedule that task by:

t.schedule(st,0,2000);

The above line takes three parameters. First is the TimerTask object, which in this case is the SomeTask object called st. Second is the intial delay (in ms) which is concerned with how long will it take to start the task for the first time and the third parameter is the frequency of the task which in this case is 2000 ms.

Thats it! Now you have scheduled your task and it will run almost instantly (0 ms delay). It will keep running every 2 seconds (2000 ms) until someone calls:

st.cancel();

Which will stop the task from running.

Watch the video tutorial here:

Sunday 15 April 2012

Threading in Java

Every thread in Java needs a Runnable. To make a runnable, you must first create a class which implements the Runnable interface. Runnable interface has a method called run() which gets called by the Thread. Your class will need to have this method. Put your code in this run() method. Your Runnable class should look similar to:

public class Work implements Runnable{

    @Override
    public void run() {
        //do some work..
    }

}
Now, you can create a thread in multiple ways but the most appropriate way is to pass the runnable object in its constructor.

Thread thread1 = new Thread(new Work());
Work work = new Work();
Thread thread2 = new Thread(work);


thread1 and thread2 are both valid threads. Now to start a thread, just write:

thread1.start();
thread2.start();
Make sure that you say thread1.start() and not thread1.run(). thread1.run() simply calls the run method within the runnable while thread1.start() runs the run method in separate thread.

Thats it! Now you know the basics of threading in Java!

Watch the video tutorial here:

Thursday 23 February 2012

Using SCLC (Source Code Line Counter)

Well, it is really very simple. Here you go:
  1. Download the file. You can get it from here.
  2. Double click it. It should open as any other normal application.
    1. If it doesn't open as expected or opens WinRAR/WinZIP/7-Zip or any other archiving software, follow here:
      1. Right click the file and point to Open With.
      2. Click on Select Default Program.
      3. Java should be here in the list of programs. If it isn't then click browse and locate your java installation. It should be in C:\Program Files\Java\jre7\bin\java.exe
        1. If you dont have any folder called Java in Program files, then go to www.java.com and download and install it first.
        2. Once Java is installed, follow step 2.
      4. Click OK. Follow step 2.
  3. Click on 'Add File' button to add files to it. A dialog box will be presented.
  4. Locate your source code files. You can select more than one file by selecting one file and then holding the 'Ctrl' key and selecting other files. Alternatively, if you wish to select all files, you can press 'Ctrl + A' to select all files in the directory you are in.
    1. Make sure that you do not select any executable files. This may cause an error.
  5. Click OK/Open.
  6. You should see list of files in the list above 'Add File' button. If you wish to add more files, follow step 3.
  7. Once you are done, click Start. It will start counting lines in the files you have selected.
  8. You're done! The table will display number of code lines in each file and below the table you'll find total line count and line density. 
I hope you like it. If you do/don't, give me feedback by commenting below. Have fun!

Count lines of code you've written!

For those of you who enjoy programming, having a curiosity about knowing number of lines of code that you've written is very common. It is easy to know that by simply scrolling down and looking at the last number. However, if your code is distributed into different classes, knowing total lines of code would be very hard. I had the same problem and hence to solve that, I created an application in Java. You simply add files whose lines you want to count and click the start button. The application will display number of lines in each file, total line count and average line density in each file. This is very simple, effective and accurate way of counting lines of code that you have written. You can download the file by clicking download below:


For usage instructions, click here.
I hope you like it. Enjoy!

Monday 13 February 2012

Conditions in Linux Shell Script

If statements are important in any programming language. I had a bit of hard time while doing if statements in linux since they are different than those in a conventional programming language. First of all, an if statement to compare whether a value in a variable val1 is equal to 5 is like:

val1=5
if [ $val1 -eq 5 ]
then
     Code here to do some stuff
else
     If above condition is false, then code here gets executed
fi
Note that spaces are important when defining condition. $val1 refers to the variable and -eq simply implies equal to operator to compare if the $val1 is equal to 5.


Seems pretty easy? It is. Other conditional operators are:


Conditional OperatorLinux Equivalent
Greater than-gt
Less than-lt
Equal to-eq
Not equal to-ne

Now, if I want to compare strings, for instance, if variable answer is equal to "yes" then the code will be as follows:


if [ "$val" = "yes" ]
then
     Code here to do some stuff
fi


Again, spaces are important here.
In here, '=' can easily be replaced by conventional conditional operators like '>' or '<' or '!=' etc.

Variables in Linux Shell Script

Well, this has been a bit tricky for me so I decided to put it on my blog so that it can be helpful to you guys.

First of all, How to define a variable?


count=0

There! I've just defined a variable count with 0 as its initial value.
Now, How do you print value of a variable?

echo "$count"

or

echo $count

Next. How do you perform calculations on a variable?
Okay. So assume that you have two variables called val1 and val2 with values 3 and 4 respectively. Now, you want val3 to have the addition of val1 and val2. So,


val1=3
val2=4
val3=`expr $val1 + $val2`

Similarly, to do subtraction:

val4=`expr $val1 - $val2`


Note that spaces are very important here.

Now, if you wish to assign value returned by a command to a variable, then it works by doing:

wcount=`wc -w myfile.txt`

anything between ` and ` will be executed as linux command and the value returned by that command will be assigned back to the variable to left.

Sunday 12 February 2012

How did I solve my problem of viewing images quickly...

I've been quite busy lately. If you are a curious PC user, then you might have noticed that the photo viewing programs that your PC comes with aren't as efficient and fast as they should be. I was extremely annoyed when the Windows Live Photo Viewer took 2 minutes to load my photo. It does have features like photo editing etc but I rarely use them. All I want is to view my pictures one by one. I don't think I should wait 2 minutes for the program to load features which I am not going to use. Hence, to solve this problem, I used, an uncommon approach. I designed my own image viewing software. I think that the best way to solve your problem is to create your own solution, rather than finding a solution.
This new software that I just created in one hour simply shows your pictures. You double-click a picture and it will open in Image Viewer. It opens in a flash and I love it. You can also open the image viewer and open a picture by clicking on Open button. Also, once you open a picture, it loads all pictures in memory and allows you to navigate through.
I will be publishing the source for this software soon so that it can be useful to you guys.

Try out the Image Viewer now!

Instructions:
  • The download is an EXE file.
  • No setup is required. Simply double click the EXE file and that will run the program.
  • If you wish to attach the program to a picture file, then right click the picture > Open With... > Select default program. Click on browse and locate the EXE file. Make sure that the checkbox below is checked and click Ok. 
Post any bugs or suggestions in comments below. Thanks!

Tuesday 31 January 2012

How to extract words from a string in C# (Split string)

This is incredibly easy in C#. First of all, you need to have a string from which you want to extract words. A word is a string separated by spaces. To do that, just say:

string s = "Welcome to my blog!";

Now, when I use the split command, it will return an array of individual strings. So, the implementation will be:

string[] words = s.Split(" ",StringSplitOptions.RemoveEmptyEntries);

As a result, words will have "Welcome", "to", "my", "blog!" in it.

Thursday 26 January 2012

Google Chrome versus Mozilla Firefox

Well, they said that Mozilla firefox is the most efficient browser. I wasn't satisfied. Hence, I went to check. I am a big fan of Google Chrome. However, I recently learnt that chrome collects browsing information. That didn't sound good to me and hence I switched to Mozilla Firefox. On the download page, it said that it is the most efficient browser. I downloaded it, but initially I had some issues. It lagged a bit when I used it on my laptop. However, when I used it on my university's mac (with Windows 7 installed) it was smooth. Hence I was suspicious. I had to check. I closed all applications, refreshed the page few times and fired up Mozilla Firefox and Google Chrome.

I opened up www.sciencedaily.com in both the browsers. I fired up Task Manager only to find that Google chrome had three simultaneous processes and firefox had one. This probably means that it is doing multi-threading a lot and has a lot of external handlers. It is a good practice though when you are programming something like a web browser. However, I counted the memory allocated and firefox had like 88,000 and Google Chrome had in total something like 50,000. I was surprised.

Then, to satisfy myself that Firefox is better, I opened two tabs in both chrome and firefox. In one tab, I opened the google home page and in another I opened up www.sciencedaily.com. This time, I hoped chrome to jump up. The task manager showed that chrome had four processes, one more than last time I had seen and firefox still had one process. In terms of memory, firefox allocated something like 120,000 and chrome took something like 90,000. I was even more surprised. My quick analysis at that point was that the memory print of chrome increases rapidly with increase in number of tabs while in same conditions, that of firefox increases at relatively slower rate.

In the third test, in which I seriously hoped firefox to win, I opened up four tabs as follows:
1. Tab 1: www.google.com
2. Tab 2: www.sciencedaily.com
3. Tab 3: www.bing.com
4. Tab 4: news.google.com

This time, firefox really won. Its memory print was around 143,000 while at the same time, that of chrome was around 150,000. Yayy! Victory at last!

So, well, what does this tell to average computer user? I will still be using firefox. However, if I quickly want to check something like a definition or address, I'd use chrome. However, for tab intensive stuff like research and like that, I will be using firefox.

FYI:
Chrome: 12.0.742.122
Firefox: 5.0

Tuesday 24 January 2012

How do I do threading in C#?


Threading in C# is no big deal. It has the easiest implementation I've ever seen. First of all, you need to have a method that you want to execute on a different thread. For this instance, I'll put method called Calculate(). Now, this method has to be a void. However, it can take any amount of parameters. So, it can be:

public void Calculate()

or

public void Calculate(int x, int y)

Now that we know what to execute, we need to create a thread with this method. This is done by:

Thread t = new Thread(Calculate());

I can now run the thread by typing:

t.Start();

See Also: How do I do threaded programming in Java?

How do I do threaded programming in Java?


My favorite concept in any programming language is Threading. It is awesome. This time, I'll get started straight away!

First of all, before making a thread in java, you need a runnable. Runnable is basically like a piece of code that you want to execute as a separate thread. There are two ways to create a runnable. You can do it by making an anonymous class such as:

Runnable r = new Runnable(){

public void run(){


//Your code goes here...


}
}
However, this is not a good practice. Hence, it is advised to create a separate class which implements the Runnable interface like:


public class MyNewRunnable implements Runnable{


MyNewRunnable(){


}


public void run(){
//Your code here...
}
}

In this manner, you can pass any parameters for processing the information using the class constructor. For instance, if you are making a runnable for downloading files, you can pass url of the file through the class constructor. Now, once you have created your runnable, you need a thread in which you have to put the runnable. Then you run the thread, the run method of runnable gets executed. For runnable r, you can make a thread as follows:

Thread t = new Thread(r);

Then, you can start the thread by typing:

t.start();

I'd say that threading would help make your program more responsive. This is solely because of the fact that all the heavy processor hungry tasks are carried out in a separate thread and the UI thread is kept clean.

See Also: How do I do threading in C#?

Sunday 22 January 2012

How to make a login in ASP .NET C#

In this post, I will teach you guys about making a simple login using common page controls. First of all, you need two textboxes, one for username and another for password. I'll call them usernameTextBox and passwordTextBox for this example. Drag down a button and call it loginButton. Now, in the OnClick event of loginButton, you need to check if the provided combination of username and password is correct or not. You can only do this if you have username and passwords stored somewhere. It is recommended to use a database to do this. Create a AccountDetails table in your database. The table should have username and password fields, both as text (VARCHAR for SQL). The way login is going to work is that you select records from AccountDetails table who have the provided username and password. This query should return one row if the combination matches. If not, then it should return nothing. Here's the query you need to pass:

string query = "SELECT * FROM AccountDetails WHERE username='"+usernameTextBox.Text + "' AND pass='" + passwordTextBox.Text + "'";
Supply this query to the command object. This can be OleDbCommand or SqlCommand depending on your type of database. Invoke the ExecuteReader method of the command object and then check if the Read method of the DataReader object returns true. If it does then this means that the login is successful. If not, then login is invalid. Here's a sample code.

string connectionString = "...";
OleDbConnection conn = new OleDbConnection(connectionString);
conn.Open();
string queryString = "SELECT * FROM AccountDetails WHERE username='"+usernameTextBox.Text + "' AND pass='" + passwordTextBox.Text + "'";
OleDbCommand command = new OleDbCommand(queryString, conn);
OleDbDataReader reader = command.ExecuteReader();
if(reader.Read()){
//Login is successful.
}else{
//Login failed.
}
Thats it! Your ASP website should now have a wonderful login to allow geniune users. To extend its capabilities, store the username in a session and then in PageLoad event of rest of the pages which require login, check if the session contains something. If it is null, then the page should redirect to login page. Same if for log-out. In the PageLoad event of the login page, check if the session username contains something. If it does, then clear out the session and display some notification saying that the user has been logged out. Now, in your page, to which the user gets redirected after successful login, put a simple link to login.

Now, initially when user lands on the login page, the session username will be empty. However, on typing correct username and password, this session gets filled with the username of the logged user and he/she is redirected to some sort of dashboard page. When the user clicks on the log-out link, he/she gets redirected to the login page which first checks if there is anything in the session. Since the user has previously logged in, there will be a username inside that session. Login page clears it out and displays a message saying that the user has been logged out. I hope that was easy.

If you have any queries or doubts, feel free to comment below.
If you want to know how session works, click here to see my post on Sessions.

Friday 20 January 2012

Using Sessions in ASP .NET


Well, believe it or not, Session is the most important thing when it comes to web design. I used to hate it but now I am a big fan of it. Trust me. You will like it once you get hang of it. So, in this post, I will be teaching you about using them. First of all, a session is like a small memory pit where you can store values. Values in session are lost once the browser closes. However, they stay the same even if you change the page or open new tab. Hence, sessions are used to pass values from one page to another.

You can store an object in session. It can be int, double, string or any other FooClass object that you have defined. This is the main benefit of it. However, when taking values back, you need to make sure that you cast them back to its same original form. Here's how you store value in a session. Let me define some variables.

int i=2;
string s="Hello";
FooClass foo = new FooClass();
Now, I will store each of them in session. To store a value, you need to give a session name. This must be unique. You must remember this because you will have to use it to extract value out of session. Here's how you do it:

Session["someIntegerVariable"] = i;
Session["someStringVariable"] = s;
Session["someFooClassObject"] = foo;
Now that I have all of them in the session, I will extract them. Remember, I can only extract variable 'i' from 'someIntegerVariable' session and not 'someStringVariable' session.

int newI = (int)Session["someIntegerVariable"];
string newS = (string)Session["someStringVariable"];
FooClass = (FooClass)Session["someFooClassObject"];
Since session stores object only, you will have to cast the object back to its original form. In the code above, I have casted the object stored in 'someIntegerVariable' session back to its original form which is int.

Thats basically how you use sessions. It is widely used in tracking pages and variety of other purposes, especially when you have to keep something consistent between pages.

Best way to query database in Visual C#


Best way to query database in C#
Well, this is actually not an official way but my personal choice. In this instance, I will use an access database as an example.
While querying the database is a long process in C#, it becomes simplified once you use object orientation. First of all, here's the conventional way of querying the database:

string connectionString = "...";
OleDbConnection dbConnection = new OleDbConnection(connectionString);
dbConnection.Open();
string queryString = "SELECT * FROM Customers";
OleDbCommand dbCommand = new OleDbCommand(queryString,dbConnection);
//since this is select query...
OleDbDataReader dr = dbCommand.ExecuteReader();
//and then you do the reading process...


Now, if you have a lot of queries to run, then this would be really painful process to do again and again. Hence, it is better to put the process in a method like this:

public OleDbDataReader runSelectQuery(string queryString){
string connectionString = "...";
OleDbConnection dbConnection = new OleDbConnection(connectionString);
dbConnection.Open();
//using the query string...
OleDbCommand dbCommand = new OleDbCommand(queryString,dbConnection);
//since this is select query...
OleDbDataReader dr = dbCommand.ExecuteReader();
//and then you do the reading process...
return dr;
}


The method takes in the select query string and returns the data reader which can then be used to extract the data. To make this more efficient, make a class and put the above method as static. Also, make the connectionString a global variable so that it if you need to change it, then you only have to change it in one place. In the end, the code would look like this:

public class QueryClass{

private static string connectionString = "...";

public static OleDbDataReader runSelectQuery(string queryString){
OleDbConnection dbConnection = new OleDbConnection(connectionString);
dbConnection.Open();
//using the query string...
OleDbCommand dbCommand = new OleDbCommand(queryString,dbConnection);
//since this is select query...
OleDbDataReader dr = dbCommand.ExecuteReader();
return dr;
}
}


Later, to access the method, you'll just have to do:

OleDbDataReader reader = QueryClass.runSelectQuery("SELECT * FROM Customers");

Comment below if you have any queries regarding the code.

Thursday 19 January 2012

Displaying tabular data in Visual C# using ListView

ListView is extremely useful in displaying tabular data in C#. Yet, it is an easy to use control.

  1. Drag the control onto your form and note its name. In this instance, I am going to use ListView1 as name.
  2. You will have to add columns to it now. This is how you do it.
    ListView1.Columns.Add("ColumnName");
    If you have 5 columns, then you will have to do it five times.
  3. Now, you will have to have each row that you want to insert as a single dimension string array. Number of items in this array should be equal to number of added columns. If it's not, then rest of string elements will not show up. 
  4. Add the string array to a ListViewItem. For that, you will have to create a ListViewItem first. ListViewItem's constructor would allow you to pass the string array to it. Do it by typing:
    ListViewItem li = new ListViewItem(stringarray);
  5. Now add the ListViewItem to the ListView by typing:
    ListView1.Items.Add(li);
  6. Thats it! Run your application and you'll have your table beautifully displayed in tabular format. 

Introduction to code efficiency and The Big O Notation



The big O notation explains how efficient the code is. It is like measurement scale for code efficiency. If you go in details, it can become complex. However, in this post, I'll explain how to get a rough idea of your code's efficiency.


To roughly calculate it, you need to know size of your problem which is 'n' in this case. Look through your code, and analyze the loops that you have. Basically, loops are the determining factor. If your code has 100 loops (not nested) then the efficiency is O(n). No matter what the number is, if your code has no nested loops, then the efficiency is still O(n). However, if you have one single nested loop, then efficiency is n2. Nested loops decrease efficiency of code. This is simply depicted by the fact that n2 is greater than n.

To write efficient code, it should be your goal to reduce number of nested loops. To do this, the best way is to reuse values that have been previously generated. My way to do this is by using connected methods. I will be discussing more about this in next posts. You can also exit loops when you have met your aim. In this case, while loop is preferred but if you have more than one condition, you should exit the loop when they are met just to save iterations.

If you wish to know more about the big O notation, read the article written by Rob Bell

Wednesday 18 January 2012

Welcome!

Welcome to Code Ninjutsu.

Code Ninjutsu is about art of writing efficient code. In this blog, we shall discuss methods to write efficient code. I shall also teach tricks that you can perform in different programming languages to get the most out of your code. We shall also see how algorithm works and methods to make it more efficient. We have a lot to talk about. Till then, you can watch videos on my youtube channel:

http://www.youtube.com/user/themanthandave

Later then!

Manthan Dave