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 ( http://blog.taragana.com/index.php/archive/how-can-sun-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"

BusinessCard

{

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

width : 300px;

padding : 10pt;

border : 1px solid #0D3427;

margin : 5px;

text-align : left;

background-color : #DACFE5;

}

Name

{

color : #0D3427;

font-weight : bold;

font-size : 140%;

display : block;

margin-bottom : 3%;

}

Phone

{

color : #523819;

font-size : 90%;

display : block;



}

email

{

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);
sqlcon.Open();
SqlDataReader dr = com.ExecuteReader();
while (dr.Read())
{
DropDownList1.Items.Add(new ListItem(dr.GetInt32(0).ToString(), dr.GetInt32(0).ToString()));
DropDownList2.DataBind();
}
sqlcon.Close();
sqlcon.Dispose();

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
connection.Open();
SqlDataReader dr = command.ExecuteReader();
if (dr.Read()) //yup we found our image
{
//Response.ContentType = dr["img_contenttype"].ToString();
Response.ContentType = "image";
Response.BinaryWrite((byte[])dr["Image_Content"]);
}
connection.Close();

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.








Now,

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

2) Add an FileUpload asp.net 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
JAVAMAIL API
WEbsite.
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

JAVA CONSOLE APPLICATION TO SEND EMAIL FROM A GMAIL ACCOUNT



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


public class SimpleGmailSend {

private static final String SMTPHOST_NAME
= "smtp.gmail.com";

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

private static final String SMTPAUTH_USER
="your email(like blah_blah@gmail.com)";

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("mail.smtps.host", SMTPHOST_NAME);
props.put("mail.smtps.auth", "true");
// props.put("mail.smtps.quitwait", "false");

Session mailSession =
Session.getDefaultInstance(props);
mailSession.setDebug(true);
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",
"text/plain");
// add your text message above
// u can also write a swings application
//to read the email body and save it here

message1.addRecipient(Message.RecipientType.TO,
new InternetAddress
("toemail address(like blah@blah.com)"));


transport.connect(SMTPHOST_NAME, SMTPHOST_PORT,
SMTPAUTH_USER, SMTPAUTH_PWD);

transport.sendMessage(message1,
message1.getRecipients(Message.RecipientType.TO));
transport.close();
}
}

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
rss,channel,title,link,description

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){

System.out.println("x="+Static.x);
//Static x=new Static();
//System.out.println("x="+x.y);
}
}

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 T.foo(). 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.

I use .NET-FRAMEWORK 2.0


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++){
Console.WriteLine(host.AddressList[i]);
}
Console.ReadLine();
}

}
if u were to use .NET-FRAMEWORK 3.5 the GetHostByName is deprecated....its obsolete.... u gotta use GetHostEntry...... i dunno why that was deprecated....it 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++){
Console.WriteLine(host.AddressList[i]);
}
Console.ReadLine();
}

}

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 =
somedate.Subtract(someotherdate);

Console.WriteLine("difference in days"
+diffResult.Days);

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

Console.ReadLine();
}
}





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

Console.ReadLine();

}

}

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")));

doc.Save("temp.xml");

)
);



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",
DateTime.Now.ToString()),
new XAttribute("id", "some name")));

xml.Save(@"C:\xml\test.xml");                            

}
}
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..................