Posts

Showing posts from 2009

Send Gmail using Dot NET

Hi, in my previous posts, I have posted how to send mail using the Java API. In this section, I would like to demonstrate on how to send mail using Dot NET. Using Dot NET, it is equally easy to send mail. In this post I would use my Dot NET application to connect with Google's outgoing mail server (Google's SMTP server) and use that to forward my mail. (In my previous post, I've demonstrated on sending mail using my own SMTP server which ran on my machine. In this scenario, it will directly put the outgoing message into the Gmail's SMTP server) You will be using mainly few Classes to get the job done. System.Net.Mail.MailMessage System.Net.NetworkCredential System.Net.Security.SmtpClient These classes will provide the basic methods to get the job done. You will also be using System.Net.Mail.MailAddress class. (Though there is a way to get the job done without actually needing this.) First of all, you need to import the namespaces. using System.

Download File using Dot Net

In this post, I will demonstrate how easy it is to download a file from a web server to your local hard drive. In most scenarios, you may browse the net using your web browser and click on a hyperlink to start a downloading of a file from a remote site. Some of you may be interested in how to download this using their application code using Dot Net. This can be very easily achieved using the WebClient class under System.Net namespace. First, import the System.Net namespace. using System.IO; The above LOC will do so. Now, create an instance of WebCleient class. WebClient client = new WebClient(); Now, call the DownloadFile method client.DownloadFile(<url>, @"<fileDestinationName>.<filetype>"); Have fun. Cheers !!!!

ASP Response.Write newline

Hi, all of you who have used ASP may have encountered situations where you require to write a text output to the screen. It can be easily done by using Response.Write("Hello world"); However, if you wish to append some more text to a newline, it would not work in the following ways. Response.Write("Hello world \n"); Response.Write("Good day."); The output of the above lines would be Hello world Good day. and NOT Hello world Good day. In order to overcome this, you can very simple place an html break tag inside the code. Response.Write("Hello world"); Response.Write("<br/>"); Response.Write("Good day."); The output would be the following. Hello world Good day. Cheers !!!

Browser addressbar icon (favicon)

Image
Hi, all of you must have noticed that when you visit a website with your browser, the image on the left of the addressbar changes. First of all lets define its correct term. It is known as the 'favIcon'. In this post, I wish to demonstrate how to add such a favicon to your website. To try this out, you would need a web server such as IIS, Apache or Tomcat. I'm using WAMP's Apache server for the demonstration. First of all, you'll need an image of dimension 16x16. You can use windows paint to do this. Save it in Windows 16 colors. If you need to do this quickly, you can use the following website , which will generate a favicon from a given image. Save the image as favicon.ico. Now, copy and paste this on your web server root directory of the application. The folder structure of WAMP is based in a way such that the web applications need to be deployed in the folder named "www". (The complete path for this is "C:\wamp\www") Now, create a separate f

ASP Regular expression to check length of textbox value

Hi, here is a regular expression validator in ASP which you can use to check if a certain textbox has less than a certain number of characters. <asp:regularexpressionvalidator runat="server" id="lengthRegex" controltovalidate="">" validationexpression=".{1,<n>}" errormessage="Please note that there should be less than <n> number of characters in the textbox"> </asp:regularexpressionvalidator> So, if you intend to make the textbox accept a number of characters in a range(say between 5 to 10) then the following changes would work <asp:regularexpressionvalidator runat="server" id="lengthRegex" controltovalidate="">" validationexpression=".{5,10}" errormessage="Please note that there should be between 5 to 10 characters in the textbox"</asp:regularexpressionvalidator> Suppose you need to limit the characters to only alphanumerics, then use the

URL Regular Expression

Here is a good Regular Expression for evaluating a URL (http(s)?\:\/\/)?([\w_-]{2,}\.)+([\w_-]{2,})((\/)(\~)[\w_-]+)?((\/)[\w_-]+)*((\/)¦(\/)[\w_-]+\.[\w]{2,})?((\?[\w_-]+\=([^\#]+)){0,1}(\&[\w_-]+\=([^\#]+))*)?(#[\w_-]+)?

Java Sorting Arrays

Hi, All you Java folks must have faced a situation where you require to sort an array of custom objects using Java. Sorting a string array is easy with Java. But, what happens when you have a custom object array, say an array od Person objects to sort. You need to sort them according to a specific custom condition. With java interfaces, this becomes easily doable. In this example I will use the custom object as 'Car' public class Car { int age; string id; string color; } I need to sort them according to the age. Thus, according to the ascending order. First, you need to implemet Comparable interface of java. public class Car implements Comparable { int age; string id; string color; } So, add the above code in Red. This tells that this class implements the Comparable interface and accepts Car objects only. Now, you need to actually implement the methods regarding the interface. public int compareTo(Car o) You must implemen

Twitter API with Java

Hi, Since Twitter is one of the most widely used ways to share your status with others, I will use this post to display how to use Java to access the Twitter API. I used a Java library named "jtwitter" which can be freely downloaded from "http://www.winterwell.com/software/jtwitter/jtwitter.jar" Once you download the jar file, add it to your project. Then, it becomes very simple to use the API. First build a new Twitter object Twitter twitter = new Twitter("<username>","<password>"); Then set your status to whatever you want twitter.setStatus("Twittering"); To get a list of your friends, simply use the following LOC List followers = twitter.getFriends(); If you need to get the user's image, you can do it in the following manner. 1. Get the URL of the image using Twitter API 2. Use Java Classes to download the image and display it NOTE: The user variable is of type ' Twitter.User ' URL imgURL = user.getProfileIma

Dot NET Regular Expression

Hi, in this post, I will demonstrate how to use a Regular Expression using the Dot NET Framework. If you are new to Regular Expressions, this post would not be of much use. This is intended for an audience who knows regular expressions and need to implement a regular expression in their Dot NET code. There may be scenarios where you need to match a certain string with a Regular Expression. Using the Dot NET Framework, this becomes relatively easy. First, you need to import the namespace by defining using System.Text.RegularExpressions; Then, you can create a Regex object by calling its constructor. This is an overloaded constructor. I will show only one use of it. (You can explore the other!!!) Regex regularExpression = new Regex(" "); This would create a Regex object. Once created, you can call several methods to get the job done. I will show how the Replace method can be used to identify a character pattern and replace it with a character set of your own. (A good example i

Dot Net Date Formatting

Hi, all of you people may have encountered situation where you wish to format your date for a specific format. This becomes very simple with Dot NET Framework. Suppose you have a date to be displayed. Let the date be 1st January 2009 Now, this can be displayed in various formats. The respective date-format-string is displayed alongside Eg: Displaying these can be done using the following LOC. DateTime today=DateTime.Now; string formattedDate=today.ToString( ); Eg: string formattedDate=today.ToString("dd-MM-yyyy"); =>01-Jan-2009 string formattedDate=today.ToString("dd/MM/yyyy"); =>01-Jan/2009 string formattedDate=today.ToString("d-MMM-yy"); =>1-January-2009 Try out other combinations of your own and experience the power!!!!!!! Format Respective date-format-string 01/01/09 'dd/MM/yy' 01 Jan 09 'dd MM yy' 01 Jan 2009 'dd MM yyyy' 1 January 2009 'd MMM yyyy'

Dot Net Writing to a File

A very simple LOC which may become very useful. File.WriteAllText("C:\\a.txt","Hello World");

Java System.out.println() explained in OOP

Hi, all Java programmers must have used the " System.out.println() " method many times during their programming careers. It is used even in the HelloWorld Java code. The most interesting part of it is that how it complies with the OOP (Object Oriented Programming) concepts. Many of us have used it, and are using it over and over again without any consideration on how this fits on with the OOP concepts. In this post I expect to give my clarification on how it is implemented. Obviously " System " is a public class. And at first, it seems as if we were accessing a static method of the " System " class by calling System.out . But, if it was a method, we would basically call a method in the following manner. System.out(); where we would be using parenthesis, and we do not use it in this case. Hence the concept regarding a static method call of a " System " class fails. We can access class variables by calling . . Given that the class variables ar

Send J2ME Mail

Hi, most of you may have wondered how to send mail using J2Me. With the support of J2ME and J2SE, it becomes simple. If you have developed Standalone/Desktop mail sending applications before, this may be even easier. If not please reffer to the following article before http://ruchiram4.blogspot.com/2008/12/sending-mail-using-java.html I assume that you are familiar with J2ME basics (Sun Wireless Toolkit, Midlets) and have the basic knowledge in deploying an application in Tomcat Server. The architecture for sending J2ME is slightly restricted. You cannot have your own SMTP Server. So, the J2ME application works by first establishing a connecting with a website/service and passing the relevant values(Eg: Message Subject, To Address, Message Text) to it. In my case, I used Tomcat and created a Servlet to handle such requests. So, we have two applications running seperately. 1. The J2ME Mobile application 2. The J2SE Server Application On receiving the request, the Servlet would process a

J2ME Split String code segment

Most of you who are used to the split() functionality may miss it a lot when moving on to J2ME. So, here is a code segment which I had used to acchive similar functionality using J2ME methods. public String[] split(String str, String delimiter){ //Iterate through the text to get the count of occurences //This is done since we do not know how many times the //delimitter occurs in the given string //--------------------------------------------------// int delimiterCount=0; int index; String tmpStr=str; String[] splittedList; while((index=tmpStr.indexOf(delimiter))!=-1){ tmpStr=tmpStr.substring(index+delimiter.length()); delimiterCount++; } splittedList=new String[delimiterCount]; /*-----------------------------------------------*/ /*-----------------------------------------------*/ //

Connect MySQL with NetBeans

Image
A very common problem which recurrs through software development is on how to connect to MySQL Database server using NetBeans IDE. In this post, I intend to present a very clear description on how to do so. I have used NetBeans 6.1 with MySQL DB Server. But connecting with other versions of the IDE would be similar. 1. Open your IDE and click on the "Services" Tab as shown. If it is not shown, click on Windows->Services to display it. You can see the Driver for MySQL is already added to NetBeans. Otherwise, right click on "Drivers" and click 'New Driver'. Then show the location of the New Driver. Right Click on MySQL and Click "Connect Using". Then you should get the following dialog. 2. This dialog requests the relevant configuration details of the Database server. You can observe a TextBox displaying the "Database URL". This is the connection String used to connect to the database. There are three main fields which you must supply a)

How to Browse Folders using Dot NET

Image
Most of you may have come up with scenarios where you wish to let the user browse for a specific folder or file. This is most commonly occured when you are requested to open a specific file in Word or Power Point. I would be using Visual Studio 2005 and DOT NET Framework 2.0 DOT NET 2.0 Framework supports several useful dialogs. In this, we will use the "FolderBrowseDialog" class for the example. It can be very easily found in the "ToolBox" under "Dialogs" category. Simply drag and drop one on to your Form. Add a Button also for the demo. Then, double click on the Search Button and it would take you to the Click Event of the Button. Inside that, place the following LOC. DialogResult result; result = folderBrowserDialog1.ShowDialog(); if (result == DialogResult.OK) { MessageBox.Show("Selected Path :" +folderBrowserDialog1.SelectedPath); javascript:void(0) } Lets anal

Encrypt and Decrypt Images Using Java

Hi, Most of you would find it useful to Encrypt a special picture of yours such that only you can view it. By using JCE(Java Cryptography Extension) classes, this becomes very simple. As I have already done before using Java to encrypt a String is very simple. If you are new to this, please read the article which I had already posted named "Java Encryption and Decryption" at "http://ruchiram4.blogspot.com/2009/04/java-encryption-and-decryption.html" Also, you need to have a basic understanding of Java IO. If you are new, it is better to read the Sun Java tutorial on IO. Before we move on, lets recall the basic steps in Encrypting plaintext. 1. Creating an instance of "Cipher" object and setting the mode of Encryption (Eg: AES, DES) 2. Generating a key by using a KeyGenerator object. 3. Setting the mode of Cipher operation on the Cipher object. As we intent to Encrypt, we simply set it by setting a property of Cipher object by calling its "init"

Off The Record Protocol (OTR)

Off The Record Protocol (OTR) is one of the emerging protocols today. It is becoming more and more popular amongst Internet Messenger Services by providing a service similar to a conversation by two people. Internet Messenger Applications such as Pidgin has already implemented such a plugin fo the application and other messenger services are already on the move with implementing the feature. OTR provides the two parties to have a conversation between them by providing the following features. i) Encryption : Messages can be read by only the two parties involved. ii) Authentication : Lets each parties know that they are chatting with the person who they think they are. In simpler terms, this features prevents forging by a third party by imitating the other person. iii) Deniability(Repudiability) : This is a controversial term. We are very much used with the term 'Non Repudiability' when we talk about Computer Security. But here, we specifically allow repudiability to occur. iv) P

Java Encryption and Decryption

Hi Folks, Most of you would be very much interested to know how to use java to do crypto work. In this post, I would demonstrate how to use JCE(Java Cryptography Extension) Classes and methods to very simply Encrypt and Decrypt a PlainText. This article is intended for an audience who is familiar with cryptography concepts and is looking for an implementation of such an algorithm in Java. If you are looking to learn Cryptography concepts, this post may not be helpful. JCE provides us with a bunch of useful classes to accomplish this. I would demonstrate how to do so using Cipher class. Cipher class is handy to handle such task. You can get an instance of a Cipher Class by calling its static method ENCRYPTION Cipher cipher=Cipher.getDefaultInstance("DES"); This accepts a string indicating the encrypting algorithm. For now, we will use DES(Data Encryption Standard) In order to Encrypt, we need a key. A key can be easily generated by using the KeyGenerator Class provided. KeyGen

Build your own SNMP Monitoring Tool

Image
SNMP is a protocol used widely for monitoring and extracting status information of a working device. Using SNMP protocol, you can extract the present information about a certain device. It is widely used for monitoring network devices such as Routers. But, practically any device which supports SNMP protocol can be used. As an example consider a SNMP enabled network printer inside an organization. The Network admin can issue necessary commands to the SNMP enabled device to get the status of the printer to check the status of the printer to see whether it is working as it should. Furthermore, the SNMP enabled device can be configured to issue an alert once a condition is met. As an example, there may be a Network printer which can be configured to make an alert once the ink level drops below a certain level. The breadth of SNMP is determined by the capabilities embedded into the device itself. Another very useful scenario is where a JVM(Java Virtual Machine) can be SNMP enabled to be mon

How to pass a collection of data to SQL Server

Hi all. If you are faced with a situation where you wish to send an array of strings(say) to the Server, then you have stumbled to the correct page :-) To start off with, SQL server up to 2005 does not support Arrays. So, it becomes a bit difficult for Java,C#,C++ programmers who are very fond of arrays to get their job done. Fortunately there is a detour which enables us to get the job done. Instead of sending the list as an array, we can append a delimiter(here I used the comma) and send the complete string to the server side. At the server side, it splits the separate strings by the delimiter and inserts them into a table(her I used it as a single column table of the form tmpTable(_name varchar(50))) You can use the values inserted into this table and use the results similar to having an array. NOTE: It does not support the sophisticated array functions you are used to, but it will let you get the job done. /* PROCEDURE NAME : readCSV AUTHOR : Ruchira Randana PROCEDURE DESC

Connect SQL Server Express 2005 with NetBeans IDE

Image
Hi, Most of you Java Folks may have encountered situations where you wish to code using Java but need to connect to a Microsoft SQL Server Database. To an experienced person, this may seem trivial, but for newbies, this can be a troublesome task. Through this post, I would briefly describe how to connect to Microsoft SQL Server 2005 Express Edition using NetBeans 6.0.1 IDE. STEP 1: Download the relevant JDBC driver from the microsoft site. (A search on the internet will more than suffice) STEP 2: Add the driver to NetBeans IDE. This can be done as follows. On the services tab, under Databases under Drivers, you can add a new driver as follows On the Window, click Add and select the necessary Jar file of the driver. Then click Find. It will search the class name and display it as follows Once the driver is installed, you can right click on it and click 'connect using' Then you will get the following screen Fill in your database name and host address. The port is usually 1433. Yo