Friday, June 11, 2010

Detect Changes in Network Connectivity

Some times you will need a mechanism to check whether changes to network occurring during running your application.
So as a solution for this you can add handlers to the static NetworkAddressChanged and NetworkAvailabilityChanged events implemented by the System.Net.NetworkInformation.NetworkChange class.

Souce Code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.NetworkInformation;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            // Add the handlers to the NetworkChange events.
            NetworkChange.NetworkAvailabilityChanged +=
            NetworkAvailabilityChanged;
            NetworkChange.NetworkAddressChanged +=
            NetworkAddressChanged;

            Console.ReadLine();
        }

        // Declare a method to handle NetworkAvailabilityChanged events.
        private static void NetworkAvailabilityChanged(
        object sender, NetworkAvailabilityEventArgs e)
        {
            // Report whether the network is now available or unavailable.
            if (e.IsAvailable)
            {
                Console.WriteLine("Network Available");
            }
            else
            {
                Console.WriteLine("Network Unavailable");
            }
        }
        // Declare a method to handle NetworkAdressChanged events.
        private static void NetworkAddressChanged(object sender, EventArgs e)
        {
            Console.WriteLine("Current IP Addresses:");
            // Iterate through the interfaces and display information.
            foreach (NetworkInterface ni in
            NetworkInterface.GetAllNetworkInterfaces())
            {
                foreach (UnicastIPAddressInformation addr
                in ni.GetIPProperties().UnicastAddresses)
                {
                    Console.WriteLine(" - {0} (lease expires {1})",
                    addr.Address, DateTime.Now +
                    new TimeSpan(0, 0, (int)addr.DhcpLeaseLifetime));
                }
            }
        }
    }
}

Download Source Code
http://www.4shared.com/file/gyfzpCB_/ConsoleApplication1.html

Monday, June 7, 2010

Obtain Information About the Local Network Interface

Here you will learn ,How to obtain information about the network adapters and network configuration of the local machine.

Code section for application

/****************************************
 * Coded By : D. E Sandaruwan           *
 * Email : erandika1986@gmail.com       *
 * Skype : erandika.sandaruwan          *
 * **************************************/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net.NetworkInformation;

namespace GetNetWorkAdaInfor
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btnGetInfo_Click(object sender, EventArgs e)
        {
            //Only proceed if there is a network available
            if (NetworkInterface.GetIsNetworkAvailable())
            {
                //Get the set off all NetworkInterface objects for the local machine
                NetworkInterface[] inteface = NetworkInterface.GetAllNetworkInterfaces();

                rtxtInfo.Text = "======================================================================" + "\n";

                //Iterate through the interface and display information
                foreach (NetworkInterface netInter in inteface)
                {
                    //Print basic inteface info
                    rtxtInfo.Text = rtxtInfo.Text + "Interface Name : " + netInter.Name + "\n";
                    rtxtInfo.Text = rtxtInfo.Text + "Description    : " + netInter.Description + "\n";
                    rtxtInfo.Text = rtxtInfo.Text + "ID             : " + netInter.Id + "\n";
                    rtxtInfo.Text = rtxtInfo.Text + "Type           : " + netInter.NetworkInterfaceType + "\n";
                    rtxtInfo.Text = rtxtInfo.Text + "Speed          : " + netInter.Speed + "\n";
                    rtxtInfo.Text = rtxtInfo.Text + "Status         : " + netInter.OperationalStatus + "\n";

                    //report physical address
                    rtxtInfo.Text = rtxtInfo.Text + "Physical address : " + netInter.GetPhysicalAddress().ToString() + "\n";

                    //report network statistics for the interface.
                    rtxtInfo.Text = rtxtInfo.Text + "Byte Sent      : " + netInter.GetIPv4Statistics().BytesSent + "\n";

                    rtxtInfo.Text = rtxtInfo.Text + "Byte Received  : " + netInter.GetIPv4Statistics().BytesReceived + "\n" + "\n" + "\n";

                    //Report IP configuration
                    rtxtInfo.Text = rtxtInfo.Text + "IP Address     : " + "\n";

                    foreach (UnicastIPAddressInformation addr in netInter.GetIPProperties().UnicastAddresses)
                    {
                        rtxtInfo.Text = rtxtInfo.Text + addr.Address + " , Lease expires : " + DateTime.Now + new TimeSpan(0, 0, (int)addr.DhcpLeaseLifetime) + "\n";
                    }

                    rtxtInfo.Text = rtxtInfo.Text + "======================================================================" + "\n";
                }
            }
            else
            {
                rtxtInfo.Text = "No network available in this machine.";
            }
        }
    }
}



Download Source Code here

Monday, May 31, 2010

Retrieve Information About a File

Following example takes a file path from textbox named by txtpath, and the display the information about the file.

User Interface













Coding Part
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace FileUpload
{
    public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
        }

        private void btnSelect_Click(object sender, EventArgs e)
        {
            string fileName = "";
            string path = "";
            OpenFileDialog fDialog = new OpenFileDialog();
            fDialog.Title = "Attach customer proposal document";
            fDialog.Filter = "Doc Files|*.doc|Docx File|*.docx|PDF doc|*.pdf";
            fDialog.InitialDirectory = @"C:\";
            if (fDialog.ShowDialog() == DialogResult.OK)
            {
                fileName = System.IO.Path.GetFileName(fDialog.FileName);
                path = Path.GetDirectoryName(fDialog.FileName);
                txtpath.Text = path + "\\" + fileName;

            }
        }

        private void btnShowInfo_Click(object sender, EventArgs e)
        {
            //To display file information
            FileInfo myFile = new FileInfo(txtpath.Text);

            rtxtInfor.Text = "Checking File: " + myFile.Name+"\n";
            rtxtInfor.Text=rtxtInfor.Text+"File exists: "+myFile.Exists.ToString()+"\n";

            if (myFile.Exists)
            {
                rtxtInfor.Text = rtxtInfor.Text + "File Created:" + myFile.CreationTime.ToString() + "\n";
                rtxtInfor.Text = rtxtInfor.Text + "File Last Updated: " + myFile.LastWriteTime.ToString() + "\n";
                rtxtInfor.Text = rtxtInfor.Text + "File Last accessed: " + myFile.LastAccessTime.ToString() + "\n";
                rtxtInfor.Text = rtxtInfor.Text + "File Size (bytes): " + myFile.Length.ToString() +"\n";
                rtxtInfor.Text = rtxtInfor.Text + "File attribute list: " + myFile.Attributes.ToString() + "\n";

            }




        }
    }
}














Sunday, May 30, 2010

Upload Files to Remote PC

Here first You have to create a folder in remote machine and You have to share that folder with other network users.

And then using following method you can upload files to the remote shared folder. public int FileUpload(string SourceFilepath)
{
try
{
WebClient client = new WebClient();

//Credential information for remote Mechine.-> here I used Username=erandika1986 and Password=123
NetworkCredential nc = new NetworkCredential("erandika1986", "123");

//Here we have to give destination information
Uri addy = new Uri(@"\\192.168.2.4\UploadDocs\" + fileName);

//Here we set the the credential information to the Webclient
client.Credentials = nc;

//upload the file from Source to the destination
client.UploadFile(addy, SourceFilepath);

return 1;

}
catch (Exception ex1)
{
MessageBox.Show(ex1.Message);
return 0;
}

}

Saturday, May 29, 2010

Send Email using SMTP Server

The .NET Framework includes the System.Net.Mail namespace, whcich provides classes to create and send email messages.Messages can include plain text,HTML and attachments

Creating & Send an email

Here We will create a class called email and we will implement the method called SendEmail inside the class.

Here the implemented class

***********************************************************
Remember you should add namespace "System.Net.Mail" first
***********************************************************

public class email
{
public int SendEmail()
{
try
{
//Create a MailMessage object
MailMessage mail = new MailMessage();

//To specify sender email address and Sender name
mail.From = new MailAddress("sender Email address", "Sender name");

//To specify recipient email address and recipient name
mail.To.Add(new MailAddress("recipient email address", "recipient name"));

//Set email Subject
mail.Subject = "Sample Email";

//Specify as HTML message body
mail.Body ="This is my message body";

//To Enable HTML body->You can type your message body using html tag.But blogger not support to post html tag in here.To enable HTML body you can use following code line.
//mail.IsBodyHtml = true;

//Attach files
mail.Attachments.Add(new Attachment(@"D:\oracle_database_11g.pdf"));


//Create a SmtpClient object
SmtpClient client = new SmtpClient();

//Assign a host for the client
client.Host = "smtp.gmail.com";

//Assign a port
client.Port=587;

//Give Credential information->Username and Password
client.Credentials=new System.Net.NetworkCredential("Your Username","Your Password");

//To enable SSL
client.EnableSsl=true;

//Send the mail
client.Send(mail);

return 1;
}
catch (Exception ex1)
{
MessageBox.Show(ex1.Message);
return 0;
}
}


}

How to use MS Outlook API to send mails

First You have to add Microsoft.Office.Interop.Outlook using References.To do that go to Solution Explorer->Reference->Add Reference->.NET tab->Microsoft.Office.Interop.Outlook.

After that we will create a small class called SendEmails and we will implement a method called sendGroupmail.

Here the Implementation for SendEmails Class.

public class SendEmails
{
public int sendGroupMail(string recipientsList, string subject, string body)
{
Outlook.Application objectOutLook = new Outlook.Application();

try
{
Outlook.MailItem mailItem = objectOutLook.CreateItem(Outlook.OlItemType.olMailItem) as Outlook.MailItem;
mailItem.Subject = subject;
mailItem.To = recipientsList;
mailItem.Body = body;
Outlook.NameSpace ns = objectOutLook.GetNamespace("mapi");
ns.Logon(Missing.Value, Missing.Value, true, true);
mailItem.Importance = Outlook.OlImportance.olImportanceLow;
((Outlook.MailItem)mailItem).Send();
ns.Logoff();
return 1;
}
catch (Exception ex2)
{
MessageBox.Show(ex2.Message);
return 0;
}

}
}


How to use this class.........

SendEmails newemail=new SendEmails();
int result = newemail.sendGroupMail("example@mail.com", "This is Subject", "This is Body")
;

Saturday, April 10, 2010

How to connect MySQL Database with C#

MySQL database is a low cost alternative to MS SQL Server database and can be used with web application (ASP.NET) and Windows Application. In this article I will explain the steps to connect to MySQL database from windows Form Application.

Major requirement : First of all you have to download and install MySQL ODBC 3.51 Driver. You can download it from following URL.

http://dev.mysql.com/downloads/connector/odbc/3.51.html


In this example I will implement the basic search functionality using MySQL database table data.

Below picture you can see the Form designing part.



How this works.
1.User enter valid employee ID and click on search button.
2.Then application with connect to the database named “employees” and from relevant table (emp) application will select the Emp Name and Emp Age and those two data will display on relevant text boxes.

Below you can see coding part for this application.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.Odbc;

namespace WindowsFormsApplication5
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)
{

}

private void btnSearch_Click(object sender, EventArgs e)
{
//Connection string for the MySQL Database.
string sConString = "Driver={MySQL ODBC 3.51 Driver};" + "Server=localhost;" + "Database=employees;" + "user id=root;" + "password=SLIIT";

OdbcConnection oConnection = new OdbcConnection(sConString);

string sSQL = "SELECT * FROM emp where eid='" + textBox1.Text + "'";

try
{
oConnection.Open();

OdbcCommand cmd = new OdbcCommand(sSQL, oConnection);

OdbcDataReader myReader;

myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);

myReader.Read();

string name = myReader["ename"].ToString();

string age = myReader["age"].ToString();

textBox2.Text = name;

textBox3.Text = age;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}


}
}
}