Sunday, December 6, 2009

Cloud Computing: Software as a Service and Platform as a Service

New age of software development has come finally, with coming of SAAS(Software As A Service) and PAAS(Platform As A Service supported by AJAX, WEB 2.0

We have been hearing about Cloud Computing quite a few number of times in the business news, technical blogs, etc. Cloud Computing is very important for an organization, especially taking into account of the present state of economy.

Now you do not have to worry about upgrading to new hardware according to the standards in the industry. Now i believe no one in the industry must have "computer industry" forced upgrade of h/w or s/w.

A Traditional Software Installation Environment:

  • A user acquires the software from the internet/cd/external media.
  • The s/w to be installed has minimum Hardware Requirements, Software Requirements.
  • Check if the present system is compatible with the requirements of the software to be installed.
  • If YES, install the software and use it.
  • If NO, upgrade the present hardware the system is running on and then install and use the software.

The normal users generally get angry when they are required to upgrade their systems to the frequently changing technology.

Now Software As A Service comes into picture. The software is hosted as a WEB SERVICE by the developer of the software. In this scenario the user just logs in and uses the service.

The famous examples of Software As A Service include:

  1. Google Docs.
  2. Office Web Apps (Online Microsoft Office).
  3. SAP Business ByDesign, etc.

Here the user does not have to install any software in particular to use the service. The SAAS applications only may few software requirements (such as compatilbe web browser, JavaScript running web browser, flash/silverlight,etc).

These type of software services are in high demand as the Organizations can cut costs, as they have no requirement of upgrading their systems.

Advantages with SAAS:

  1. A single instance of software is used by an entire organization.
  2. No Software Upgrade.
  3. No Hardware Upgrade required when updating the service.
  4. Accessed over internet from anywhere in the world.
  5. No installation of Software required.
  6. Service can also be leased instead of buying the entire Software.
  7. Low system requirements(may run even with a low cost Netbook).

Issues with SAAS:

  1. Privacy: It is a major issue as the data is stored at a Server and all the clients interact with the server. If there are issues with browser, the security may be compromised.
  2. Reliability: If the server hosting the service is down, the entire organization must suffer the outage.
  3. Bandwidth requirements: To use the service optimally, we may require good bandwidth.
  4. Integrating with existing software/services: The existing software and services in the organization may require changes or changes in the SAAS is required to integrate into the existing system.

Platform As A Service:
PAAS is a combination of computing platform(the system on which the code is executed) and development environment(solution stack: OS, web server, database, etc) offered as a service

This means as a Developer or a End User you get to use a Platform available on the Web as a service. Google App Engine, Amazon Elastic Compute Cloud are two popular PAAS services that are popular presently.

Microsoft has jumped into these waters with its "Azure" Cloud Computing Services. It was recently announced in the Professional Developers Conference 2009 (PDC 2009)

What does this mean for a developer?
  • No istallation of Developement Environment on developers PC to BUILD, TEST and RUN the Applications.
  • All code is executed remotely on the server and the result is displayed onto the system.
  • No need to upgrade present systems to latest H/W as the H/W infrastructure is being hosted remotely.
  • Can develop applications irrespective of Clients side system (environment required on the client system to run the developed APPLICATION).
  • All the client needs is a secure internet connection to use the service.
  • Developer can as well develop software using a small low configuration netbook instead of a workstation.
Microsoft has showcased its prowess in this field by building Dell Cloud Computing Servers at the PDC 2009.

Intel also has its plans for the "Cloud Computing". It has already developed a 48 Core Processor: Single Chip Cloud computing Processor the "SCCP"

Friday, November 27, 2009

Read Data from Excel File

I am sure some of us have come across the requirement of reading through excel files. The following program reads a Excel file. It basically parses through all the cells and determines if it is a String or a Number or just white spaces.

  1. I basically used Apache POI API to read Excel files.
  2. Download and extract the following zip file:
  3. Put poi-3.5-FINAL-20090928.jar in classpath (Environment Variables in Windows OR Bashrc file in Linux-Ubuntu OR External Jar in Eclipse).
  4. Compile and Execute the following code with small changes(change the name of the file to be read to your own Excel Sheet).
  5. The code determines if the data read from the cell is a number or a string.
  6. It doesnt convert the number to a string by default. You have to convert it manually.

Apache POI API has no support to read Number seperately (like a method readString() or readNumber()), as EXCEL Spread Sheet does contain most of the time digits and numbers.


Wednesday, October 28, 2009

Installing Java (for JAVA Developers)

I am sure that lot of you guys might have gone through the pain of installing JDK(java development kit) on your PC. Well i went through the pain too. I just wanted to share my knowledge to help you guys out there.


  1. search for Java JDK in google
  2. visit the first link in your search.
  3. Select a "Java SE Development Kit" from all the links visible (Make sure that you select a JDK not a JRE and ill tell you the difference).
  4. Select the appropriate OS.
  5. Download the file.
  6. Double click the file and install.
  7. go to C:\Program Files\Java\ (or the path where you installed java).
  8. go to the jdk folder that comes up.
  9. go to the lib folder. copy the path of the folder in the Explorer address bar.
  10. Go to start. Right click on My Computer and go to properties (for Vista users, its properties of "Computer").
  11. go to "advanced"->"environment variables".
  12. go to system variables.
  13. double click open "CLASSPATH" variable in system variable. If "CLASSPATH" or "classpath" doesnt exist create one.
  14. Make sure that CLASS and PATH are a single word as in "CLASSPATH" not as in "CLASS PATH" or "class path".
  15. in variable value of "CLASSPATH" add a dot and a semi colon as in ".;"
  16. now paste the entire path after the ".;" .It should be similar to the following: ".;C:\Program Files\Java\jdk1.6.0_16\lib"
  17. now open "PATH" variable in system environment variables.
  18. go to the end of the variable value add a semicolon and then paste the text as like in previous steps but MAKE SURE THAT you change the "lib" to a "bin".
  19. the variable value of "PATH" should be like in "something;C:\Program Files\Java\jdk1.6.0_16\bin".
  20. click on OK and come out.
  21. open cmd from run in start menu.
  22. type in "javac" command to make sure that path is set right. You can also type "java" to check but, its a good idea to try "javac" as javac only comes with a JDK not a JRE which is by default installed in a system.
  23. write your program in a text editor like notepad or textpad. compile and execute the program to make sure that it works.
Now i will explain the above steps:
Steps 1 to 12 are all about installing java.
Steps 13 to 16 make sure that you give the "CLASSPATH" right.
Steps 17 to 19 make sure that you give the "PATH" right.

So, whenever you create a executable and you want others to access it via command prompt from any directory. You add the executable file path to the "PATH" variable.

For LINUX Users: There are lots of Linux distros available and there are many ways to install it. So, i will tell you two easy ways to install Java on a popular Linux Distro UBUNTU.

First Method: This is more easier than in WINDOWS :p as there is no need of configuring CLASSPATH or PATH. Just follow the commands and start developing in java.
  1. open the terminal.
  2. type the following command.
  3. sudo apt-get install sun-java6-jre sun-java6-jdk sun-java6-plugin
  4. the above command will install java runtime environment (JRE), JDK, java6 plugin (for web browser i suppose).
  5. Restart the terminal to check if jdk is installed by typing in following commands: "javac" and "java"
Second Method:
  1. Visit
  2. Select Java Development Kit and select Linux (32 bit/ 64 bit).
  3. Download the bin file.
  4. open the terminal browse to the folder where the bin file exists.
  5. type in the following command $chmod a+x downloadedbinfile
  6. In above command chmod a+x would give all (user group and others) execute permission.
  7. then type the following command in terminal in the folder where the file exists "./downloadedbinfile".
  8. Then follow the instructions in the terminal.
  9. After its done. Open bash.rc file in /home/yourusername directory in root mode and add the following:
    export PATH=$PATH:/path to jdk/bin
    export CLASSPATH=:.:/path to jdk/lib
  10. restart the terminal and type in javac and java to check if its working.

Now answers to questions that may arise in your mind after following above process (if you are a noob java programmer)

CLASSPATH contains all the precompiled class files that you need to run your program. For example in the following program:

import java.util.Random;
class RandomGenerator extends Random {
public int nextInt(int L_limit,int U_limit)
return nextInt ((U_limit - L_limit+1))+L_limit;
// the above line always generates numbers b/w U_limit and L_limit.
public class RandomDemo
{ public static void main(String[] arguments_stored_here)
RandomGen x = new RandomGen();
// change 1,5 to number u like to generate random numbers between them
// 1 and 5 are inclusive here.

java.util.Random refers to Random class in your system. You can view by going into the CLASSPATH folder and opening the tools.jar file with winrar. you can find a file called Random.class under java->util folder. Similarly you can also find System->out (in for System.out.println)

So, basically CLASSPATH is the repository of all class we refer in import statement in our java progam. If we do not set the path, the compiler does not know where to look for the classes in order to compile the program. The "." in class path refers to current folder.

PATH makes sure that your commands like "javac" or "java", etc work from any directory in your system. If you observe there are files by the name "javac" and "java" in bin folder of the jdk directory. For example a simple command like "ipconfig" in command gives you the ip configuration of your PC, even ipconfig is a file under system32 folder .

JRE stands for Java Run Time Environment. It is the software required to execute java programs or programs that require java to run. You write the code in java and give the user the .class files. The JRE executes the .class files. It contains the JVM (Java Virtual Machine).
JDK stands for Java Development Kit. It is the software required required to develop java programs or java related applications. It also includes a JRE (for the developer to test the developed applications).

Saturday, October 24, 2009

Generate random numbers between two numbers: JAVA

The other day i came accross an interesting task where i had to generate random numbers between two numbers.

Unfortunately, there is no built-in methods in Java to generate random numbers between two numbers.

I searched many forums to get my answer. I am writing this in my blog as i found it interesting.


Tuesday, October 13, 2009

Microsoft Windows is not bad as we think: filename length restriction in Windows XP

The other day i was busy backing up important data in windows xp manually.....

I was using a x86 machine running a Windows XP SP3....... i was copying data saved on a different hard disk to my new machine (probably a windows xp but older version).

I noticed a flaw while trying to modify data in a folder. I could not copy a file from a hard disk. The length of the path of the folder (address bar in the explorer window) was very lengthy and windows would not allow me to copy it saying the length of the file is too long.

I then checked out the filename length(it was 254, may it has restrictions on file length of 255 or 256)......

The thing to notice here is at first how did the previous OS agree to copy the file with that filename length?? Now, while copying it back in the new OS reveals that Microsoft has fixed that problem..... That is why it kept giving me error message asking me to limit the file length size.

i thought writing this in my blog would be good reminding me that this bug existed before in previous windows of XP.....

Sunday, September 27, 2009

Ubuntu File Permissions and recursively changing file permissions:

To change file permissions of a particular folder and folders/files under it recursively to read write execute, the shell command is :

sudo chmod 777 -R /path/tothe/particularfile-folder/

The first 7 determines that it is intended for this "user"(current user)....
The second 7 determines that it is intended for this "group"(current user group or a particular group)....
The third 7 determines that it is intended for "others"....

Now what is the fuss about "7"?/ u guys might be wondering. This has significance.

All Unix like systems have the following standard to represent RWX(read-write-execute)for a user/groups/other users in the system:

4- Read(can only read).

2- Write(can only write).

1- Execute(can only execute).

so, if you want to give a current user only execute rights you say:
sudo chmod 177 blah/blah

but if you want to give read and execute you give (1 + 4 = 5):

sudo chmod 577 blah/blah/topath

if you want to give read and write to a user group and others but not execute you give (4 + 2 = 6):

sudo chmod 166 blah/blah/topath

so far i guess you must have figured out that

1+4= 5 (gives execute and read rights but not write rights)

1+2= 3 (gives execute and write rights but not read rights)

4+2= 6 (gives read and write rights but not execute rights)

4+2+1=7 (gives read write and execute rights).....

you can use the above commands for recursively or just changing folder permissions, file permissions......

just chill whenever you see a 7,3,6,5 in a chmod or in any other command.....its determining the UGO(User Group and Other) rights/or what so ever..........


Monday, September 7, 2009

to make a shell script executable

hi all..........

we all do face some probs now and then to make a shell script executable, especially when running in a text mode or while accessing linux through telnet remotely.........

to make a shell script executable, you are required to type the following code:

$chmod a+x executable_file

then you run/execute the script the way you want........


rahul kavi

recursively change file folder permissions

Hi again..........its been a while since ive written my last blog post..........

I have lost touch with Unix/Linux and its commands........ite been a while(about 6-9 months) since ive used linux...... Now im completely on linux for over a month.. :)

This blog post is about converting the files and its constituent folders and files into your own files(i.e, you are the owner), if you sufficient rights to convert

to do it..........
step 1) go to the particular folder using "$cd folder_path"
step 2( type the chmod command with -R parameter......... "$chmod -R 777 *"
step 3) if its alright you will get the prompt, otherwise you have some error message, you may not have sufficient rights to modify the permissions of that particualr folder..

"777" gives you rights to read write exacute and "-R" refers to "recursively" do it........

cheers........rahul kavi

Tuesday, July 14, 2009

Testing basic string array properties with pointer and addresses

In this program we unearth basic properties of character arrays.
Check the following program out….
Here inside the main() function we are in initializing the array with the string “rahul….”
The next two lines were basically written to indicate two facts:
· Whenever you try to print an array using the variable you get the base address of the array.
· Trying to print the base address using %d or %u doesn’t matter it gives the same output.
Then we are printing the address of last character of the array using &a[strlen(a)-1].
Then we are printing the length of the array using strlen() function.
Then we are accessing the content of the array using *&a[0] and *&a[strlen(a)-1].
Basically &variable_name means address of variable_name and
*address means value at that address.
So finally, *&variable = value at(address of variable) i.e, the variable value.

The following is the output of this program

Monday, June 1, 2009

Bool Variables in C++

Ive been trying to work on C++ again....after 2 long years.... ive never

tried hard to understand this programming language....just studied C++ from

academic point of view.

Bool in C++ takes only 1 or 0 as inputs....i mean it expresses true or false

in terms of 1 and 0 respectively.

THe following code works in DEV C++ which uses gc++ compiler:

int main()
bool real;
return 0;

irrespetive of assignment of values to a bool variable it is reflected as

true or 1; unless 0 is assigned or a bool variable is declared it has "0" by


Wednesday, April 22, 2009

Oracle+= Sun;

According to internet sources, Oracle is buying the SUN for a staggering $7.4 billion.

Years ago, in a blog i read a critic saying that he does not trust JAVA and its future because, its a product of the SUN microsystems not IBM. He said he will be happy if IBM took over SUN. I was like, if it would happen it would be the biggest takeover in the history(for me atleast, in terms of tech czars - microsoft, sun, ibm, oracle, sap, etc). There were news that SUN was in trouble(financially) and many developers, critics, analysts saying that SUN was not able to monetize java ( ).

Few weeks ago i was very happy for Java, because there were talks of IBM taking over SUN. IBM has always been a supporter of Linux and OPEN-SOURCE movement. Such a move, would benefit the open source enthusiasts.

But for now, i am really suprised as Oracle is taking over SUN Microsystems not IBM. Im no high tech market analyst but, i have read in many blogs that Oracle planned such a move to optimize Oracle for the Solaris OS. There must be an uproar in the open source community in this deal.

Oracle does recommend Solaris as its most preferred OS to run its DB, but i really doubt its future as an OS because most of the Unix market is being taken over by Linux.

Now in the high tech world, 3 powerful war-lords exist, competing against each other.

1) Microsoft.
2) IBM.
3) Oracle.

Now, we must wait and see how Oracle integrates technologies of SUN into its mainstream.

The developer community are closely watching this deal on the following terms:
  • How Oracle would treat Java (the crown jewel of Sun microsystems).
  • How Oracle would take on MySQL (most popular of the open source alternatives to Oracle Database (the main product of Oracle Corporation).
  • On future of OpenOffice??
  • Oracle`s take on Sun Hardware ( its market is dying, as people are opting for IBM`s low priced servers. This market also consists of Dell Servers, HP Servers). With Oracle now selling hardware/servers , will strain their relationship with HP !!
  • whats the Future of "Netbeans IDE"? Oracle has always supported Eclipse. I believe Netbeans would die out soon or Oracle will optimize NetBeans IDE to compete more fiercely against Eclipse IDE ( most preferred JAVA IDE).
  • Oracle`s take on SUN`s promise of opening (open source) up its entire software stack?? I believe that Oracle would not go ahead with this.
Many analysts say that Post Takeover of SUN by the Oracle corporation, existing hardware division employees would be more safer than the software division employees (Oracle has no hardware presence, so Oracle would like build on it. We could see some drastic changes in the software arena at SUN as Oracle would mould SUN`s software division policies/ideologies according to its existing software policies).

As on for now, all of the developers, market analysts wait closely watching the outcome of this deal. I pray to god, that this deal would spell some on the other good for the developer community.

Saturday, April 18, 2009

Inserting Images into MySQL database using Java Console Application

Hi again. Here we see insertion of image files(here jpg file, it need not be jpg all the time, you can insert any other files also) into a MySQL database.

First create the table in the MySQL database. Issue the following SQL query to create a table by the name "Image" that stores the images which we intend.

CREATE TABLE `image` ( `id` varchar(20) NOT NULL, `size` int(11) default '0',
`image` blob NOT NULL ) ENGINE=InnoDB;

We use the "File" and "FileInputStream" class to store the parameters related to the image file and then use the method "setBinaryStream(int index, FileInputStream object, int length_of_the_file)" to insert the image into the database.

The program in java is as follows(u need to have all the JDBC drivers configured before running this java app):

Friday, April 17, 2009

Associating XML with CSS data

Hi all, we all know why XML is used (weve used it as a small-database).

Here we now see presenting XML data on a web-browser while associating XML tags and CSS.

1)Create a simple XML file which looks something similar to this and save it with the name "BusinessCard_CSS.xml" .

2) View it in a browser to make sure its a well formed document, if it is not, make it one. If its wellformed.

3) Create a simple CSS file, in the same folder as the XML file. Create a block for a tag for which u want the browser to parse it. Add the following data in order to define the body, color, etc. Save it with the name "BusinessCard_CSS.css"



font-family : Arial, Helvetica, Sans-Serif;

width : 300px;

padding : 10pt;

border : 1px solid #0D3427;

margin : 5px;

text-align : left;

background-color : #DACFE5;




color : #0D3427;

font-weight : bold;

font-size : 140%;

display : block;

margin-bottom : 3%;




color : #523819;

font-size : 90%;

display : block;




color : #0D3247;

font-weight : bold;

font-size : 120%;

display : blocl;

margin-top : 3%;


4) Now as we have defined the CSS element blocks and even the XML tags in the xml file. Now we have to associate the XML with the CSS properties.

Add following line to the starting of the file.
<?xml-stylesheet type="text/css" href="BusinessCard_CSS.css" ?>
and finally the xml document should look like the following:

Open the XML document in the browser and you would see something similar to this:

Thus we have associated an XML file containing data with some presentation using CSS properties.

Wednesday, April 15, 2009

Retreiving Images from Database in SQL Server with ASP.NET using C#

Now in this blog post i explain how to retreive images from the database.

This article is continuation of previous post (where i have mentioned database design of the image table and stuff- refer the previous post).
Open VS 2008, Add an aspx page to existing Website.

1) add a drop down list(of id "DropDownList1") to the webpage, and enable the post back feature.

2) add a button (of id "ViewButton") to the webpage.

3)In Page_Load function/method add the following code to populate the dropdownlist with the list of images available in the database.

SqlConnection sqlcon= new SqlConnection("Data Source=SERVERNAME\\SQLEXPRESS; Initial Catalog= DB_NAME; Integrated Security=SSPI");
string sqltext = "select Img_Id from Image_Gallery";
SqlCommand com = new SqlCommand(sqltext, sqlcon);
SqlDataReader dr = com.ExecuteReader();
while (dr.Read())
DropDownList1.Items.Add(new ListItem(dr.GetInt32(0).ToString(), dr.GetInt32(0).ToString()));

4) Now add the following code to the event handler of the button.

string ImageId = DropDownList1.SelectedValue.ToString();

//build our query statement
string sqlText = "SELECT Image_Content FROM Image_Gallery WHERE Img_Id ="+ImageId+";";

SqlConnection connection = new SqlConnection("Data Source = SERVERNAME\\SQLEXPRESS; Initial Catalog= DB_NAME; Integrated Security= SSPI");
SqlCommand command = new SqlCommand(sqlText, connection);

//open the database and get a datareader
SqlDataReader dr = command.ExecuteReader();
if (dr.Read()) //yup we found our image
//Response.ContentType = dr["img_contenttype"].ToString();
Response.ContentType = "image";

5) save the page and run the page. You see something similar to this

6) Select the a option from the list of available images and click the button and its done.

Upload images onto SQL Server using ASP.NET webpage

Uploading images is one of the most frequently required features of a blog/website.

This program explains you how to upload images onto a SQL Server 2008 db using VS 2008 with code written in C#.

Open SQL Server 2005/2008 instance, select a db and create a table (Image_Gallery) with following attributes.


1)Open a new website, In solution explorer of VS 2008/2005 add a new aspx page.

2) Add an FileUpload control onto the webpage.

3) Add a button to the asp page and name it to "Upload"

3) Double click on it to go to the logic.

4) add the following code in the event handler of the "Upload" button

Now, Save and Run the application. Its done.

Monday, April 13, 2009

JAVA: send emails through a console application

ive searched a lot for help on sending emails through an application. But i found most of the articles on the web very confusing, i think this java application is one of the most simplest solution from which i could come up with the console application to send email. This java application can send emails through a console application.

i have referred many articles before writing this post, the credit goes to the concerned programmers article/blog to which ive referred

You read the code and use it accordingly . Understand the code and u can integrate this into a JSP page or a desktop application combining with appropriate JAVA API.

This code sends emails from your gmail account to the recipents from a console application.

before executing this code, download the mail.jar file from the
and also the activation.jar file from java beans activiation framework website

and include them in the class path, otherwise you would get an class not found error

go through the code and make appropriate changes, to make it compatible with
other email service providers by referring to the following link
List of email service providers with smtp, pop configurations


import javax.mail.*;
import javax.mail.internet.*;
import java.util.Properties;

public class SimpleGmailSend {

private static final String SMTPHOST_NAME
= "";

private static final int SMTPHOST_PORT = 465;
// 465 is for GMAIL.

private static final String SMTPAUTH_USER
="your email(like";

private static final String SMTPAUTH_PWD
= "your password";

public static void main(String[] args)
throws Exception{
new SimpleGmailSend().test();

public void test() throws Exception{
Properties props = new Properties();

props.put("mail.transport.protocol", "smtps");
props.put("", SMTPHOST_NAME);
props.put("mail.smtps.auth", "true");
// props.put("mail.smtps.quitwait", "false");

Session mailSession =
Transport transport = mailSession.getTransport();

MimeMessage message1 = new MimeMessage(mailSession);

message1.setSubject("Testing sending mails
through java application with GMAIL ");

message1.setContent("Your text in EMAIL GOES HERE",
// add your text message above
// u can also write a swings application
//to read the email body and save it here

new InternetAddress
("toemail address(like"));



your own rss feeds !!!!

hi guys......

this is rahul.

the following is a small tutorial to build your own rss feeds.

ive faced many problems in looking out for building rss feeds, so finally decided to post my own article on building rss feeds for dummies novice( like me)

RSS stands for (Really Simple Syndication (RSS 2.0)).

it is an simple summary of the site updates in text format.

the following is an rss feed from a firefox 3 browser(a bbc rss feed of world news updates)

he drop down list is the list of updates, the site wants us to check out.

lets come down to the basic syntax of a rss file.

basically the rss feed exists in a XML file (generally in a file called rss.xml).

the rss file contains the tags of

the following is an example of a rss.xml file

-> the rss tag marks the beginning and ending of the rss feed.

-> the channel tag specifies the beginning and ending of the channel.

-> the title tag specifies the title name to be displayed for a particular link

-> the link tag specifies the particular link to a url.

-> the description tag specifies the description of a particular link .

there are many more tags in the rss file, but most of them are not required(FOR A SIMPLE RSS FEED)

write the above rss structure in your rss.xml file(change it as per your requirements) and place it in the context root of your website.

try accessing the rss.xml file through the URL, and then add the bookmark prompted by your
firefox 3 browser(or firefox 2+, IE 7).

one can write a java code/php code/asp code to update the rss file from data fetched from the database, the rss file then keeps on changing, so does the links displayed according to the structure in the rss file.

now you are done with your own rss feed.

Java Set Precision

Sometimes it does feel odd to search Mbs and Mbs of API Documentation to accomplish a simple task like setting precision after decimal point in java.

ive searched for many articles over google, but found the most of them confusing. This was the best and the most simplest way i could find to set precision after decimal point in calculations while working with primitive data-types like double and float.

this is a small patch of code in java to set precision after the decimal point in handling float and double related data-types.

the above code is self-explanatory as ive inserted comments.

JAVA: why static variables cannot be referenced from non-static context

hi guys, this is rahul

i have always been wondering on properties of the key-word static !!!

i`m really enthralled on discoveries that i make while playing with the language, that`s how its should be learnt;

this article deal about why in java programming, static variables cannot be accessed from non-static context;

consider the following code:

class Static
static int x=20;
int y=40;
class TestStatic extends Static
public static void main(String[] ar){

//Static x=new Static();

the above code works fine, because we have accessed static members from static context.

static means, one can access the member without having to create the class object(only classname.staticvariablename will do)

instance variables(variables declared in class) are created ONLY IF the object for the class is created.

Static methods and members are at the class level and not instance or the object level.

so that means they can't access instance level methods/members.

for example,

class Example
int x; // non-static integer 'x'.

static void foo()
return x+4;

In above example, unless an object of Example is created, the variable "x" doesn't exist.
But still u can call method foo() using BUT WAIT !!! What is 'x' in this case??
it is not static, it is an instance variable and is initialized only if class object is created
Same thing happens with static methods.
Therefore you can access non-static members from within static context.

C#: Executing dos commands without opening the console window

while googling i encountered a superb post at one of the blogs of Microsoft developers, in which it there was a discussion on executing a dos command and reading the output. This interested me a lot.

Ive developed small programs which were simple front end GUI for dos commands. While executing the programs, the dos console always popped up. This was very annoying, i wanted it not to appear and still execute the dos command.

I wanted to read the output of the dos command, execute the command without command window popping up.

The following code is about opening a "cmd" and executing a "ipconfig" command without window showing up from the console. This would be effective while executing the code from a Windows Form rather than.

I beleive that guys with basic .NET programming skill can understand this and PORT it to a windows FORM application.

the code goes as follows....

this code will open a invisible dos command window, execute the command and read the output into a string variable.

i have referred this post, before writing this small article
without dos window, execute dos commands

C#: get IP address of the system by hostname

i thought this was a very useful program for people who are trying to read the IP address of a system in a programmatic manner.


using System;
using System.Net;
class getIP

static void Main(string[] args) {
string machine_name = Dns.GetHostName();
IPHostEntry host = Dns.GetHostByName(machine_name);

for (int i=0; i < host.AddressList.Length; i++){

if u were to use .NET-FRAMEWORK 3.5 the GetHostByName is deprecated....its obsolete.... u gotta use GetHostEntry...... i dunno why that was was simple to remember "GetHostByName" is a very obvious name......
using System;
using System.Net;
class getIP

static void Main(string[] args) {
string machine_name = Dns.GetHostName();
IPHostEntry host = Dns.GetHostEntry(machine_name);

for (int i=0; i < host.AddressList.Length; i++){


the first ip is of the ethernet Local Area Network... the 2nd or the 3rd one are probably the external ip.

C# : program to calculate the difference between two give dates and time

i guess this is one of the most important thing a developer must code while developing desktop applications(ie, trial software with time limit).

this is a simple way where one can calculate the differnce between two dates in C#.

program goes as follows.

Calculating the Date Difference using the Subtract Method.

using System;

class Program


static void Main(string[] args)


System.DateTime somedate =
new System.DateTime(2014, 9, 13, 13, 0, 0);

System.DateTime someotherdate =
new System.DateTime(2006, 9, 13, 0, 0, 0);

System.TimeSpan diffResult =

Console.WriteLine("difference in days"

Console.WriteLine("differnce in days
(with decimal precision)" +diffResult.TotalDays);


Calculating the Date Difference using the minus symbol('-').

using System;

public class difference TestDateDiff

public static void Main()

System.DateTime somedate =
new System.DateTime(2014, 9, 13, 0, 0, 0);

System.DateTime someother =
new System.DateTime(2006, 9, 13, 0, 0, 0);

System.TimeSpan diffResult =
somedate - someother;

Console.WriteLine("difference in days = "
+ diffResult.Days);// returns int

Console.WriteLine("difference in days with decimal precision"
+ diffResult.TotalDays);//in decimal fraction




Sunday, April 12, 2009

LINQ (Language Integrated Query) C#: Editing XML Docs the easy way in DotNET Framework 3.5 C#

Ive tried appending XML(at the end of the file) many times, but failed (there
are ways of doing it successfully, but i became very confused).

Im writing a small C# application for myself where i can store information
in a XML file and retreive it.

Learning the way to write XML through C# is quite a uphill task, as there are
many known ways of reading/writing/saving a XML document.

Man there are many many classes like XMLDocument, XMLNode, XMLElement, etc
in the "System.Xml" namespace.

With introduction of LINQ interacting with objects or elements which
contain data(arrays, lists, xml docs, databases) have become very easy.

Although there are many cons claimed at many blogs which ive read.

This was the most easiest way of writing XML using LINQ in C#.

using System.Xml.Linq;
using System;
using System.Xml;
using System.Text;
class NodesAttribs
public static void Main()
//creating a new XML document with body
XDocument doc =
new XDocument(
new XDeclaration("1.0",
Encoding.UTF8.HeaderName, String.Empty),
new XComment("Xml Document"),
new XElement("catalog",
new XElement("book",
new XAttribute("id", "001"),
new XElement("author", "Dan Brown"))

//end of a single statement, very lengthy isnt it..LOL...but its easy imagining the end XML doc.

//NOW adding a new ELEMENT: to the above created xml file( doc object)

doc.Element("catalog").Add(new XElement("book",
new XAttribute("id", "002"),
new XElement("author", "John Grisham")));



The above code will add an element called "book" with attributes
to root element catalog in that specific XML file.

It will generate the following XML :

LINQ (Language Integrated Query) C#: Appending to existing XML files using DotNET Framework 3.5

LINQ has been one of the greatest innovations in the recent trends of programming. And this comes from the Microsoft.

I really like the easiness of interacting with XML files. Now writing, reading, appending an XML (using the LINQ TO XML features of Microsoft Framework 3.5) has become very easy and, is no more complicated as it was before (atleast for me, LOL).

In this program i explain how to APPEND an XML file using LINQ TO XML Features of C# in Framework 3.5

Let us consider the following XML file.

the following program explains how to append to existing XML files.

This program would be quite useful in writing log files/ appending to xml files.

consider the following program.

using System;
using System.IO;
using System.Xml.Linq;
using System.Linq;

class LinqAppendXML
static void Main()

XDocument xml = XDocument.Load(@"C:\xml\test.xml");

Console.Write("successfully loaded the xml file");

//getting to the root element.

XElement t = xml.Root;

//adding new element to the root element

t.Add(new XElement("login",new XAttribute("time",
new XAttribute("id", "some name")));


The program produces the following output:

This way an xml files can be appended. This is one of the most easiest way to append to a existing XML file.

Thursday, April 2, 2009

Disable random Port number for Visual Studio while running ASP.NET application

I guess most of you guys might have come accross this problem.

By default, the Visual Studio/ Visual Web Developer runs on random port number while running the ASP.NET website/application/webservices.

This is very frustrating specially if you are using a firewall.

I had come across this problem, as i wanted to publish RSS feeds and i dont have server( i use localhost) and the port number changes on starting a different instance of Visual Studio.

We can disable this by following steps:

1)click on the website on solution explorer.

2)in properties section of the website
---> select "use dynamic ports: false"
--->Then specify any 4 digit number of your choice(a valid number)
--->save your setting....thats all.....

From now on all the website runs only on this particular port while running the web application.

have fun..................