ClosedXML can't delete file after saving Workbook "process in use" - runtime-error

So here's the code:
string filename = #"c:\test.xlsx";
using (XLWorkbook wb = CreateWorkbookInformation())
{
wb.SaveAs(filename);
Email.EmailAsAttachment(filename);
}
File.Delete(filename);
It creates the Workbook information just fine, it saves the file fine, it emails the file fine as an attachment... However, when I try to delete file (after the using statement), it states the "process is in use". There shouldn't be anything keeping the file open?!? What process am I missing that I should close in order to delete the file?

Ahh, nevermind, had nothing to do with ClosedXML, had everything to do with attaching the file to the email and not using a proper usingstatement for the attachment. So the attachment process was keeping the file open.

Thank you so much for posting this answer!!!
I went crazy trying to understand what's my problem!
I did as you suggested and used the proper using statement:
using (MailMessage mail = new MailMessage(senderAdress, emailAdress))
{
SmtpClient client = new SmtpClient();
client.Port = 25;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Host = ConfigurationManager.AppSettings["SMTPHostName"];
if (string.IsNullOrWhiteSpace(client.Host))
{
errorMsg = "ConfigurationManager.AppSettings[\"SMTPHostName\"] not found";
return false;
}
mail.Subject = subject;
mail.IsBodyHtml = isBodyHtml;
mail.Body = body;
if (!string.IsNullOrWhiteSpace(attachmentFullPath))
{
if (File.Exists(attachmentFullPath))
{
System.Net.Mime.ContentType contentType = new System.Net.Mime.ContentType();
contentType.MediaType = System.Net.Mime.MediaTypeNames.Application.Octet;
contentType.Name = Path.GetFileName(attachmentFullPath);
mail.Attachments.Add(new Attachment(attachmentFullPath, contentType));
}
else
{
errorMsg = "Attachment File Doesn't Exist: " + attachmentFullPath;
return false;
}
}
client.Send(mail);
}

Related

How to use Windows task Scheduler in ASP.NET

I am trying to use ASP.NET in Window Task Scheduler. I want to send the email on specific time.
But ASP.NET is not run as an EXE, it has a dynamic ip address.
I have no idea to use Window Task Scheduler in ASP.NET.
Can you give me any solutions for it?
void SendEmail()
{
//get the data from database
DataTable data = GetData();
DataTable email_data = GetEmailData();
//set DataTable Name of Excel Sheet
data.TableName = "NSOList";
//Create a New Workook
using (XLWorkbook wb = new XLWorkbook())
{
//Add the DataTable as Excel Workhseet
wb.Worksheets.Add(data);
using (MemoryStream memoryStream = new MemoryStream())
{
//Save the Excel Workbook to MemoryStream
wb.SaveAs(memoryStream);
//Convert MemoryStream to Byte array
byte[] bytes = memoryStream.ToArray();
memoryStream.Close();
//body with embedded image
AlternateView body = AlternateView.CreateAlternateViewFromString
("Hi <br><br> <img src=cid:example>", null, "text/html");
//create the LinkedResource (embedded image)
LinkedResource image = new LinkedResource("c:\\example.png");
image.ContentId = "example";
//add the LinkedResource to the appropriate view
body.LinkedResources.Add(image);
String from = "abcd#abcd.net";
//bring Email data
for (int i = 0; i < email_data.Rows.Count; i++)
{
String to = email_data.Rows[i][0].ToString();
using (MailMessage mm = new MailMessage(from, to))
{
SmtpClient smtp = new SmtpClient();
mm.Subject = "List";
mm.AlternateViews.Add(body);
mm.Attachments.Add(new Attachment(new MemoryStream(bytes), "NSOList.xlsx"));
mm.IsBodyHtml = true;
smtp.Host = "smtp.gmail.com";
smtp.EnableSsl = true;
System.Net.NetworkCredential credentials = new System.Net.NetworkCredential();
credentials.UserName = "abcd#gmail.com";
credentials.Password = "abcd";
smtp.UseDefaultCredentials = true;
smtp.Credentials = credentials;
smtp.Port = 587;
smtp.Send(mm);
}
}
}
}
}
You should use a Task Scheduler like Quartz.Net. It allows you to define classes as Jobs, and then execute those jobs according to an schedule. I'm currently using it in some in-house projects and it performs as advertised.
EDITED
Check the answers here.
It should be a console application with your code in it. In bin folder it will create a .exe file which you need to use it in windows task scheduler.
Following link provides you a step by step procedure on how to create a task in windows task scheduler.
http://www.digitalcitizen.life/how-create-task-basic-task-wizard

Activation code is not displaying in url after click on the link

I am sending a link using email to create password but while sending link in an email i have attach my Activation Code also to display with link but it is not displaying when i click on link though in debugging i'm getting the link with Activation Code. Below is my code to add link in Body section
body+=#"<br /><a href='http://localhost:49234/Index.aspx?ActivationCode='"+objUserDetailsBE.ActivationCode+"'>Create a login to account</a>";
I am getting only till http://localhost:49234/Index.aspx?ActivationCode= in browser after click on the link Please let me know where i am doing wrong.
Adding code as per in comments:
string emailAddress = txtEmailAddress.Text;
string subject = "Login Credentials For Nth Star";
string body = string.Format("Hello,");
body+=#"<br /><a href='http://localhost:49234/Index.aspx?ActivationCode='"+objUserDetailsBE.ActivationCode+"'>Create a login to account</a>";
Email.SendMail(objemail, emailAddress, subject, body, "");
and below is my 'SendMail' method
public static bool SendMail(EmailConfigurationBE objEmailConfig, string toEmailAddresses, string subject, string body, string mailAttachments)
{
char[] splitter = { ';' };
MailMessage mailMessage = new MailMessage();
mailMessage.From = new MailAddress(objEmailConfig.Email);
mailMessage.Subject = subject;
mailMessage.Body = body;
mailMessage.IsBodyHtml = true;
mailMessage.Priority = MailPriority.High;
string[] multi = toEmailAddresses.Split(';');
string[] multipath = mailAttachments.Split(';');
foreach (string MultiemailId in multi)
{
mailMessage.To.Add(new MailAddress(MultiemailId));
}
if (mailMessage.To.Count > 0)
{
//Adding Multiple Attachments
if (mailAttachments != "")
{
foreach (string Multipath1 in multipath)
{
Attachment attachFile = new Attachment(Multipath1);
mailMessage.Attachments.Add(attachFile);
}
}
SmtpClient smtpClient = new SmtpClient();
try
{
smtpClient.Host = objEmailConfig.SMTPServer;
smtpClient.EnableSsl = EnableSsl;
System.Net.NetworkCredential NetworkCred = new System.Net.NetworkCredential();
NetworkCred.UserName = objEmailConfig.Email;
NetworkCred.Password =objEmailConfig.Password;
smtpClient.UseDefaultCredentials = true;
smtpClient.Credentials = NetworkCred;
smtpClient.Port =Convert.ToInt32(objEmailConfig.PortNumber);
smtpClient.Send(mailMessage);
return true;
}
catch
{
mailMessage = null;
smtpClient = null;
return false;
}
}
else
{
return false;
}
}
It looks like a simple quoting problem. Look
<a href='http://localhost:49234/Index.aspx?ActivationCode='"+objUserDetailsBE.ActivationCode+"'
In here you have a single quote before http, another one after ActivationCode= and third one at the end. Looks like one is redundant, and that breaks your markup.
Correct version:
body+=#"<br /><a href='http://localhost:49234/Index.aspx?ActivationCode="+objUserDetailsBE.ActivationCode+"'>Create a login to account</a>";
The only change I did was to remove the single quote after ActivationCode=.
Also make sure the active code does not contain symbols like quotes or <>, that can also break the markup.

Mail excel attachment in asp.net C#

I am trying to attach a excel file with mail, but not getting where I am doing the mistake. There is no error coming but mail does not get send. When I try to check the server path of file with file exist. it show me true, so my file path is correct.
Mail is going properly without attachment.
MailMessage Msg = new MailMessage();
Msg.Subject = "User Creation";
string body = MailSending.PrepareMailBodyWith("WelcomeTemplate.htm", "LoginID", LoginID, "password", password);
string clientCoverage = System.Web.HttpContext.Current.Server.MapPath("~/file/abc.xlsx");
bool isFile = false;
if (File.Exists(clientCoverage))
{
isFile = true;
}
byte[] bytes = System.IO.File.ReadAllBytes(clientCoverage);
MemoryStream stream = new MemoryStream(bytes);
lblerror.Text = avnTutorial + isFile.ToString() ;
Attachment attachment = new Attachment(stream, "document.xlsx");
Msg.Attachments.Add(attachment);
Msg.Body = body;
Msg.IsBodyHtml = true;
Msg.From = new MailAddress("info#xyz.in");
Msg.To.Add(new MailAddress(Email));
SmtpClient client = new SmtpClient();
client.Host = "mail.xyz.in";
client.Port = 25;
client.Credentials = new System.Net.NetworkCredential("info#xyz.in", "xyz");
client.Send(Msg);
I tried with without memory stream also here is the code but does not work.
Attachment attachment = new Attachment(clientCoverage, MediaTypeNames.Application.Octet);

Email goes into Junk folder from asp.Net app

I have functionality in my site which sends a email to an id .. Email contains a link to a webpage and a security key .. But the problem is it goes into the junk folder
I'm using free hosting by Somee.com
Code:
MailMessage message = new MailMessage();
message.IsBodyHtml = true;
message.Body = ("Copy The Link And paste It In Them follow Link Download </br>"+ encoded_url);
message.From = new MailAddress("lz-wag#hotmail.com");
message.To.Add(TextBox2.Text);
message.Subject = user + " Has Share The File With You";
try{
SmtpClient client = new SmtpClient();
client.Host = "smtp.live.com";
client.EnableSsl = true;
System.Net.NetworkCredential networkcred = new System.Net.NetworkCredential();
networkcred.UserName = "lz-wag#hotmail.com";
networkcred.Password = "password";
client.Port = 587;
client.Credentials = networkcred;
client.Send(message);
sendFile.Visible = false;
Label1.Visible = true;
Label1.Text = "Your File Has Been Shared";
}
catch(Exception ex){
Label1.Visible = true;
Label1.Text = "Your File Is Not Shared";
//Label1.Text = ex.ToString(); ;
}
Whether or not the email goes into the junk mail folder is a function of the email client, not a function of how you are sending the email.
However, FYI, both the MailMessage and the SmtpClient implement IDisposable, so should be in using blocks. Something like this:
using (MailMessage message = new MailMessage())
{
// ...
using (SmtpClient client = new SmtpClient())
{
// ...
client.Send(message);
}
}
I also suggest that you log the exception somewhere, or you'll never know what went wrong when something goes wrong.

Attachment Excel File from Stream in ASP.NET?

I have an excel document.I want to mail it as attachment from stream.
It sended mail with attachment but i cant open excel file correctly
this is my code:
public static string EPostaGonder(...,Stream AttachmentStream,string AttachmentFileName)
{
.
.
.
SmtpClient mailClient = new SmtpClient(Host, Port);
mailClient.EnableSsl = true;
NetworkCredential cred = new NetworkCredential(KullaniciAdi, Sifre);
mailClient.Credentials = cred;
MailMessage ePosta = new MailMessage();
ePosta.IsBodyHtml = true;
ePosta.From = new MailAddress(Kimden, Isim);
foreach (string Kime_ in Kime.Split(';'))
{
if (Kime_.Trim() != "")
ePosta.To.Add(Kime_.Trim());
ePosta.Subject = Konu;
ePosta.Body = Mesaj.Replace("\n","<br/>");
if (Cc != "")
ePosta.CC.Add(Cc);
if (AttachmentStream != null)
{
AttachmentStream .Seek(0, SeekOrigin.Begin);
ePosta.Attachments.Add(
new Attachment(AttachmentStream, AttachmentFileName + ".xlsx"));
}
try
{
//mailClient.SendAsync(ePosta, (object)ePosta);
mailClient.Send(ePosta);
return "Done";
}
catch (SmtpException SmtpException_)
{
return SmtpException_.Message;
}
}
Use following code to add Attachment in mail. Simply pass the file path to Attachment constructor.
Attachment attachment = new Attachment(file);
ePosta.Attachments.Add(attachment);
Add an attachment from stream:
ePosta.Attachments.Add( new Attachment( AttachmentStream, filename, "application/msexcel" ));
Try something like
var attach = new MailAttachment(Server.MapPath(strFileName));
ePosta.Attachments.Add(attach);
Have a look at this article about ASP.NET email with multiple attachments

Resources