Free Information Technology Magazines and eBooks

Thursday, May 07, 2009

How to Read POP3 email using C#

Aside from sending email notification, sometimes we require our application to read POP3 emails. Today I will show you how to read POP3 mails using SmtPop.Net in C#. SmtPop.Net is an open source class library to receive and send e-mail messages through SMTP and POP3 server.


First you need to reference smtpop.dll on you .NET project. Then include SmtPop on the Using directives as follows:

using SmtPop;


Now here is a sample code to read POP3 emails:

// connect to pop3 server
POP3Client pop = new POP3Client ();
pop.ReceiveTimeout = 3 * 60000; // Set the timeout to 3 minutes
pop.Open ("mymailserver", "110", "sampleuser", "password");

// retrieve messages list from pop server
POPMessageId[] messages = pop.GetMailList ();

if (messages != null)
{
// run through available messages in POP3 server
foreach (POPMessageId id in messages)
{
POPReader reader = pop.GetMailReader (id.Id);
MimeMessage msg = new MimeMessage ();

// read the message
msg.Read (reader);
if (msg.Attachments != null)
{
// retrieve attachements
foreach (MimeAttachment attach in msg.Attachments)
{
if (attach.Filename != "")
{
// read data from attachment
Byte[] b = Convert.FromBase64String (attach.Body);
// save attachment to disk
System.IO.MemoryStream mem = new System.IO.MemoryStream (b, false);
FileStream outStream = File.OpenWrite(attach.Filename);
mem.WriteTo(outStream);
mem.Close();
outStream.Flush();
outStream.Close();
}
}
}
//delete message
pop.Dele (id.Id);
}
}
//close the connection to POP3 server
pop.Quit ();


Aside from reading emails, SmtPOP.NET can also send e-mail to an SMTP server.
To download the SmtPOP.NET library click here



For more C# tips and tricks, subscribe now



Cybercriminals taking advantage of Swine flu scare

Swine flu virus and SEOTo be an internet goon nowadays, you just don't need to know hacking, you must also good in Search Engine Optimization. This is what the blog from PandaLabs uncovered. Cybercriminals manage to take advantage of the recent swine flu scare by using Blackhat SEO techniques to enable malicious websites to take top position in search engines. Cyber-crooks uses keyword with "swine flu" to persuade victims and redirect them to malware sites.


Qouted from PandaLabs blog:

Just look what we found in Google: a search engine which offers information about the swine flu.

swine flu and blackhat seo

When clicking on the results displayed by the search engine, we are redirected to porn sites where we can view videos. However, to view a video we are required to install the last version of a player.




For more tech news, subscribe now



Wednesday, May 06, 2009

How to Send Email using VB.NET or C#

Email notification is a great tool to inform administrators or users that an important  event happened. Fortunately for VB.NET programmers, Microsoft built the .NET framework full of ready- to-use namespaces such as System.Net.Mail. It is the namespace used to send email if you are using the 2.0 (or higher) .NET Framework. Unlike its predecessor (System.Web.Mail), which was introduced in the 1.0 Framework, System.Net.Mail is not built from the CDO/CDOSYS libraries. Instead it is coded from scratch without any interop so it is not dependent to any other COM libraries.


Requirements to send Email in .NET
1. We need to reference the System.Net.Mail namespace to create and send email messages.
Use it on VB.NET

Imports System.Net.Mail


Or in C#

Using system.Net.Mail

2. We need a relay server to send email through. A relay server is a mail server, or a SMTP server/service, that can handle sending email. System.Net.Mail sends the mail to a relay server, and the relay server is responsible for delivering it to the recipient's mail server.

Sample code of sending plain text using VB.NET


'create the mail message
Dim mail As New MailMessage()

'set the addresses
mail.From = New MailAddress("me@mycompany.com")
mail.To.Add("you@yourcompany.com")

'set the content
mail.Subject = "This is an email"
mail.Body = "this is a sample body"

'send the message
Dim smtp As New SmtpClient("127.0.0.1")
smtp.Send(mail)


Sample code of sending plain text using C#
//create the mail message
MailMessage mail = new MailMessage();

//set the addresses
mail.From = new MailAddress("me@mycompany.com");
mail.To.Add("you@yourcompany.com");

//set the content
mail.Subject = "This is an email";
mail.Body = "this is a sample body";

//send the message
SmtpClient smtp = new SmtpClient("127.0.0.1");
smtp.Send(mail);


To send an email in HTML format, just add set the isBodyHtml property to true of the MailMessage object. After setting it, you can already include HTML tags inside the Body property.

In VB.NET

'set the content to HTML
mail.IsBodyHtml = true


In C#:

//set the content to HTML
mail.IsBodyHtml = true;


To add an attachment on your email, make use of the Attachements property as shown below.

Email Attachment in VB.NET

Dim file as String = "C:\attachment.dat"
If Not file = "" Then
Dim MsgAttach As New Attachment(file)
mail.Attachments.Add(MsgAttach)
End If


Email Attachment in C#

string file = @"C:\attachment.dat";
if (file.Length>0)
{
Attachment MsgAttach = new Attachment(file);
mail.Attachments.Add(MsgAttach);
}


Basically thats all we need to learn to send email using .NET. I also created a VB.NET class that has all email sending functions.
Here's how you can call the ready-to-use class in your application:

Dim oEmail As New clsEmail
oEmail.SendEmailMessage(From_Email, From_Name, strEmailTo, "Event Notification", BodyMsg, "")


You can download the class from Mediafire



For more .NET tips and tricks, subscribe now

Windows 7 security lapse, allows unsafe files to be disguised as safe files

Unsafe files disguises as safe files in Windows 7Found this article from F-Secure who discovered a security lapse on the new version of Windows. The fault is nothing new and in fact it exist on the previous and current build. In windows explorer of Windows NT, 2000, XP and Vista, user can hide extensions of known file types just by going to Tools>Folder Options. Virus coders used this "feature" to make people mistake executables for stuff such as document files. The trick is to rename any executable file and add any known file type, For example you can make MALWARE.EXE to MALWARE.TXT.EXE and Windows will automatically hide the .EXE part of the filename that would be tricky to ordinary computer users.


Here are some sample screenshots of the testing done by F-Secure in Windows 7.

It look like just a text file


But on command prompt, the exe is uncovered.
Unsecured files in Windows 7

This is a very easy way to get people clicking on the unsafe files.

If you want to be notified for future tech news, subscribe now




Tuesday, May 05, 2009

C#: How to save and retrieve image to MS SQL

Store image to SQL using C#This morning, my fried buzz me and asking for help. He is creating a customer profile module which contains images like company logo and customer picture. He want to save actual data of the images to a Microsoft SQL server database rather than just storing the file's full path. On this post, using C#, I will try to show you the following:
- How to save or store images to MS SQL?
- How to retrieve and display images from MS SQL?
The complete source code of the sample project used on this post can be downloaded from this link.


Storing images to MS SQL Server is easy, first you have to create a field with an Image type. Just copy and paste the following CREATE TABLE script on your query analyzer to create the table.


CREATE TABLE [dbo].[tblImages](
[FullPath] [nvarchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[MyImageSample] [image] NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]


On your C# project, add the following controls:

- Textbox for image path
- Textbox for connection string (database)
- Button for saving image to database
- Button for retrieving image from database
- Picture control to display the image

Your form is more or less should look like this:

Save image to SQL using C#

Now lets do the coding, Add the ReadImageToBytes function written below (this will be called on the Save event):

//Open image file then convert into byte array
byte[] ReadImageToBytes(string sPath)
{
//Initialize byte array with a null value initially.
byte[] data = null;

//Use FileInfo object to get file size.
FileInfo fInfo = new FileInfo(sPath);
long numBytes = fInfo.Length;

//Open FileStream to read file
FileStream fStream = new FileStream(sPath, FileMode.Open,
FileAccess.Read);

//Use BinaryReader to read file stream into byte array.
BinaryReader br = new BinaryReader(fStream);

data = br.ReadBytes((int)numBytes);
return data;
}

ReadImageToBytes convert the image into bytes that will be stored to database later. Now on your save button, put the following code inside the Click event as shown below:

private void btnSave_Click(object sender, EventArgs e)
{
try
{
//Read Image Bytes into a byte array
byte[] imageSampleData = ReadImageToBytes(txtImagePath.Text);

//Initialize SQL Server Connection
SqlConnection con = new SqlConnection(txtConnectionString.Text);

//Set insert query
string query = "INSERT INTO tblImages (FullPath,MyImageSample) values(@FullPath, @MyImageSample)";

//Initialize SqlCommand object for insert.
SqlCommand cmd = new SqlCommand(query, con);

cmd.Parameters.Add(new SqlParameter("@FullPath",
(object)txtImagePath.Text));

cmd.Parameters.Add(new SqlParameter("@MyImageSample",
(object)imageSampleData));

//Open connection and execute insert query.
con.Open();
cmd.ExecuteNonQuery();
con.Close();


}
catch
{
MessageBox.Show("Error while saving image.", "Error");
}
}


The save button code will insert the byte image into SQL table with image type. You can verify this by opening your table using Query Analyzer or Enterprise Manager.


Now lets double click the retrieve button and add the following code to fetch our stored image:


private void btnRetrieveImage_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(txtConnectionString.Text);
SqlCommand cmd = new SqlCommand();
try
{
con.Open();
cmd.Connection = con;
cmd.CommandText = "SELECT Top 1 MyImageSample FROM tblImages"; // for this example only get top record
byte[] Img = (byte[])cmd.ExecuteScalar();
// Convert the image record to file stream and display it to picture control
string str = Convert.ToString(DateTime.Now.ToFileTime());
FileStream fs = new FileStream(str, FileMode.CreateNew, FileAccess.Write);
fs.Write(Img, 0, Img.Length);
fs.Flush();
fs.Close();
pic1.Image = Image.FromFile(str);
}
catch
{
MessageBox.Show("Error while saving image.", "Error");
}
finally
{
con.Close();
}

}


We're done. Now you have a program than can save and retrieve images. You can also download the complete sample project at mediafire.



For more C# tips and tricks, subscribe now


Pidgin: All in one Instant Messaging

Pidgin: All in one Instant MessagingI've been using this great all-in-one messenger for quiet some time now. Its been useful for me so I think its time to give it some credit. Pidgin is a chat program which lets you log in to accounts on multiple chat networks simultaneously. This means that you can be chatting with friends on MSN, talking to a friend on Google Talk, and sitting in a Yahoo chat room all at the same time. Pidgin can run on multiple operating system such as Windows, Linux and UNIX.

Pidgin is also compatible with the following chat networks
AIM, ICQ, Jabber/XMPP, Bonjour, Gadu-Gadu, IRC, Novell GroupWise Messenger, QQ, Lotus Sametime, SILC, SIMPLE, MySpaceIM, and Zephyr.

And most of Pidgin is open source, free and contains no ads. So it means you can get Pidgin's code and revise it to suit your needs. If you want to extend its capabilities without changing the code, you can use several official and 3rd-party plugins such as Facebook IM (it rocks!) and Twitter protocol.

Try it for yourself! you can download it from pidgin download page.

For more information on Cool Softwares, subscribe now


Monday, May 04, 2009

.NET FileSystemWatcher, watch for changes in a specified directory

Ever wanted to be notified if there are file changes on a specified directory on your local computer, a network drive, or a remote computer? The watcher application should detect file event such as change, creation, deletion and rename. You can implement such kind of application in .NET using FileSystemWatcher Class. Using this class you can watch any activities users can do in your monitored folder.



To implement FileSystemWatcher Class, you need to include using System.IO namespace.

Here a sample folder monitoring C# code:

using System.IO;
// Watches the C:\Temp folder and notifies creation of new text files

public static void MonitorFolder(string strFolder)
{
// Create the FileSystemoFileSystemWatcher object and set its properties

FileSystemWatcher oFileWatcher = new FileSystemWatcher();
oFileWatcher.Path = @strFolder;
oFileWatcher.NotifyFilter = NotifyFilters.LastAccess
| NotifyFilters.LastWrite | NotifyFilters.FileName |
NotifyFilters.DirectoryName;
oFileWatcher.Filter = "*.txt";

// Add event handlers.

oFileWatcher.Created += new FileSystemEventHandler(OnChanged);
oFileWatcher.Changed += new FileSystemEventHandler(OnChanged);
oFileWatcher.Deleted += new FileSystemEventHandler(OnChanged);
oFileWatcher.Renamed += new RenamedEventHandler(OnRenamed);

// Begin watching/monitoring.

oFileWatcher.EnableRaisingEvents = true;

// Wait for the user to quit the program.

Console.WriteLine("Press \'x\' to exit the watcher.");
while(Console.Read()!='x');
}

// The event handlers

private static void OnChanged(object source, FileSystemEventArgs e)
{
Console.WriteLine("File: " + e.FullPath + " " + e.ChangeType);
}
private static void OnRenamed(object source, RenamedEventArgs e)
{
// Specify what is done when a file is renamed.
Console.WriteLine("File: {0} renamed to {1}", e.OldFullPath, e.FullPath);
}


Lets translate it to VB.NET

Imports System.IO

Private Sub MonitorFolder(strFolder as String)
' Create a new FileSystemWatcher and set its properties.
Dim oFileWatcher As New FileSystemWatcher()
oFileWatcher.Path = strFolder
' Watch for changes in LastAccess and LastWrite times, and
' the renaming of files or directories.

oFileWatcher.NotifyFilter = (NotifyFilters.LastAccess Or NotifyFilters.LastWrite Or NotifyFilters.FileName Or NotifyFilters.DirectoryName)
' Only watch text files.
oFileWatcher.Filter = "*.txt"

' Add event handlers.
AddHandler oFileWatcher.Changed, AddressOf OnChanged
AddHandler oFileWatcher.Created, AddressOf OnChanged
AddHandler oFileWatcher.Deleted, AddressOf OnChanged
AddHandler oFileWatcher.Renamed, AddressOf OnRenamed

' Begin watching.
oFileWatcher.EnableRaisingEvents = True

' Wait for the user to exit the program.
Console.WriteLine("Press 'x' to exit the watcher.")
While Chr(Console.Read()) <> "x"
End While
End Sub

' Define the event handlers.
Private Shared Sub OnChanged(source As Object, e As FileSystemEventArgs)
' Specify what is done when a file is changed, created, or deleted.
Console.WriteLine("File: " & e.FullPath & " " & e.ChangeType)
End Sub

Private Shared Sub OnRenamed(source As Object, e As RenamedEventArgs)
' Specify what is done when a file is renamed.
Console.WriteLine("File: {0} renamed to {1}", e.OldFullPath, e.FullPath)
End Sub


Now add this function on your .NET application and begin monitoring your specified folder.

For more .NET tips and tricks, subscribe now

Software to uninstall stubborn security applications

uninstall stubborn security applicationsWhile looking for uninstaller software, I found this interesting software that enable users to uninstall only security applications that just don't go away such as antivirus and antispyware. I tried using it on my office computer which has corrupted AVG free antivirus software and it amazingly did the job. This software is called AppRemover and was developed by OPSWAT, Inc. The software is totally free to use. I was able to remove my AVG in 2 minutes including the installation time.


Before downloading AppRemover, please take note that it can only remove antivirus and antispyware. Yes, it cannot remove other types of application. Here is the list of supported applications.

uninstall stubborn security applications

You can download the software here

For more information on cool softwares, subscribe now

Sunday, May 03, 2009

C#: How to Write to Windows Event Log

Application log is a must for good programmers to troubleshoot applications problems. Most of these logs are written on text file or database. But these types of logs are only good if the programmer himself is the one whos supporting his own software. If your creating a windows service that will be administered by system adminitrators it would be a best practice to write your logs on Windows Event Log. This way your system administrator will be notifed in case some failures or important events occur.

Here's how to do it in C#:
First, add System.Diagnostics namespace on your Using Directives:

using System.Diagnostics;


Now Let's code the event log function:
public void WriteEventToWindowsLog(string strMyApp, string strEvent)
{
if (!System.Diagnostics.EventLog.SourceExists(strMyApp))
System.Diagnostics.EventLog.CreateEventSource(strMyApp, "Application");

EventLog MyEventLog = new EventLog();
MyEventLog.Source = strMyApp;
MyEventLog.WriteEntry (strEvent, EventLogEntryType.Warning);
}


Just include the WriteEventToWindowsLog function above to your application and you already got your windows event logger.

For more C# Tips and Tricks, subscribe now

Secrets revealed from historical maps on Google Earth

Google Earth JapanTOKYO - When Google the search giant included historical maps of Japan to Google Earth's collection last year they didn't realise that it could backfire. The company is now facing inquiries from the Japan's Justice Ministry and angry accusations of prejudice because its maps detailed the locations of former low-caste communities. The maps date back to the country's feudal era, when shoguns ruled and a strict caste system was in place. At the bottom of the hierarchy were a class called the "burakumin," ethnically identical to other Japanese but forced to live in isolation because they did jobs associated with death, such as working with leather, butchering animals and digging graves

Castes have long since been abolished, and the old buraku villages have largely faded away or been swallowed by Japan's sprawling metropolises. Today, rights groups say the descendants of burakumin make up about 3 million of the country's 127 million people.

An employee at a large, well-known Japanese company, who works in personnel and has direct knowledge of its hiring practices, said the company actively screens out burakumin job seekers.

If we suspect that an applicant is a burakumin, we always do a background check to find out,
she said. She agreed to discuss the practice only on condition that neither she nor her company be identified.

Read the full story at yahoo tech news

If you want to be notified for future tech news, subscribe now

Saturday, May 02, 2009

How to Cartoonize yourself

Cartoonize meI stumbled with this cool site that let you convert any existing pictures of yours to cartoon portrait. It is called BeFunky and it has a photo application called cartoonizer. The service is easy to use, free and instant. After seconds, you can download your cartoonize picture to your computer or share it through your favorite social networking sites. To do all of this, there is no software to download, all processing are done online. Now let's turn your offline personalities within photos and videos into powerful online visual expressions. Just follow this step-by-step procedure to start the cartoon of you.


1. Go to BeFunky photo apps page.
2. Choose Cartoonizer from the list of tools.
3. Select where you want to get your file: upload it from your computer, upload from a website, upload from photosharing sites or use your web cam.

Upload picture to cartoonize

4. After uploading the picture, Befunky will allow you to edit your final photo before applying the cartoon effects.

Final Editing of your cartoon pictures

5. Then after Befunky processed your photo. You can save it to your computer or share it on your favorite photo sharing website.

Cartoon Photo of Me

There you have it! Have some fun with your own cartoonist on-demand!

For more information on cool softwares, subscribe now.


Friday, May 01, 2009

How to translate SQL 2005 database script to sql 2000

SQL 2005 Generate ScriptsMy brother who is a newly computer science graduate was developing his first application for his first customer as a freelancer. It was a billing system from scratch using VB.NET and SQL 2005. He already generated the SQL 2005 database scripts to be use in deployment on his client's server. Unfortunately his customer has only SQL 2000 license and not SQL 2005. So the dilemma was, how can he deploy his application on SQL 2000? Will his SQL 2005 scripts work on SQL 2000?


He tried running the SQL 2005 scripts on the SQL 2000 query analyzer and the result was a series of errors that look like this:

Msg+170,+Level+15,+State+1,+Line+7Line+7:
+Incorrect+syntax+near+'('.


Lucky for him, his big brother knows the answer. You can translate SQL 2005 database scripts to a form that is executable or readable on SQL 2000. To generate such kind of SQL script, here is a step-by-step procedure:

1. Open your SSMS (SQL Server Management Studio).
2. Right click your database then choose "Generate Scripts" from the context menu.



3. In Choose Scripts Option, Find the "Script for Server version" then select SQL Server 2000.

Script for Server version Option

4. Click next to finish.

Then it will generate the scripts compatible to SQL Server 2000.

For more SQL fix, subscribe now.