Introduction
Web service , which promote software re-usability in distributed systems where applications execute across multiple computers on a network. A web service is a class that allows it methods to called by on other machines via common data formats and protocols, such as XML and HTTP. In .NET, the over-the network method calls are commonly implemented through the Simple Object Access Protocol (SOAP).
Download Word Document with All steps
http://www.4shared.com/file/T95t7ANP/Create_New_Web_Service_Applica.html
Download Web Service Source Code
http://www.4shared.com/file/uXFzwWya/WebServiceExample.html
Download Web Service Client Source Code
http://www.4shared.com/file/VoIl8u1j/WebServiceClient.html
Saturday, August 21, 2010
Friday, July 23, 2010
Socket programming
What is a socket?
A socket is an End – Point of a two-way communication link between two programs running on the network.
A server application normally listens to a specific port waiting for connection request from client. When a connection request arrives from the client, the client and server establish a dedicated connection over which they can communicate. During the connection process, the client assigned a local port number, and binds a socket to it. Client talks to server by writing to socket and get information from the server by reading from it. Similarly, the server gets a new local port number. Server also binds a socket to its local port and communicates with the client by reading from and writing it.
Also client and server must agree on a protocol. They are two type of communication protocol uses for socket programming, they are TCP/IP communication and UDP/IP communication. In this article we use TCP/IP as communication protocol.
More about TCP
TCP is a connection-oriented communication protocol which guarantees that sent packet will arrive at the intended receiver undamaged and in the correct sequence. TCP allows protocols like HTTP to send information across a network as simply and reliably as writing to a file on local machine. If packets of information don’t arrive at the recipient, TCP ensures that the packets are sent again. If the packets arrive out of order, TCP reassemble them in correct order transparently to receiving application. If duplicate packets arrive, TCP discard them.
In C# we need two programs for communicating a socket application.
1. Server Socket Program
A server socket program running on a computer has a socket that bound to port number on the same computer and listening to the client’s incoming requests.
2. Client Socket Program
Client socket program have to know the IP address of the computer that the server socket program resides and the port number assign for listening for client request.
Once the connection is established between server and client, they can communicate through their own socket. Since programs that communicate via TCP process the data they send and receive as stream of bytes, programmers sometimes refer to Socket as “Stream Socket”.
Establishing a Simple TCP Server
Establishing a simple server with TCP and stream sockets require five steps.
1. Create an object class of TcpListener of namespace System.Net.Sockets.
This class represents a TCP stream socket through which a server can listen for requests. Creating new TCPListener , as in
TcpListener server = new TcpListener( ipAddress, port );
2. The second step is the connection process is to call TcpListener’s Start method, which causes the TcpListener object to begin listening for connection requests. The server listens indefinitely for a request, the execution of the server-side application waits until some client attempts to connect with it. The server creates a connection to the client when it receives a connection request. An object of class Socket (namespace Syetem.Net.Socket) manages a connection to client. Method AcceptSocket of class TcpListener accepts a connection request. This method return a Socket object upon connection,
Socket connection = server.AcceptSocket();
When the server receives a request, AcceptSocket calls method Accept of the TcpListener’s underlying Socket to make the connection. This is an example of how networking complexity is hidden from the programmer. You simply place the preceding statement in a server-side program the classes of namespace System.Net.Sockets handle the details of accepting request and establishing connections.
3. The third step establishes the stream used for communication with the client. In this step, we create a NetworkStream object that uses the Socket object representing the connection to perform the actual sending and receiving data.
4. Step four is the processing phase, in which the server and client communicate using the connection established in the third step. In this phase, the client uses BinaryWriter method Write and BinaryReader method readString to perform the appropriate communication.
5. The fifth step is the connection-termination phase. When the client and server have finished communicating , the server calls method Close of the Binaryreader, BinaryWriter ,NetworkStream and Socket to terminate the connection.
Establishing a Simple TCP Client
There are four steps to creating simple TCP client.
1. First, we create an object of class TcpClient (namespace System.Net.Sockets0 to connect to the server. The connection established by calling TcpClient method Connect. One overload version of this method takes two arguments the server’s IP address and its port number,
TcpClient client = new TcpClient();
client.Connect( serverAddress, serverPort );
The serverPort is an int that represents the port number to which the server application is bound to listen for connection requests. The serverAddress can be either and IPAddress instance or a string that specifies the server’s hostname or IP address. Method Connect also has an overload version to which you can pass an IPEndPoint object that represents an IP addresss/port number pair. TcpClient method Connect calls Socket method Connect to establish the connection. If the connection is successful, TCPClient method Connect returns a positive integer otherwise it returns 0.
In step two, the TcpClient uses its GetStream method to get a NetworkStream so that it can write to and read from the server. We then use the NetworkStream object to create a BinaryWriter and a BinaryReader that will be used to send information to and receive information from the server, respectively.
The third step is the processing phase, in which the client and the server communicate. it is very similar to the server process.
After the transmission is complete, step four requires the client to close the connection by calling method Close() on each of BinaryReader, BinaryWriter, NetworkStream and TcpClient. This closes each of the stream and the TcpClient’s socket to terminate the connection with the server.
TcpClient client = new TcpClient();
client.Connect( serverAddress, serverPort );
The serverPort is an int that represents the port number to which the server application is bound to listen for connection requests. The serverAddress can be either and IPAddress instance or a string that specifies the server’s hostname or IP address. Method Connect also has an overload version to which you can pass an IPEndPoint object that represents an IP addresss/port number pair. TcpClient method Connect calls Socket method Connect to establish the connection. If the connection is successful, TCPClient method Connect returns a positive integer otherwise it returns 0.
In step two, the TcpClient uses its GetStream method to get a NetworkStream so that it can write to and read from the server. We then use the NetworkStream object to create a BinaryWriter and a BinaryReader that will be used to send information to and receive information from the server, respectively.
The third step is the processing phase, in which the client and the server communicate. it is very similar to the server process.
After the transmission is complete, step four requires the client to close the connection by calling method Close() on each of BinaryReader, BinaryWriter, NetworkStream and TcpClient. This closes each of the stream and the TcpClient’s socket to terminate the connection with the server.
Wednesday, July 7, 2010
Insert Any File Type to the SQL Server table
Here I used table named doc with 2 columns and data types are varbinary(max), int.
Coding Part
SqlConnection myconn = new SqlConnection(@"Data Source=192.168.2.4;Initial Catalog=pubs;Persist Security Info=True;User ID=vidu;Password=123");
try
{
myconn.Open();
byte[] bytearr = File.ReadAllBytes(textBox1.Text);
int i = 1;
//I have 2 columns in my table ->Column type varbinary(max),int
string query = "INSERT INTO doc values(@file1,@no)";
using(SqlCommand comm=new SqlCommand(query,myconn))
{
comm.Parameters.Add(new SqlParameter("@file1", bytearr));
comm.Parameters.Add(new SqlParameter("@no", i));
comm.ExecuteNonQuery();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
Download Source Code
http://www.4shared.com/file/spPyvhwW/FormInterface.html
Coding Part
SqlConnection myconn = new SqlConnection(@"Data Source=192.168.2.4;Initial Catalog=pubs;Persist Security Info=True;User ID=vidu;Password=123");
try
{
myconn.Open();
byte[] bytearr = File.ReadAllBytes(textBox1.Text);
int i = 1;
//I have 2 columns in my table ->Column type varbinary(max),int
string query = "INSERT INTO doc values(@file1,@no)";
using(SqlCommand comm=new SqlCommand(query,myconn))
{
comm.Parameters.Add(new SqlParameter("@file1", bytearr));
comm.Parameters.Add(new SqlParameter("@no", i));
comm.ExecuteNonQuery();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
Download Source Code
http://www.4shared.com/file/spPyvhwW/FormInterface.html
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
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.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.";
}
}
}
}
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
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";
}
}
}
}
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;
}
}
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;
}
}
}
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");
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);
}
}
}
}
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);
}
}
}
}
Subscribe to:
Posts (Atom)