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.Collections;
using System.Net.Mail;
using Lesnikowski.Client;
using Lesnikowski.Client.IMAP;
using Lesnikowski.Mail;
using Lesnikowski.Mail.Fluent;
using Lesnikowski.Mail.Headers;
using Lesnikowski.Mail.Headers.Constants;
using System.IO;
using System.Drawing.Imaging;
using System.Diagnostics;
using System.Drawing.Drawing2D;
using TallComponents.PDF.Rasterizer;
using TallComponents.PDF.Rasterizer.Configuration;
using System.Text.RegularExpressions;
namespace AHA_Fax_Downloader
{
public partial class Attach_Download : Form
{
public static int counter = 0;
Document document = null;
public Attach_Download()
{
InitializeComponent();
}
List<long> uids;
public void getmailbox()
{
try
{
using (Imap imap = new Imap())
{
//imap.Connect("smtp.gmail.com");
//imap.Login("software@gmail.com", "A99");
imap.Connect("smtp.gmail.com");
imap.Login("ahafax@gmail.com", "a6789");
imap.SelectInbox();
uids = imap.SearchFlag(Flag.All);
if (uids.Count < 1)
{
txtNoFax.Text = "0";
MessageBox.Show("No Faxes Available");
}
else
{
txtNoFax.Text = uids.Count.ToString();
int i = 0;
dgvmails.Rows.Clear();
foreach (long uid in uids)
{
//counter = counter + 1;
//if (counter == 11)
//{
// break;
//}
dgvmails.Rows.Add();
//for (int i = 0; i < dgvmails.Rows.Count; i++)
//{
string eml = imap.GetMessageByUID(uid);
IMail email = new MailBuilder()
.CreateFromEml(eml);
dgvmails.Rows[i].Cells[1].Value = email.Sender.ToString();
dgvmails.Rows[i].Cells[2].Value = email.Subject.ToString();
dgvmails.Rows[i].Cells[3].Value = String.Format("{0:MM/dd/yyyy}", email.Date);
dgvmails.Rows[i].Cells[4].Value = uid.ToString();
i++;
//}
}
gridrowcolor(dgvmails, dgvmails.Rows.Count);
}
}
}
catch (Exception err)
{
}
}
private void Attach_Download_Load(object sender, EventArgs e)
{
lbluser.Text = "Welcome :" + " " + LoginForm.user.ToString();
try
{
lbldate.Text = String.Format("{0:dd-MMMM-yyyy}", System.DateTime.Now);// System.DateTime.Now.ToShortDateString();
Directory.Delete(@"C:\TempDownloads", true);
}
catch (Exception err)
{
}
}
string currentdt = String.Format("{0:dd-MM-yyyy}", System.DateTime.Now);
public void createPatientList()
{
string dirStr2 = "c:/PatientList";
string str = "c:/PatientList/" + currentdt.ToString();
if (Directory.Exists(dirStr2))
{
}
else
{
Directory.CreateDirectory(dirStr2);
}
if (Directory.Exists(str))
{
}
else
{
Directory.CreateDirectory(str);
}
string str1 = "c:/TempDownloads/ImageFiles";
if (Directory.Exists(str1))
{
}
else
{
Directory.CreateDirectory(str1);
}
string str2 = "c:/TempDownloads/TempFiles";
if (Directory.Exists(str2))
{
}
else
{
Directory.CreateDirectory(str2);
}
}
public static string Extracttext(string Url)
{
if (Url.Contains(@"Patient Name: "))
{
Url = Url.Split(new string[] { "Patient Name: " }, 2, StringSplitOptions.None)[1];
}
else if (Url.Contains(@"Pt. Name: "))
{
Url = Url.Split(new string[] { "Pt. Name: " }, 2, StringSplitOptions.None)[1];
}
else if (Url.Contains(@"PATIENT NAME: "))
{
Url = Url.Split(new string[] { "PATIENT NAME: " }, 2, StringSplitOptions.None)[1];
}
else if (Url.Contains(@"PATIENT: "))
{
Url = Url.Split(new string[] { "PATIENT: " }, 2, StringSplitOptions.None)[1];
}
else
{
Url = "";
}
return Url.Split('\r')[0];
}
private void btnsave_Click(object sender, EventArgs e)
{
}
int getDPI()
{
return 96;
throw new Exception("Unsupported DPI selected.");
}
TiffCompression getCompression()
{
return TiffCompression.None;
throw new Exception("Unsupported Compression selected.");
}
private void Attach_Download_FormClosing(object sender, FormClosingEventArgs e)
{
Application.Exit();
}
private void btnload_Click(object sender, EventArgs e)
{
pb.Maximum=20;
pb.Value = 5;
// lblmessage.Visible = true;
// lblmessage.Text = "Please Wait while loading list of faxes";
getmailbox();
// lblmessage.Visible = false;
pb.Value = 0;
}
private void btnSaveAll_Click(object sender, EventArgs e)
{
pb.Maximum = 20;
pb.Value = 5;
// lblmessage.Text = "Please wait while Downloading Faxes";
try
{
if (MessageBox.Show("Are you sure to Download All Faxes", "AHA Fax Downloader", MessageBoxButtons.YesNo, MessageBoxIcon.Question)==System.Windows.Forms.DialogResult.Yes)
{
//Please purchase Mail.dll license at http://www.lesnikowski.com/mail/
string dirStr = "c:/Downloads";
string currentdt = String.Format("{0:dd-MM-yyyy}", System.DateTime.Now);
string str = "c:/Downloads/" + currentdt.ToString();
string dirStr2 = "c:/TempDownloads/TempFiles";
if (Directory.Exists(dirStr))
{
}
else
{
Directory.CreateDirectory(dirStr);
}
if (Directory.Exists(str))
{
}
else
{
Directory.CreateDirectory(str);
}
if (Directory.Exists(str))
{
using (Imap imap = new Imap())
{
imap.Connect("smtp.gmail.com");
//imap.Login("software@gmail.com", "A99");
imap.Login("ahafax@gmail.com", "ah@99");
imap.SelectInbox();
List<long> uids = imap.SearchFlag(Flag.All);
if (uids.Count < 1)
{
MessageBox.Show("MailBox is empty");
}
else
{
foreach (long uid in uids)
{
counter = counter + 1;
if (counter == 11)
{
break;
}
string eml = imap.GetMessageByUID(uid);
IMail email = new MailBuilder().CreateFromEml(eml);
// save all attachments to disk
email.Attachments.ForEach(mime => mime.Save(str + "/" + mime.SafeFileName));
createPatientList();
email.Attachments.ForEach(mime => mime.Save(dirStr2 + "/" + +uid + ".pdf"));
//Convert pdf to .tiff
string path = @"c:\TempDownloads\TempFiles\" + uid + ".pdf";//+ txtPatientNm.Text + "-" + String.Format("{0:MM-dd-yyyy}", dateTimePicker1.Text.ToString()) + ".pdf";
using (FileStream file = new FileStream(path, FileMode.Open, FileAccess.Read))
{
document = new Document(file);
}
ConvertToTiffOptions tiffOptions = new ConvertToTiffOptions(getDPI(), getCompression());
string tiffile = @"c:\TempDownloads\ImageFiles\" + uid + ".tiff";//Image Files\" + txtPatientNm.Text + "-" + String.Format("{0:MM-dd-yyyy}", dateTimePicker1.Text.ToString()) + ".tiff";
using (FileStream file = new FileStream(tiffile, FileMode.Create, FileAccess.Write))
{
document.ConvertToTiff(file, tiffOptions);
file.Close();
}
//OCR(get Patient Name)
try
{
//CheckFileType(@"c:\TempDownloads\ImageFiles\");
//******************************************
string fileExtension = ".tiff";
//get file name without extenstion
string fileName = tiffile.Replace(fileExtension, string.Empty);
//Check for JPG File Format
if (fileExtension == ".tiff" || fileExtension == ".TIFF") // or // ImageFormat.Jpeg.ToString()
{
try
{
//OCR Operations ...
MODI.Document md = new MODI.Document();
md.Create(Convert.ToString(tiffile));
md.OCR(MODI.MiLANGUAGES.miLANG_ENGLISH, true, true);
string myText = "";
for (int i = 0; i < md.Images.Count; i++)
{
MODI.Image image = (MODI.Image)md.Images[i];
myText = myText + " " + image.Layout.Text.ToString();
}
myText = myText.Replace("'", "''").ToString();
//********************
txtPatientNm.Text = Extracttext(myText).ToString();
}
catch (Exception)
{
//MessageBox.Show("This Image hasn't a text or has a problem",
//"OCR Notifications",
//MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
//*************************************
//***************************************
string ln = "";
string fn = "";
// File.Delete(@"C:\PatientList2\ImageFiles\temp.tiff");
string Message = txtPatientNm.Text.ToString();
string[] Record = Regex.Split(Message.Trim(), " ");
if (Record.Length > 1)
{
ln = Record[1].ToString();
fn = Record[0].ToString();
}
string strPList = "c:/PatientList/"+ currentdt +'/';
if (ln != "" && fn != "")
{
if (File.Exists(strPList + "/" + fn + "-" + ln + ".pdf"))
{
email.Attachments.ForEach(mime => mime.Save(strPList + "/" + fn + "-" + ln + "(" + uid + ")" + ".pdf"));
}
else
{
email.Attachments.ForEach(mime => mime.Save(strPList + "/" + fn + "-" + ln + ".pdf"));
}
}
else
{
email.Attachments.ForEach(mime => mime.Save(strPList + "/" + mime.SafeFileName));
}
}
catch (Exception err)
{
string strPList = "c:/PatientList/" + currentdt + '/';
email.Attachments.ForEach(mime => mime.Save(strPList + "/" + mime.SafeFileName));
}
//Delete mail message
//imap.DeleteMessageByUID(uid);
//imap.CreateFolder("Old Mails");
imap.MoveByUID(uid, "Old Mails");
}
imap.Close();
// lblmessage.Visible = true;
MessageBox.Show("Faxes downloaded successfully....");
dgvmails.Rows.Clear();
txtPatientNm.Text = "";
txtNoFax.Text = "";
// lblmessage.Text = "";
this.Refresh();
}
}
}
}
else
{
}
}
catch (Exception err)
{
MessageBox.Show("Connection error! Please try after some time", "AHA Fax Downloader", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
pb.Value = 0;
}
private void btnDownloadSelected_Click(object sender, EventArgs e)
{
pb.Maximum = 20;
pb.Value = 5;
int flag = 0;
foreach (DataGridViewRow row in dgvmails.Rows)
//for (int i = 0; i <= dgvmails.Rows.Count - 1; i++)
{
if ((Boolean)((DataGridViewCheckBoxCell)row.Cells[0]).FormattedValue)
// if ((bool)dgvmails.Rows[i].Cells[0].Value = CheckState.Checked)
{
flag = 1;
}
}
if (flag == 0)
{
MessageBox.Show("Please select the record", "AHA Fax Downloader", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
// lblmessage.Text = "Please wait while Downloading Faxes";
try
{
if (MessageBox.Show("Are you sure to Download Selected Faxes", "AHA Fax Downloader", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
{
//Please purchase Mail.dll license at http://www.lesnikowski.com/mail/
string dirStr = "c:/Downloads";
string currentdt = String.Format("{0:dd-MM-yyyy}", System.DateTime.Now);
string str = "c:/Downloads/" + currentdt.ToString();
string dirStr2 = "c:/TempDownloads/TempFiles";
if (Directory.Exists(dirStr))
{
}
else
{
Directory.CreateDirectory(dirStr);
}
if (Directory.Exists(str))
{
}
else
{
Directory.CreateDirectory(str);
}
if (Directory.Exists(str))
{
using (Imap imap = new Imap())
{
imap.Connect("smtp.gmail.com");
//imap.Login("software@gmailp.com", "A99");
imap.Login("ahafax@gmail.com", "a999");
imap.SelectInbox();
List<long> uids = imap.SearchFlag(Flag.All);
if (uids.Count < 1)
{
MessageBox.Show("MailBox is empty");
}
else
{
for (int l = 0; l < dgvmails.Rows.Count; l++)
//foreach (long uid in uids)
//if ((Boolean)((DataGridViewCheckBoxCell)row.Cells[0]).FormattedValue)
{
if ((Boolean)dgvmails.Rows[l].Cells[0].FormattedValue)
{
long uid = Convert.ToInt64(dgvmails.Rows[l].Cells[4].Value);
string eml = imap.GetMessageByUID(uid);
IMail email = new MailBuilder().CreateFromEml(eml);
// save all attachments to disk
email.Attachments.ForEach(mime => mime.Save(str + "/" + mime.SafeFileName));
createPatientList();
email.Attachments.ForEach(mime => mime.Save(dirStr2 + "/" + +uid + ".pdf"));
//Convert pdf to .tiff
string path = @"c:\TempDownloads\TempFiles\" + uid + ".pdf";//+ txtPatientNm.Text + "-" + String.Format("{0:MM-dd-yyyy}", dateTimePicker1.Text.ToString()) + ".pdf";
using (FileStream file = new FileStream(path, FileMode.Open, FileAccess.Read))
{
document = new Document(file);
}
ConvertToTiffOptions tiffOptions = new ConvertToTiffOptions(getDPI(), getCompression());
string tiffile = @"c:\TempDownloads\ImageFiles\" + uid + ".tiff";//Image Files\" + txtPatientNm.Text + "-" + String.Format("{0:MM-dd-yyyy}", dateTimePicker1.Text.ToString()) + ".tiff";
using (FileStream file = new FileStream(tiffile, FileMode.Create, FileAccess.Write))
{
document.ConvertToTiff(file, tiffOptions);
file.Close();
}
//OCR(get Patient Name)
try
{
//CheckFileType(@"c:\TempDownloads\ImageFiles\");
//******************************************
string fileExtension = ".tiff";
//get file name without extenstion
string fileName = tiffile.Replace(fileExtension, string.Empty);
//Check for JPG File Format
if (fileExtension == ".tiff" || fileExtension == ".TIFF") // or // ImageFormat.Jpeg.ToString()
{
try
{
//OCR Operations ...
MODI.Document md = new MODI.Document();
md.Create(Convert.ToString(tiffile));
md.OCR(MODI.MiLANGUAGES.miLANG_ENGLISH, true, true);
string myText = "";
for (int i = 0; i < md.Images.Count; i++)
{
MODI.Image image = (MODI.Image)md.Images[i];
myText = myText + " " + image.Layout.Text.ToString();
}
myText = myText.Replace("'", "''").ToString();
//********************
txtPatientNm.Text = Extracttext(myText).ToString();
}
catch (Exception)
{
//MessageBox.Show("This Image hasn't a text or has a problem",
//"OCR Notifications",
//MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
//*************************************
//***************************************
string ln = "";
string fn = "";
// File.Delete(@"C:\PatientList2\ImageFiles\temp.tiff");
string Message = txtPatientNm.Text.ToString();
string[] Record = Regex.Split(Message.Trim(), " ");
if (Record.Length > 1)
{
ln = Record[1].ToString();
fn = Record[0].ToString();
}
string strPList = "c:/PatientList/" + currentdt + '/';
if (ln != "" && fn != "")
{
if (File.Exists(strPList + "/" + fn + "-" + ln + ".pdf"))
{
email.Attachments.ForEach(mime => mime.Save(strPList + "/" + fn + "-" + ln + "(" + uid + ")" + ".pdf"));
}
else
{
email.Attachments.ForEach(mime => mime.Save(strPList + "/" + fn + "-" + ln + ".pdf"));
}
}
else
{
email.Attachments.ForEach(mime => mime.Save(strPList + "/" + mime.SafeFileName));
}
}
catch (Exception err)
{
string strPList = "c:/PatientList/" + currentdt + '/';
email.Attachments.ForEach(mime => mime.Save(strPList + "/" + mime.SafeFileName));
}
//Delete mail message
//imap.DeleteMessageByUID(uid);
//imap.CreateFolder("Old Mails");
imap.MoveByUID(uid, "Old Mails");
}
}
imap.Close();
// lblmessage.Visible = true;
MessageBox.Show("Faxes downloaded successfully....");
dgvmails.Rows.Clear();
getmailbox();
txtPatientNm.Text = "";
txtNoFax.Text = "";
this.Refresh();
}
}
}
}
else
{
}
}
catch (Exception err)
{
//MessageBox.Show("Connection error! Please try after some time", "AHA Fax Downloader", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
pb.Value = 0;
}
private void btnLogout_Click(object sender, EventArgs e)
{
this.Hide();
Application.Exit();
}
private void btnDel_Click(object sender, EventArgs e)
{
if (MessageBox.Show("Are you sure to Delete Selected Faxes", "AHA Fax Downloader", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
{
using (Imap imap = new Imap())
{
imap.Connect("smtp.gmail.com");
//imap.Login("software@gmail.com", "A99");
imap.Login("ahafax@gmail.com", "a89");
imap.SelectInbox();
List<long> uids = imap.SearchFlag(Flag.All);
if (uids.Count < 1)
{
MessageBox.Show("MailBox is empty");
}
else
{
for (int l = 1; l < dgvmails.Rows.Count; l++)
{
if ((Boolean)dgvmails.Rows[l].Cells[0].FormattedValue)
{
long uid = Convert.ToInt64(dgvmails.Rows[l].Cells[4].Value);
string eml = imap.GetMessageByUID(uid);
IMail email = new MailBuilder().CreateFromEml(eml);
MessageBox.Show(uid.ToString());
//Delete mail message
imap.DeleteMessageByUID(uid);
}
}
imap.Close();
// lblmessage.Visible = true;
MessageBox.Show("Selected Faxes deleted successfully....");
getmailbox();
}
}
}
else
{
}
}
private void btnLogout_Click_1(object sender, EventArgs e)
{
//LoginForm lf = new LoginForm();
//lf.ShowDialog();
this.Hide();
Application.Exit();
}
public void gridrowcolor(DataGridView gridname, int count)
{
for (int i = 0; i <= count - 1; i++)
{
if (i % 2 == 0)
{
gridname.Rows[i].DefaultCellStyle.BackColor = Color.White;
}
else
{
gridname.Rows[i].DefaultCellStyle.BackColor = Color.LightSteelBlue;
}
}
}
}
}
Updated 8-Oct-12 22:32pm
v2