Add Multiple Images as Inline Attachment in Email Message Body - asp.net

I am trying to add multiple png images as inline attachments to email body. My email body only has the last image. Looks like the memorysteam was overwritten new one. I tried to use AlternateView as this post suggested How to attach multi images in email body in windows application?. But it does not show any image. How to add multiple images attachments? Thanks.
struct Webpage
{
public string Id { get; set; }
public Byte[] Img { get; set; }
public string SiteName { get; set; }
public DateTime CollectTime { get; set; }
}
//
static void SendMultileImgsWEmail(List<Webpage> msg)
{
MailMessage mailMessage = new MailMessage();
SmtpClient client = new SmtpClient(mailserver);
mailMessage.IsBodyHtml = true;
mailMessage.From = new MailAddress(From);
mailMessage.To.Add(new MailAddress(To));
mailMessage.Subject = "xxx";
foreach (Webpage item in msg)
{
byte[] image = item.Img;
Attachment att = new Attachment(new MemoryStream(item.Img), item.SiteName);
att.ContentDisposition.Inline = true;
att.ContentId = item.Id;
att.ContentType.MediaType = "image/png";
mailMessage.Body += "Website Name: " + item.SiteName + Environment.NewLine + Environment.NewLine;
mailMessage.Body += "Screenshot Time: " + item.CollectTime + Environment.NewLine + Environment.NewLine;
mailMessage.Body = String.Format( #"<img src=""cid:{0}"" />", att.ContentId);
mailMessage.Attachments.Add(att);
}
//send message
try
{
client.Send(mailMessage);
}
catch (Exception ex)
{
throw;
}
}

Related

email function not working after publishing to iis

I've published my app and it is now running from IIS. the problem is that the email function in my controller no longer works when running on IIS (the email function does not send email)
I have an email function on my mvc application and when I run it, it does send an email. The problem starts after I've published my app, Its running on IIS now but the email function does not send the email anymore. How do I go about fixing this?
[HttpPost]
public JsonResult SendMailToUser(string lt, string reason, string name, string fr, string ed)
{
bool result = false;
result = SendMail("ntulisakhile8#gmail.com", "Leave Reaquest", "Hi Sensei,<br />I would like to take a " + lt + " leave<br/><strong>From:</strong> " + fr + " <strong>To:</strong> " + ed + " <br/>Reason: " + reason + "<br/>Regards<br/>" + name + "<br/><a href=~/Response.html>Respond</a>");
return Json(result, JsonRequestBehavior.AllowGet);
}
public bool SendMail(string toEmail, string subject, string emailBody)
{
try
{
string senderEmail = System.Configuration.ConfigurationManager.AppSettings["SenderEmail"].ToString();
string senderPassword = System.Configuration.ConfigurationManager.AppSettings["SenderPassword"].ToString();
SmtpClient client = new SmtpClient("smtp.gmail.com", 587);
client.EnableSsl = true;
client.Timeout = 100000;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Credentials = new NetworkCredential(senderEmail, senderPassword);
MailMessage mailMessage = new MailMessage(senderEmail, toEmail, subject, emailBody);
mailMessage.IsBodyHtml = true;
mailMessage.BodyEncoding = UTF8Encoding.UTF8;
client.Send(mailMessage);
return true;
}
catch (Exception ex)
{
return false;
}
}

how to upload photo to sql using json wcf

I am creating WCF for an iphone app. i want to know how to upload photo to the sql using json wcf any idea?this is the process how to connect it to the sql?
public class TestService : ITestService
{
[WebInvoke(Method = "POST", UriTemplate = "UploadFile?fileName={fileName}")]
public string UploadFile(string fileName, Stream fileContents)
{
//save file
string absFileName = "";
try
{
absFileName = string.Format("{0}\\FileUpload\\{1}"
, AppDomain.CurrentDomain.BaseDirectory
, Guid.NewGuid().ToString().Substring(0,6) + ".jpg");
// string fld = #"h:\root\home\amrmk185-001\www\publish\WCFService\FileUpload\" + fileName;
//System.IO.File.Create(absFileName);
using (FileStream fs = new FileStream(absFileName, FileMode.Create))
{
fileContents.CopyTo(fs);
fileContents.Close();
}
return "Upload OK";
}
catch(Exception ex)
{
return "FAIL ==> " + ex.Message + " " + absFileName;
}
}

Windows Phone 8 http post file upload timeout

I am developing a Windows phone 8 app that needs to upload photos to amazon s3 storage. However, I find that this is impossible since the HttpClient time out after about 60 seconds regardless of what timeout setting I use.
Is there really no way to upload large files from Windows Phone?
BackgroundTransferRequest is useless since it cannot send the neccessary metadata with file uploads.
I use this code (which times out):
using (var httpClient = new HttpClient())
{
httpClient.Timeout = TimeSpan.FromMinutes(30);
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, m_uploadUrl);
httpContent.Headers.Add("Keep-Alive", "true");
request.Content = httpContent; // 3-5 Mb file
response = await httpClient.SendAsync(request);
statusCode = response.StatusCode;
}
I also tried PostAsync(), but same result. After about 60 sec the call completes with a status code 400 or 404. This is not a server timeout. IPhone and Android apps use the same service. No problems there.
Any ideas on how to upload files that takes more than 60 seconds to send?
I too faced similar things. The timeout glitch.
Check if you could use another class instead of HttpClient.
WebClient may be.
Check if this helps you:
http://blog.anthonybaker.me/2013/06/how-to-upload-file-from-windows-phone.html
and even this:
http://chriskoenig.net/2011/08/19/upload-files-from-windows-phone/
I got things working for me with those.
I've used several days now to implement a new uploader and get all the details working. I used HttpWebRequest with the async methods and split the file into chuncks. Finally I got it working and it uploads without the timeout. Here is the complete code:
using System;
using Models;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Services
{
public class UploadData
{
public Stream PostStream { get; set; }
public Stream FileStream { get; set; }
public byte[] HeaderBytes {get; set;}
public byte[] FooterBytes {get; set;}
public byte[] Buffer { get; set; }
public Photo Upload { get; set; }
public int BytesWritten { get; set; }
}
public class UploadEventArgs : EventArgs
{
public Photo Upload { get; set; }
public int Progress { get; set; }
}
public class UploadService
{
public delegate void CompletedEventHandler(object sender, UploadEventArgs e);
public event CompletedEventHandler UploadCompleted;
public delegate void ProgressEventHandler(object sender, UploadEventArgs e);
public event ProgressEventHandler ProgressChanged;
private static string contentType = "multipart/form-data; boundary={0}";
private static string headerString = "Content-Disposition: form-data; name=\"file\"; filename=\"{0}\"\r\nContent-Type: Content-Type: application/octet-stream\r\n\r\n";
private HttpWebRequest m_request;
private static string boundarystr;
private UploadData m_uploadData;
private bool m_isStopped;
public async Task StartUpload(Photo upload, Uri uri, Dictionary<string, string> parameters)
{
try
{
m_isStopped = false;
var fileStream = (await upload.File.OpenReadAsync()).AsStreamForRead();
var uploadData = new UploadData();
boundarystr = "---------------------------" + DateTime.Now.Ticks.ToString("x");
string para = GetParamsString(parameters);
string headAndParams = para + String.Format(headerString, HttpUtility.UrlEncode(upload.File.Name));
var headerBytes = System.Text.Encoding.UTF8.GetBytes(headAndParams);
var footerBytes = Encoding.UTF8.GetBytes("\r\n--" + boundarystr + "--\r\n");
uploadData.Upload = upload;
uploadData.FileStream = fileStream;
uploadData.FooterBytes = footerBytes;
uploadData.HeaderBytes = headerBytes;
uploadData.BytesWritten = 0;
m_uploadData = uploadData;
m_request = (HttpWebRequest)WebRequest.Create(uri);
m_request.Method = "POST";
m_request.AllowWriteStreamBuffering = false;
m_request.ContentType = string.Format(contentType, boundarystr);
m_request.ContentLength = fileStream.Length + headerBytes.Length + footerBytes.Length;
var asyncResult = m_request.BeginGetRequestStream((ar) => { GetRequestStreamCallback(ar, uploadData); }, m_request);
}
catch (Exception ex)
{
m_uploadData.Upload.UploadInfo.StatusCode = HttpStatusCode.NotFound;
m_uploadData.Upload.UploadInfo.Exception = new Exception("Start upload failed: " + ex.Message);
var argsStopped = new UploadEventArgs();
argsStopped.Upload = m_uploadData.Upload;
m_uploadData.FileStream.Close();
m_uploadData.PostStream.Close();
OnUploadComplete(argsStopped);
}
}
private void GetRequestStreamCallback(IAsyncResult asynchronousResult, UploadData uploadData)
{
try
{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
Stream postStream = request.EndGetRequestStream(asynchronousResult);
postStream.Write(uploadData.HeaderBytes, 0, uploadData.HeaderBytes.Length);
var args = new UploadEventArgs();
args.Upload = uploadData.Upload;
args.Progress = 1;
OnProgressChanged(args);
uploadData.PostStream = postStream;
WriteNextChunck(uploadData);
}
catch (Exception ex)
{
m_uploadData.Upload.UploadInfo.StatusCode = HttpStatusCode.NotFound;
m_uploadData.Upload.UploadInfo.Exception = new Exception("Header write failed: " + ex.Message);
var argsStopped = new UploadEventArgs();
argsStopped.Upload = m_uploadData.Upload;
m_uploadData.FileStream.Close();
m_uploadData.PostStream.Close();
OnUploadComplete(argsStopped);
}
}
private void WriteNextChunck(UploadData upload)
{
try
{
if ((upload.FileStream.Length - upload.BytesWritten) >= 16 * 1024)
{
upload.Buffer = new byte[16 * 1024];
}
else
{
// Last part
upload.Buffer = new byte[upload.FileStream.Length - upload.BytesWritten];
}
upload.FileStream.Read(upload.Buffer, 0, (int)upload.Buffer.Length);
upload.PostStream.BeginWrite(upload.Buffer, 0, upload.Buffer.Length, BeginWriteCallback, upload);
}
catch (Exception ex)
{
m_uploadData.Upload.UploadInfo.StatusCode = HttpStatusCode.NotFound;
m_uploadData.Upload.UploadInfo.Exception = new Exception("Buffer write failed: " + ex.Message);
var argsStopped = new UploadEventArgs();
argsStopped.Upload = m_uploadData.Upload;
upload.FileStream.Close();
upload.PostStream.Close();
OnUploadComplete(argsStopped);
}
}
private void BeginWriteCallback(IAsyncResult ar)
{
try
{
var upload = ar.AsyncState as UploadData;
upload.PostStream.EndWrite(ar);
upload.BytesWritten += upload.Buffer.Length;
var args = new UploadEventArgs();
args.Upload = upload.Upload;
args.Progress = (int)(((decimal)upload.BytesWritten / (decimal)upload.FileStream.Length) * 100);
OnProgressChanged(args);
if (m_isStopped)
{
upload.FileStream.Close();
upload.PostStream.Close();
m_uploadData.Upload.UploadInfo.StatusCode = HttpStatusCode.NotFound;
m_uploadData.Upload.UploadInfo.Exception = new Exception("Upload stopped");
var argsStopped = new UploadEventArgs();
argsStopped.Upload = m_uploadData.Upload;
OnUploadComplete(argsStopped);
return;
}
// write next chunck
if (upload.BytesWritten < upload.FileStream.Length)
{
WriteNextChunck(upload);
}
if (upload.BytesWritten >= upload.FileStream.Length)
{
WriteFooter(upload);
}
}
catch (Exception ex)
{
m_uploadData.Upload.UploadInfo.StatusCode = HttpStatusCode.NotFound;
m_uploadData.Upload.UploadInfo.Exception = new Exception("Upload write failed: " + ex.Message);
var argsStopped = new UploadEventArgs();
argsStopped.Upload = m_uploadData.Upload;
OnUploadComplete(argsStopped);
}
}
private void WriteFooter(UploadData upload)
{
try
{
upload.PostStream.Write(upload.FooterBytes, 0, upload.FooterBytes.Length);
upload.PostStream.Close();
var asyncResult = m_request.BeginGetResponse(new AsyncCallback(GetResponseCallback), m_request);
}
catch (Exception ex)
{
m_uploadData.Upload.UploadInfo.StatusCode = HttpStatusCode.NotFound;
m_uploadData.Upload.UploadInfo.Exception = new Exception("Footer write failed: " + ex.Message);
var argsStopped = new UploadEventArgs();
argsStopped.Upload = m_uploadData.Upload;
OnUploadComplete(argsStopped);
}
}
private void GetResponseCallback(IAsyncResult asynchronousResult)
{
try
{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
Stream streamResponse = response.GetResponseStream();
StreamReader streamRead = new StreamReader(streamResponse);
string responseString = streamRead.ReadToEnd();
streamResponse.Close();
streamRead.Close();
response.Close();
m_uploadData.FileStream.Close();
m_uploadData.Upload.UploadInfo.StatusCode = response.StatusCode;
if (response.StatusCode == HttpStatusCode.NoContent)
{
m_uploadData.Upload.UploadInfo.Exception = null;
}
else
{
m_uploadData.Upload.UploadInfo.Exception = new Exception(responseString);
}
var args = new UploadEventArgs();
args.Upload = m_uploadData.Upload;
args.Progress = 100;
OnUploadComplete(args);
}
catch (Exception ex)
{
m_uploadData.Upload.UploadInfo.StatusCode = HttpStatusCode.NotFound;
m_uploadData.Upload.UploadInfo.Exception = ex;
var args = new UploadEventArgs();
args.Upload = m_uploadData.Upload;
OnUploadComplete(args);
}
}
private string GetParamsString(Dictionary<string, string> parameters)
{
bool needsCLRF = false;
string result = "";
foreach (var param in parameters)
{
// Thanks to feedback from commenters, add a CRLF to allow multiple parameters to be added.
// Skip it on the first parameter, add it to subsequent parameters.
if (needsCLRF)
result += "\r\n";
needsCLRF = true;
string prm = string.Format("--{0}\r\nContent-Type: text/plain; charset=utf-8\r\nContent-Disposition: form-data; name={1}\r\n\r\n{2}",
boundarystr,
param.Key,
param.Value);
result += prm;
}
// Add the end of the request. Start with a newline
string footer = "\r\n--" + boundarystr + "\r\n";
result += footer;
return result;
}
protected virtual void OnUploadComplete(UploadEventArgs e)
{
if (UploadCompleted != null)
UploadCompleted(this, e);
}
protected virtual void OnProgressChanged(UploadEventArgs e)
{
if (ProgressChanged != null)
ProgressChanged(this, e);
}
public void Stop()
{
m_isStopped = true;
}
}
}

How to render a Bitmap property in a Reporting RDLC and render a non corrupted pdf file

I have to render a bitmap in my rdlc (using .Net Reporting) And then render this file in different formats(including pdf).
The DataSet consists of SeriesItemModels objects List that(each item of the list) has one property defined as of the Bitmap type!
The problem is that I face two problems:
- It seems like the bitmap is not rendered in the rdlc
- The file extension disappears and the downloaded file is corrupted
Here is the Print method (the one that I call within an action to render the pdf file)
public class StatisticsStateModels
{
public static void Print(List<SeriesItemModels> items, string printFormat)
{
ReportViewer rptViewer = new ReportViewer();
rptViewer.ProcessingMode = ProcessingMode.Local;
rptViewer.LocalReport.EnableExternalImages = true;
rptViewer.LocalReport.ReportPath = #HttpContext.Current.Request.PhysicalApplicationPath + "Content/States/Statistics.rdlc";
rptViewer.LocalReport.DataSources.Add(new ReportDataSource("StatisticsModelsDataSet", StatisticsStateModels.GetStatistics(items)));
HttpResponse response = HttpContext.Current.Response;
DateTime now = DateTime.Now;
string filename = now.Year + "" + now.Month + "" + now.Day + "" + now.Hour + "" + now.Minute + "" + now.Second + "" + now.Millisecond;
Warning[] warnings;
string[] streamIds;
string mimeType = string.Empty;
string encoding = string.Empty;
string extension = string.Empty;
switch (printFormat.ToLower())
{
case "pdf":
byte[] pdfContent = rptViewer.LocalReport.Render("PDF", null, out mimeType, out encoding, out extension, out streamIds, out warnings);
response.Clear();
//response.ClearHeaders();
response.Buffer = true;
response.ContentType = mimeType;
response.AddHeader("content-disposition", "attachment; filename=" + filename + "." + extension);
// response.ContentType = "application/pdf";
response.BinaryWrite(pdfContent);
response.Flush(); // send it to the client to download
response.End();
break;
default:
break;
}
}
}
and the DataSet method
public static List<SeriesItemModels> GetStatistics(List<SeriesItemModels> items)
{
return items;
}
Last, you have the SeriesItem model bellow
public class SeriesItemModels
{
public string name { get; set; }
public List<object> data { get; set; }
public Bitmap graph { get; set; }
public SeriesItemModels() {
this.name = "";
this.graph = validBitMap();//be sure: this bitMap is external and valid!
this.data = new List<object>();
}
}
PS: the validBitMap is generated perfectly and correctly! I tried to save it on the server, It works! But the file remains corrupted despite my efforts.
Can you tell me how to solve theses issues? Why is my file corrupted ?
Thank you
Here is what I did and It works perfectly:
first I changed the Bitmap graph property into a byte[] array, using the ImageConverter (see bellow)
public class SeriesItemModels{
public string name { get; set; }
public List<object> data { get; set; }
private BitMap _graph;
public byte[] graph { get{
ImageConverter converter = new ImageConverter();
return (byte[])converter.ConvertTo(_bitmap, typeof(byte[]));
}
set{
//...intentionaly ignored
} }
public SeriesItemModels() {
this.name = "";
this.graph = validBitMap();//be sure: this bitMap is external and valid!
this.data = new List<object>();
}
}
And the files were corrupted because of the post request! I have changed the request into a get request and now files are being downloaded correctly(not corrupted)

insert Image in database

I am new to asp.net and databases! I am trying to save image into database from the file upload control. i have tried it but it isn't working that is upon clicking the submit button, the data does not get added into the database neither showing any error! this is the code which I have tried
protected void ButtonSubmit_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile && Page.IsValid) //fileUpload and submit
{
string fileExtension = System.IO.Path.GetExtension(FileUpload1.FileName);
if (fileExtension.ToLower() != ".jpg")
{
Labelupload.Text = "Only Files with .jpg extension are allowed";
Labelupload.ForeColor = System.Drawing.Color.Red;
}
else
{
FileUpload1.SaveAs(Server.MapPath("~/Uploads/" + FileUpload1.FileName));
Labelupload.Text = "File Uploaded";
Labelupload.ForeColor = System.Drawing.Color.DeepSkyBlue;
LabelSubmit.Text = "Submitted Succesfully";
LabelSubmit.ForeColor = System.Drawing.Color.DeepSkyBlue;
}
}
else
{
Labelupload.Text = "Please select a file";
Labelupload.ForeColor = System.Drawing.Color.Red;
LabelSubmit.Text = "Failed to Submit";
LabelSubmit.ForeColor = System.Drawing.Color.Red;
}
// insert into database
Work obj = new Work();
/* Stream fs = FileUpload1.PostedFile.InputStream;
BinaryReader br = new BinaryReader(fs);
Byte[] bytes = br.ReadBytes((Int32)fs.Length);*/
obj.listItem_1 = DropDownList1.SelectedValue;
obj.listItem_2 = DropDownList2.SelectedValue;
obj.Description = TextBoxdescription.Text;
obj.Date = TextBoxdate.Text;
//obj.UploadedImage = bytes;
int k = obj.insertmethod();
TextBoxdescription.Text = "";
}
Here is the Work class that contains the insertmethod() logic:
public class Work
{
Clssqlconnection obj = new Clssqlconnection();
public string listItem_1 { get; set; }
public string listItem_2 { get; set; }
public string Description { get; set; }
public string Date { get; set; }
//public Byte[] UploadedImage { get; set; }
public int insertmethod()
{
obj.str = #"insert into [assign_Work] (listItem_1, listItem_2, Description, Date, UploadedImage)" +
"values('" + listItem_1 + "','" + listItem_2 + "','" + Description + "','" + Date + "','" + UploadedImage + "')";
return obj.ExecuteNonQuery();
}
}
The image needs to go into the database via a parameter. You cannot have it in a raw SQL statement. Try this:
public int insertmethod()
{
obj.str = #"insert into [assign_Work] (listItem_1, listItem_2, Description, Date, UploadedImage)" +
"values('" + listItem_1 + "','" + listItem_2 + "','" + Description + "','" + Date + "', ?)";
obj.Parameters.AddWithValue("File", UploadedImage);
return obj.ExecuteNonQuery();
}
Also, btw, you might want to consider using parameters for all of these values to avoid injection attacks. For instance, what if your Description field had an apostrophe in it?

Resources