Saturday, April 25, 2009

Send email from a PHP script

PHPMailer is a powerful email transport class. Sending email using PHPMailer is simple.

PHPMailer features:-


  • Supports emails digitally signed with S/MIME encryption!
  • Supports emails with multiple TOs, CCs, BCCs and REPLY-TOs
  • Works on any platform.
  • Supports Text & HTML emails.
  • Embedded image support.
  • Multipart/alternative emails for mail clients that do not read HTML email.
  • Flexible debugging.
  • Custom mail headers.
  • Redundant SMTP servers.
  • Support for 8bit, base64, binary, and quoted-printable encoding.
  • Word wrap.
  • Multiple fs, string, and binary attachments (those from database, string, etc).
  • SMTP authentication.
  • Tested on multiple SMTP servers: Sendmail, qmail, Postfix, Gmail, Imail, Exchange, etc.
  • Good documentation, many examples included in download.
  • It's swift, small, and simple.
[http://phpmailer.codeworxtech.com]

How to use

Download PHPMailer from http://sourceforge.net/projects/PHPmailer
Extract it into your web directory.
Turn on SSL support.
Use the following code to send email.

Sample code

include("/lib/phpmailer/class.phpmailer.php");
$mail = new PHPMailer(); // Creating PHPMailer object
$body = "Hai hello, this is my first mail using PHPMailer. ";
$mail->IsSMTP();
$mail->SMTPAuth = true;
$mail->Host = "ssl://smtp.gmail.com:465"; // SMTP Server.
/*
Setting gmail as the SMTP Server
*/
$mail->Username = "myphpapp@gmail.com"; // username [Gmail]
$mail->Password = "mypassword
"; // password for myphpapp
$mail->AltBody = "This is the body when user views in plain text format";
$mail->Subject = "Say hello!"; // This is the subject
$mail->From = "myphpapp@gmail.com"; // From email-id
$mail->FromName = "PHP Developer"; // From Name
$mail->MsgHTML($body);
$mail->AddAddress("toaddress@gmail.com","Name"); // To address.
$mail->IsHTML(true);
if(!
$mail->Send()) {
echo
"Mailer Error: " . $mail->ErrorInfo;
}
else {
echo
"Message has been sent";
}
?> 


courtsey: nexabion software cum webdevelopers and webhosting providers kerala

Wednesday, April 22, 2009

Save Image to Sql Server in ASP.net and Retrieve it Using Generic Handler

1. Create a Website Project in visual studio

Add File Upload control.

File Upload control doesn't have an event associated with it to post a file to server, so add button a to the page

2. Create a database in SQLSEVER to store your image for example lets create a table named 'employee' where we store Employee's image with other relevant information.

Employee table contains the following fields:

Employeeid Int,

Employeename Varchar(50),

EmpImg Image. (look here the datatype is image/blob).

3.Add Generic Handler

Generic Handler file is an asp.net file with ashx extension similar to a normal web file with aspx extension. Normal aspx pages is used to handle "light duties" .But the ashx files can handle ‘Heavy duty’ like dynamically loading pictures from database .

Just as aspx files can be compiled on the fly (just-in-time), so can be handlers. Generic handlers have an extension of ashx. They're equivalent to custom handlers written in C Sharp or Visual Basic.NET in that they contain classes that fully implement IHttpHandler. They're convenient in the same way as of aspx files. You simply surf to them and they're compiled automatically.

The following example illustrates the implementation of a "generic handler". Here the name given is GetImage.


Add a "generic" handler to the Web site. Go to the Solution Explorer, right-click on the CustomHandler Web site node and select Add New Item. Select Generic Handler from the templates. Name the handler GetImage.ashx:


Generic Handler Code GetImage.ashx is given below.


<%@ WebHandler Language="C#" Class="GetImage" %>

using System;

using System.Web;

using System.Data.SqlClient;

using System.IO;

public class GetImage : IHttpHandler {

public void ProcessRequest (HttpContext context) {

try

{

string empno;

if (context.Request.QueryString["id"] != null)

empno = context.Request.QueryString["id"].ToString();//Get Employee Id from Query String

else

throw new ArgumentException("No parameter specified");

context.Response.ContentType = "image/jpeg";

Stream strm = GetImageData(empno);

byte[] buffer = new byte[4096];

int byteSeq = strm.Read(buffer, 0, 4096);//Read Image data from Db to byte array

while (byteSeq > 0)

{

context.Response.OutputStream.Write(buffer, 0, byteSeq);

byteSeq = strm.Read(buffer, 0, 4096);

}

}

catch (Exception ex)

{

}

}

public Stream GetImageData(string employeeid)

{

SqlConnection connection = new SqlConnection("Data Source=.;Database=Images;Trusted_Connection=True");//ReplaceitWith Your Conncetion String

connection.Open();

string sql = "SELECT img FROM EmployeePhoto WHERE employeeid = @ID";

SqlCommand cmd = new SqlCommand(sql, connection);

cmd.Parameters.AddWithValue("@ID", employeeid);

object img = cmd.ExecuteScalar();

try

{

return new MemoryStream((byte[])img);

}

catch

{

return null;

}

finally

{

connection.Close();

}

}

public bool IsReusable {

get {

return false;

}

}

}

Add Employees Photo Page(Default.aspx here)

using System;

using System.Data;

using System.Configuration;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Web.UI.HtmlControls;

using System.Data.SqlClient;

public partial class _Default : System.Web.UI.Page

{

protected void Page_Load(object sender, EventArgs e)

{

}

protected void Button1_Click(object sender, EventArgs e)

{

try

{

FileUpload img = (FileUpload)imgUpload;

Byte[] imgByte = null;

if (img.HasFile && img.PostedFile != null)

{

//To create a PostedFile

HttpPostedFile File = imgUpload.PostedFile;

//Create byte Array with file len

imgByte = new Byte[File.ContentLength];

//force the control to load data in array

File.InputStream.Read(imgByte, 0, File.ContentLength);

}

// Using File Stream to read data from file

//SqlConnection connection=new SqlConnection("server=.;uid=sa;pwd=sa;Database=Images");//SQL SErver Authentication

SqlConnection connection = new SqlConnection("Data Source=C.;Database=Images;Trusted_Connection=True");//Windows Authentication

connection.Open();

SqlCommand addImage = new SqlCommand("insert into EmployeePhoto values(@employeeid,@employeename,@img)", connection);

addImage.Parameters.Add("@employeeid", SqlDbType.Int).Value = TextBox1.Text;

addImage.Parameters.Add("@employeename", SqlDbType.VarChar).Value = TextBox2.Text;

addImage.Parameters.Add("@img", SqlDbType.Image).Value=imgByte;//

addImage.ExecuteNonQuery();

connection.Close();

}

catch(Exception ex)

{

Response.Write(ex.Message);

}

}

public void ClearPage()

{

foreach (Control c in form1.Controls)

{

if (c.GetType().ToString() == "System.Web.UI.WebControls.TextBox")

{

((TextBox)c).Text = String.Empty;

}

}

}

}

ViewEmployees Page

using System;

using System.Data;

using System.Configuration;

using System.Collections;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Web.UI.HtmlControls;

using System.Data.SqlClient;

public partial class ViewEmployees : System.Web.UI.Page

{

protected void Page_Load(object sender, EventArgs e)

{

if (!IsPostBack)

{

SqlConnection connection = new SqlConnection("Data Source=.; Database=Images;Trusted_Connection=True");

connection.Open();

DropDownList1.Items.Clear();

DropDownList1.Items.Add("---------Select--------");

SqlCommand getemplyeeids = new SqlCommand("select employeeid,

employeename from EmployeePhoto", connection);

SqlDataReader Read_Name;

Read_Name = getemplyeeids.ExecuteReader();

while (Read_Name.Read())

{

ListItem LI = new ListItem();

LI.Text = Read_Name.GetValue(1).ToString();

LI.Value = Read_Name.GetValue(0).ToString();

DropDownList1.Items.Add(LI);

}

Read_Name.Close();

connection.Close();

}

}

protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)

{

Image1.ImageUrl = "~/GetImage.ashx?id=" + DropDownList1.SelectedItem.Value;//Invokes Generic Handler Implemented in GetImage

}

}


If all have done your coding, run the Project and add some employees,View Employee image by selecting Name from Dropdownlist

Enjoy!!!

Download Sample Project

Convert Object To Byte Array Using JAVA

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

public class ObjectToByte {

public byte[] convert(Object obj) throws IOException {
ObjectOutputStream os = null;

ByteArrayOutputStream byteStream = new ByteArrayOutputStream(5000);
os = new ObjectOutputStream(new BufferedOutputStream(byteStream));
os.flush();
os.writeObject(obj);
os.flush();
byte[] sendBuf = byteStream.toByteArray();
os.close();
return sendBuf;

}
}

Monday, April 20, 2009

Aptna Studio

Download Aptana Studio 1.2.6
Inlcudes Aptana Cloud & Jaxer. Add support for PHP, Ruby, Rails, Python, iPhone and Adobe AIR after installation.

Since Aptana Studio is based on Eclipse, I can take advantage of the vast number of Eclipse plugins like Mylyn, the Bazaar plugin, GotoFile, QuantumDB, SQL Explorer, etc...
Download

Ext JS 2.0

Ext JS is a cross-browser JavaScript library for building rich internet applications.

  • High performance, customizable UI widgets
  • Well designed, documented and extensible Component model
  • Commercial and Open Source licenses available
http://extjs.com/

Saturday, April 18, 2009

Play Audio File using java

import java.io.File;
import java.io.IOException;

import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;

public class AudioPlayer extends Thread {

private static final int EXTERNAL_BUFFER_SIZE = 128000;
private SourceDataLine line = null;
private String strFilename;
boolean play = true;

public AudioPlayer(String strFilename) {
this.strFilename = strFilename;
}

public void startPlaying() {
play = true;
start();
}

public void stopPlaying() {
play = false;
line.drain();
line.close();

}

public void run() {
File soundFile = new File(strFilename);
AudioInputStream audioInputStream = null;
try {
audioInputStream = AudioSystem.getAudioInputStream(soundFile);
} catch (Exception e) {

e.printStackTrace();
System.exit(1);
}
AudioFormat audioFormat = audioInputStream.getFormat();

DataLine.Info info = new DataLine.Info(SourceDataLine.class,
audioFormat);
try {
line = (SourceDataLine) AudioSystem.getLine(info);


line.open(audioFormat);
} catch (LineUnavailableException e) {
e.printStackTrace();
System.exit(1);
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
line.start();
int nBytesRead = 0;
byte[] abData = new byte[EXTERNAL_BUFFER_SIZE];
while (nBytesRead != -1 && play) {
try {
nBytesRead = audioInputStream.read(abData, 0, abData.length);
} catch (IOException e) {
e.printStackTrace();
}
if (nBytesRead >= 0) {
int nBytesWritten = line.write(abData, 0, nBytesRead);
}
}
line.drain();
line.close();
}
}

Wednesday, April 15, 2009

Creating Gantt Chart in ASP.NET

GanttChart
Sample GanttChart


Gantt Chart in asp.net

A Gantt chart(wiki link) is a type of bar chart that illustrates a project schedule. Gantt charts illustrate the starting and finishing dates of terminal elements and summary elements of a project. Terminal elements and summary elements comprise the work breakdown structure of the project. Some Gantt charts also show the dependency (i.e, precedence network) relationships between activities.

We here use jsgantt(Its a free JavaScript library for creating Gantt chart) to create Gantt chart having following features .It’s implemented using JavaScript, HTML, CSS and thus very fast and flexible. Since it is pure HTML/JavaScript you can integrate this with any server side scripting language.

URL: http://www.jsgantt.com

Basic Features

* Tasks & Collapsible Task Groups

* Multiple Dependencies

* Task Completion

* Task Color

* Milestones

* Resources

* No images needed

* Free [released under BSD license]

Advanced Features

* Dynamic Loading of Tasks

* Dynamic change of format (day/week/month)

* Load Gantt from XML file

Disadvantage

Currently only one Gantt chart is allowed per page.

You can download jsGantt from http://code.google.com/p/jsgantt/

There are many ways to integrate gantt chart programmatically, here we explain one of the method which using external data exchange between asp.net and JavaScript using XML file that are generated at run time using values from the SQL Server Database.


Sample xml file Structure that used by jsgantt. Is as follows

<project>

<task>

<pID>10</pID>

<pName>WCF Changes</pName>

<pStart></pStart>

<pEnd></pEnd>

<pColor>0000ff</pColor>

<pLink></pLink>

<pMile>0</pMile>

<pRes></pRes>

<pComp>0</pComp>

<pGroup>1</pGroup>

<pParent>0</pParent>

<pOpen>1</pOpen>

<pDepend />

</task>

<task>

<pID>20</pID>

<pName>Move to WCF from remoting</pName>

<pStart>8/11/2008</pStart>

<pEnd>8/15/2008</pEnd>

<pColor>0000ff</pColor>

<pLink></pLink>

<pMile>0</pMile>

<pRes>Rich</pRes>

<pComp>10</pComp>

<pGroup>0</pGroup>

<pParent>10</pParent>

<pOpen>1</pOpen>

<pDepend></pDepend>

</task>

</project>

XML tags in our External XML file have following tags and values. Here we describe the purpose of each tag:

pID: (required) is a unique ID used to identify each row for parent functions and for setting dom id for hiding/showing

pName: (required) is the task Label

pStart: (required) the task start date, can enter empty date ('') for groups

pEnd: (required) the task end date, can enter empty date ('') for groups

pColor: (required) the html color for this task; e.g. '00ff00'

pLink: (optional) any http link navigated to when task bar is clicked.

pMile:(optional) represent a milestone

pRes: (optional) resource name

pComp: (required) completion percent

pGroup: (optional) indicates whether this is a group(parent) - 0=NOT Parent; 1=IS Parent

pParent: (required) identifies a parent pID, this causes this task to be a child of identified task

pOpen: can be initially set to close folder when chart is first drawn

pDepend: optional list of id's this task is dependent on ... line drawn from dependent to this item

pCaption: optional caption that will be added after task bar if Caption Type set to "Caption"

Creating Database Schema in Sql Server

Create database named Projects in SQL Server

Tables

project

Column Name --------------------------------Data Type

projectid-----------------------------------------Int(PK)

projectname-------------------------------------Varchar(50)

startdate-----------------------------------------Datetime

enddate------------------------------------------Datetime

tasks

Column Name---------------------------------- Data Type

taskid-------------------------------------------Int((PK)

projectid----------------------------------------Int(FK)

taskname---------------------------------------Varchar(50)

startdate----------------------------------------Datetime

enddate---------------------------------------- Datetime

percentagecompleted---------------------------Int

parenttask--------------------------------------Int


Sample data

project

projectid----------------------name------------------ startdate-------------- enddate

1---------------------------Search Engine-----------04/03/2009 -----------04/30/2009

Task

projectid name startdate enddate percentagecompleted parenttask

1--------------Analysis----- 4/3/2009----- 4/11/2009-----100 -------------------- 0

2--------------Design-------4/12/2009----4/15/2009------100---------------------1

3--------------Code--------4/16/2009----4/20/2009-------25----------------------2

4--------------Test ---------4/21/2009--- 4/27/2009--------0 ----------------------3

5------------- Test2---------4/28/2009----4/30/2009------- 0 ----------------------4

*Tasks Date is in mm/dd/yyyy format

Using Gantt Chart in your ASP.NET Application

Create a website project in ASP.NET in Visual Studio.

Add an XML file named Tasks.xml to project

UnCompress Copy paste jsgantt directory you downloaded from jsGantt Website http://code.google.com/p/jsgantt/ to your project

Add dropdownlist control to Default.aspx to fill projects and to select name it cmbproject

Edit .aspx page’s HTML do following step

1. Include JSGantt CSS and Javascript

Add this just before the </head> tag

<link rel="stylesheet" type="text/css" href="jsgantt.css" />
<script language="javascript" src="jsgantt.js"></script>

2. Create a div element to hold the Gantt chart

In your html body

<div style="position:relative" class="gantt" id="GanttChartDIV"></div>

  1. Add This script to html body

<script>

var g = new JSGantt.GanttChart('g',document.getElementById('GanttChartDIV'), 'day');//Here intantiating chart control

g.setShowRes(1); // Show/Hide Responsible (0/1)

g.setShowDur(0); // Show/Hide Duration (0/1)

g.setShowComp(1); // Show/Hide % Complete(0/1)

//g.setCaptionType('Resource'); // Set to Show Caption (None,Caption,Resource,Duration,Complete)

if( g ) {

// You can also use the XML file parser

JSGantt.parseXML('Tasks.xml',g)//Read data from Tasks.xml

g.Draw();

g.DrawDependencies();

}

else

{

alert("not defined");

}

</script>

ASP.NET CODE

Default.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >

<head runat="server">

<title>Untitled Page</title>

<link rel="stylesheet" type="text/css" href="jsgantt/jsgantt.css"/>

<script language="javascript" src="jsgantt/jsgantt.js"></script>

</head>

<body>

<form id="form1" runat="server">

<div>

<table style="width: 384px">

<tr>

<td style="width: 185px">

</td>

<td style="width: 167px">

</td>

<td style="width: 65px">

</td>

</tr>

<tr>

<td style="width: 185px; height: 24px;">

</td>

<td style="width: 167px; height: 24px;">

<asp:DropDownList ID="cmbproject" runat="server" AutoPostBack="True" OnSelectedIndexChanged="cmbproject_SelectedIndexChanged"

Width="165px">

</asp:DropDownList></td>

<td style="width: 65px; height: 24px;">

</td>

</tr>

<tr>

<td style="width: 185px">

</td>

<td style="width: 167px">

</td>

<td style="width: 65px">

</td>

</tr>

</table>

</div>

<div style="position:relative" class="gantt" id="GanttChartDIV">

</div>

<script>

var g = new JSGantt.GanttChart('g',document.getElementById('GanttChartDIV'), 'day');

g.setShowRes(1); // Show/Hide Responsible (0/1)

g.setShowDur(0); // Show/Hide Duration (0/1)

g.setShowComp(1); // Show/Hide % Complete(0/1)

//g.setCaptionType('Resource'); // Set to Show Caption (None,Caption,Resource,Duration,Complete)

if( g ) {

// You can also use the XML file parser

JSGantt.parseXML('Tasks.xml',g)//Read data from Tasks.xml

g.Draw();

g.DrawDependencies();

}

else

{

alert("not defined");

}

</script>

</form>

</body>

</html>

Default.aspx.cs

using System;

using System.Data;

using System.Configuration;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Web.UI.HtmlControls;

using System.Data.SqlClient;

using System.Xml;

public partial class _Default : System.Web.UI.Page

{

protected void Page_Load(object sender, EventArgs e)

{

if (!IsPostBack)

{

//Fill dropdownlist with all projects names

SqlConnection mcon = new SqlConnection("Data Source=CYBERMIND\\SQLEXPRESS;Database=Projects;Trusted_Connection=True"); //Cahnge Connection string of your SQL Server Here

mcon.Open();

cmbproject.Items.Clear();

SqlCommand GetProjectName = new SqlCommand("select projectid,name from project", mcon);

SqlDataReader ReadPrjName;

ReadPrjName = GetProjectName.ExecuteReader();

cmbproject.Items.Add("--------Select-----");

while (ReadPrjName.Read())

{

ListItem LIT = new ListItem();

LIT.Text = ReadPrjName.GetValue(1).ToString();//Add Project name as dropdownlists Text

LIT.Value = ReadPrjName.GetValue(0).ToString();//Add Projectid as dropdownlists Value

cmbproject.Items.Add(LIT);

}

ReadPrjName.Close();

mcon.Close();

}

}

protected void cmbproject_SelectedIndexChanged(object sender, EventArgs e)

{

string projectid = "";

SqlConnection mcon = new SqlConnection("Data Source=CYBERMIND\\SQLEXPRESS;Database=Projects;Trusted_Connection=True");

mcon.Open();

//Creating data of ou Task.xml programatically

XmlTextWriter xwriter = new XmlTextWriter(Server.MapPath("Tasks.xml"), null); //Creating a Xml Text writer

xwriter.Formatting = Formatting.Indented;// Setting indendation in xml file

xwriter.Indentation = 4;// Indentation space is 4 here

SqlCommand mmcmd = new SqlCommand("select projectid,name,convert(varchar(10),startdate,101),convert(varchar(10),enddate,101) from project where projectid =" + cmbproject.SelectedItem.Value + "", mcon);

SqlDataReader projectReader = mmcmd.ExecuteReader();

xwriter.WriteStartElement("project");

while (projectReader.Read())

{

projectid = projectReader.GetValue(0).ToString();

xwriter.WriteStartElement("task");

xwriter.WriteStartElement("pID"); // WriteStartElement writes a tag

xwriter.WriteString(projectReader.GetValue(0).ToString()); // WriteString writes strin to xml file

xwriter.WriteEndElement();// WriteStartElement writes a end tag

xwriter.WriteStartElement("pName");

xwriter.WriteString(projectReader.GetValue(1).ToString());

xwriter.WriteEndElement();

xwriter.WriteStartElement("pStart");

xwriter.WriteString(projectReader.GetValue(2).ToString());

xwriter.WriteEndElement();

xwriter.WriteStartElement("pEnd");

xwriter.WriteString(projectReader.GetValue(3).ToString());

xwriter.WriteEndElement();

xwriter.WriteStartElement("pParent");

xwriter.WriteString("0");

xwriter.WriteEndElement();

xwriter.WriteEndElement();

}

//End of Project Details Read and Write to XML

mcon.Close();

SqlConnection mcon2 = new SqlConnection("Data Source=CYBERMIND\\SQLEXPRESS;Database=Projects;Trusted_Connection=True");

mcon2.Open();

string str = "select taskid,taskname,convert(varchar(10),startdate,101),convert(varchar(10),enddate,101), percentagecompleted from Task where projectid =" + cmbproject.SelectedItem.Value + " ";

SqlCommand mcmd = new SqlCommand(str, mcon2);

SqlDataReader reader = mcmd.ExecuteReader();

//Start to read and write Tasks to Xml file

while (reader.Read())

{

xwriter.WriteStartElement("task");

xwriter.WriteStartElement("pID");

xwriter.WriteString(reader.GetValue(0).ToString());

xwriter.WriteEndElement();

xwriter.WriteStartElement("pName");

xwriter.WriteString(reader.GetValue(1).ToString());

xwriter.WriteEndElement();

xwriter.WriteStartElement("pStart");

xwriter.WriteString(reader.GetValue(2).ToString());

xwriter.WriteEndElement();

xwriter.WriteStartElement("pEnd");

xwriter.WriteString(reader.GetValue(3).ToString());

xwriter.WriteEndElement();

xwriter.WriteStartElement("pColor");// Sets chart task bar color to blue

xwriter.WriteString("ff00ff");

xwriter.WriteEndElement();

xwriter.WriteStartElement("pComp");

xwriter.WriteString(reader.GetValue(4).ToString());

xwriter.WriteEndElement();

xwriter.WriteStartElement("pParent");

xwriter.WriteString(projectid);

xwriter.WriteEndElement();

xwriter.WriteEndElement();

}

xwriter.WriteEndElement();

//Start to read and write Tasks to Xml file

xwriter.Flush();

xwriter.Close(); //Close XML File

mcon2.Close();

}

}

Download Complete Project Code

LinkWithin

Related Posts with Thumbnails