Navigation


RSS : Articles / Comments


Send Gmail using Dot NET

1:19 AM, Posted by ruchira, No Comment

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.Net.Mail;
using System.Net;

using System.Net.Security;


Now, create a MailMessage object using the following LOC.

MailMessage mail = new MailMessage();

Now, lets set the sender's address and receiver's address. We create a MailAddress object and set the value directly from its constructor.

mail.From = new MailAddress("from@gmail.com","Any name to appear as alias");

Now set the receiver.

mail.To.Add(new MailAddress("toaddress", "
Any name to appear as alias"));

NOTE: You cannot simply set the To Address in a similar way as setting from address. ie: You cannot set
mail.To=new MailAddress("yourffiend", "Alias name");
This is because, you can send a mail to multiple people at once. Hence, the To property of a mail object contains a collection of MailAddress objects. You can add a new mail address to the collection in the above manner.

Now create an SmtpClient object. This can be done using.

SmtpClient smtp = new SmtpClient();


Next, we will set the host address of the smtp server.

smtp.Host = "smtp.gmail.com";

And the port.

smtp.Port = 587;


NOTE: If you are using your own SMTP mail server, then the port would be port 25.

We will use our own credentials. Thus disable the default credentials.

smtp.UseDefaultCredentials = false;

We
must enable SSL.

smtp.EnableSsl = true;


Now we will create our own credentials using the following LOC.
First create a NetworkCredential object.

NetworkCredential cred = new NetworkCredential();


And now set the required usename and password.

cred.UserName = "username";

cred.Password="password";

And now , set the credentials of the smtp object to the credentials we created.

smtp.Credentials = cred;

Now, you can send the main using the follwing LOC.

smtp.Send(mail);

I have taught you the basic procedure, now you can extend it to get the job done your way. Have fun Folks !!!!

Download File using Dot Net

2:34 AM, Posted by ruchira, No Comment

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

4:04 AM, Posted by ruchira, No Comment

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)

10:49 AM, Posted by ruchira, No Comment

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 folder for your application inside the root folder.




For the demonstration, I will use a simple web site with just one web page. It would display the simple Hello World message. Just copy the following code segment into a text editor and save it as "index.html". Now, place this html code in your web server's application root folder.

<html>
<head>
<link rel="shortcut icon" href="favicon.ico">
</head>

<body>
<table>
<tr>
<td>Hello World!</td>
</tr>
</table>
</body>
</html>

Now, make sure that you place the code in red in the header. It is needed if you need to change the image location other than the root folder. So, if you need to save the image in a folder named images, then you could simply locate the file using the path to the directory.

Now, the folder structure should be similar to the following.



Now, start your web server. In my case, I would start WAMP's Apache service. Then view it through a browser. When you view it, it should be automatically displayed on the left of the addressbar.



NOTE: You may sometimes need to clear the browser cash for the image to be displayed and restart the Web Server.

Cheers

ASP Regular expression to check length of textbox value

11:58 PM, Posted by ruchira, 4 Comments

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 following regular expression for the validator.

"[A-Za-z0-9]{5,10}"

Now, suppose you only wish to have a certain number of special characters only. Say you need to accept the space( ) period(.) , comma(,) and dash(-) only with the alphanumerics. Then use the following regex.

"[A-Za-z0-9.-,\s]{5,10}"

You can modify the above code for your custom needs.
Have fun.

URL Regular Expression

2:26 AM, Posted by ruchira, 3 Comments

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

5:13 AM, Posted by ruchira, No Comment

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 implement the above method signature and write the relevant code/ logic associated with it.

Note that this method returns an integer. The values which we will use are in the set of {-1,1,0} . So, when we want to sort an array of cars, the JVM will decide on which should be first by looking at the return value. If it is -1, it implies that the second value is larger, if the value returned is 0, it implies both should have the same value.
Since we want to sort them according to the age, we will write the following LOC.

public int compareTo(Car o) {

if (this.age
return -1;
}
else if(o.age==this.age){
return 0;
}
else{
return 1;
}
}

Now, we have done the necessary work to sort. Lets give it a try by using a demo.

First create an array of Car objects and put them in a randomn order.

Car[] carArray= new Car[5];

Car c1 = new Car();
Car c2 = new Car();
Car c3 = new Car();
Car c4 = new Car();
Car c5 = new Car();

c1.setAge(1);
c1.setColor("blue");
c1.setId("");

c2.setAge(2);
c2.setColor("black");
c2.setId("");

c3.setAge(3);
c3.setColor("red");
c3.setId("");

c4.setAge(4);
c4.setColor("green");
c4.setId("");

c5.setAge(5);
c5.setColor("purple");
c5.setId("");


carArray[0]= c4;
carArray[1]= c1;
carArray[2]= c3;
carArray[3]= c5;
carArray[4]= c2;

System.out.println("----------------------------------------------------");
System.out.println("----------------------------------------------------");
System.out.println("Before Sorting");
System.out.println("");


As we observe, the Car objects are not in the correct order. They are in the order of [C4, C1, C3, C5, C2]

NOTE: After the sort, they should be in the order of [C1,C2,C3,C4,C5]

Now, lets print the array to see how they are before we order.

print(carArray);

Now, lets call the sort.

We can call a sort using the Arrays.sort(); method. It belongs to the class Arrays declared in java.utils package. This class has a static method sort, which accepts an array of objects which must implement the comparable interface.
(Since our Car class implemented the interface, we can pass an array of Car objects to this method)

Arrays.sort(carArray);

Now, lets try to print this and see what we get.

print(carArray);

Presto !!!!!! We get an array which is according to the correct order as we required. Thus, by using the Comparable interface in java, we can write almost any custom ordering rule for our classes.
Hope you enjoyed this !!!!!!
Happy coding !!!!

:)



 
[source language="xml"] [/source]