c# Base64 in email attachment - c#

I know that i'm stuck in a silly problem...and now i am here with hope, that you can help me. Simple situation: I need to send email with attachment from database. I have done it by myself, but...i don't know why, but attachment in email what was send is incorrect. Preciously attachment contents code, what i get from my database.
My code:
static void IncomeMessage()
{
SqlConnection conn = new SqlConnection("Data Source=xxx;Initial Catalog=xxx;User ID=xxx;Password=xxx");
SqlCommand cmd = new SqlCommand("Here is my SQL SELECT", conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
try
{
var AID = dr["ID"].ToString();
var Ids = dr["MessageID"].ToString();
var SuperOrganizationTitle = dr["SuperOrganizationTitle"].ToString();
var Date = dr["Date"].ToString();
var Title = dr["Title"].ToString();
var Description = dr["Description"].ToString();
var DBFile = dr["File"].ToString();
var Filename = dr["FileName"].ToString();
MailMessage oMail = new MailMessage("test#test.com", "guntisvindels#gmail.com", "New message with theme: " + Title, "Message Income: " + Date + " From " + SuperOrganizationTitle + ". Message Content: " + Description);
DBFile = GetBase64(DBFile);
var bytes = Encoding.ASCII.GetBytes(DBFile);
MemoryStream strm = new MemoryStream(bytes);
Attachment data = new Attachment(strm, Filename);
ContentDisposition disposition = data.ContentDisposition;
data.ContentId = Filename;
data.ContentDisposition.Inline = true;
oMail.Attachments.Add(data);
SmtpClient oSmtp = new SmtpClient();
SmtpClient oServer = new SmtpClient("test.test.com");
oServer.Send(oMail);
}
catch (Exception ex)
{
//TraceAdd("Error=" + ex.Message.ToString());
}
}
}
For removing unnessessary data ( tags) from database File field i use this code
public static string GetBase64(string str)
{
var index1 = str.IndexOf("<content>");
index1 = index1 + "<content>".Length;
var index2 = str.IndexOf("</content>");
var kek = Slice(str, index1, index2);
return kek;
}
public static string Slice(string source, int start, int end)
{
if (end < 0)
{
end = source.Length + end;
}
int len = end - start;
return source.Substring(start, len);
}
When launching my code I can send email to me, and I'll recieve it. But message content attachment with my Base64 code from database File field. Here is a question - Where I got wrong, and how can I recieve email with correct attachment that has been written into database. Thank you for your attention
P.S Attachment in database is written correctly, because K2 integration platform can correctly display it
Here is example what database contain in File column (DBFile)
<file><name>zinojums.html</name><content>PGh0bWw+PGhlYWQ+PG1ldGEgaHR0cC1lcXVpdj0iQ29udGVudC1UeXBlIiBjb250ZW50PSJ0ZXh0L2h0bWw7IGNoYXJzZXQ9dXRmLTgiIC8+PHN0eWxlPmh0bWwsYm9keXtmb250LWZhbWlseTpBcmlhbCxIZWx2ZXRpY2Esc2Fucy1zZXJpZjtmb250LXNpemU6MTBwdDt9aDF7Zm9udC1zaXplOjE0cHQ7fWgye2ZvbnQtc2l6ZToxMnB0O31we2JhY2tncm91bmQtY29sb3I6I0Y3RUVEQTttYXJnaW46MDtwYWRkaW5nOjhweDt9aHJ7aGVpZ2h0OjFweDsgYm9yZGVyOjAgbm9uZTsgY29sb3I6ICM1RjlCRDQ7IGJhY2tncm91bmQtY29sb3I6ICM1RjlCRDQ7fTwvc3R5bGU+PC9oZWFkPjxib2R5PjxoMT5JbmZvcm3EgWNpamEgbm8gVmFsc3RzIGllxYbEk211bXUgZGllbmVzdGE8L2gxPjxoMj5Eb2t1bWVudHMgcGllxYZlbXRzPC9oMj48cD5Ob2Rva8S8dSBtYWtzxIF0xIFqYSBOci4gPGI+TEFUVklKQVMgVkFMU1RTIFJBRElPIFVOIFRFTEVWxKpaSUpBUyBDRU5UUlMgQVMgKDQwMDAzMDExMjAzKTwvYj4gaWVzbmllZ3RhaXMgZG9rdW1lbnRzICI8Yj5aacWGYXMgcGFyIGRhcmJhIMWGxJNtxJNqaWVtPC9iPiIgTnIuIDxiPjU1NDYyNTY5PC9iPiBwaWXFhmVtdHMgdW4gaWVrxLxhdXRzIFZJRCBkYXR1YsSBesSTLjxiciAvPjwvcD48IS0tY29udGVudC0tPjxociAvPsWgaXMgZS1wYXN0cyBpciBpenZlaWRvdHMgYXV0b23EgXRpc2tpLCBsxatkemFtIHV6IHRvIG5lYXRiaWxkxJN0LjxiciAvPlBpZXNsxJNndGllcyBWSUQgRWxla3Ryb25pc2vEgXMgZGVrbGFyxJPFoWFuYXMgc2lzdMSTbWFpOiA8YSBocmVmPSJodHRwczovL2Vkcy52aWQuZ292Lmx2Ij5lZHMudmlkLmdvdi5sdjwvYT4uPC9ib2R5PjwvaHRtbD4=</content></file>

Right now the method you're using to create binary data from your string takes no account of the fact the string is base64-encoded specifically.
You need to replace
var bytes = Encoding.ASCII.GetBytes(DBFile);
with
var bytes = Convert.FromBase64String(DBFile);

Related

Storing Array Of String in Queue in C# AsynC

enter image description hereI am reading from MySql DB using C# but because I am doing some fata processing for the data which is coming out from DB so I had to store these data in order using Queue<> Class.
I am trying to store the data as ( String[] arr ) format in the Queue
but I found the Queue memory is ecpanding per each time storing data but the last group of array data will be repeated in side queue memory which I believe I am doing something wrong.
I believe it is clear in the attached image.
Notices:
I am calling Queue.Enqueue(arr) method inside another Async method which I believe it is very problematic way as in below
`
public async void DBReadAsync(Calculations.RetStartEndDates f, DataBufferCls.DataBuffer dt)
{
int i;
Task t1 = Task.Factory.StartNew(() =>
{
DB.ReadFromDB3(f, dt);
}
) ;
await t1;
}
public string[] ReadFromDB3(RetStartEndDates WeekStrtEnd, DataBuffer dt)
{
string s;
string[] arr = new string[8];
string fromtime = WeekStrtEnd.StartTime_Str;/// "8:40:30";"10:09:00"; //
string FromDate = WeekStrtEnd.StartDateDBFormate_Str; //"2022-10-14 "; //"2022-11-06 "; //
string FromTD = FromDate + " " + fromtime;
string Totime = WeekStrtEnd.EndTime_Str; //"11:19:22"; //
string ToDate = WeekStrtEnd.EndDateDBFormate_Str; //"2022-11-07 "; //
string ToTD = ToDate + " " + Totime;
Console.WriteLine($"Start date is {FromTD}");
Console.WriteLine($"End Date is {ToTD}");
string query = "SELECT * FROM data_46";
//Open connection
if (this.IsConnect())
{
StartReadingFromDB_Event("Hold");
dt.Monitortest();
//Create Command
MySqlCommand cmd = new MySqlCommand(query, Connection);
//Create a data reader and Execute the command
MySqlDataReader dataReader = cmd.ExecuteReader();
//Read the data and store them in the list
while (dataReader.Read())
{
arr[0] = dataReader[0].ToString();
arr[1] = dataReader[1].ToString();
arr[2] = dataReader[2].ToString();
arr[3] = dataReader[3].ToString();
arr[4] = dataReader[4].ToString();
arr[5] = dataReader[5].ToString();
arr[6] = dataReader[6].ToString();
arr[7] = dataReader[7].ToString();
dt.WrToBuffer3(arr);
Thread.Sleep(10);
}[enter image description here](https://i.stack.imgur.com/aAJnB.png)`
`
`
I am trying to understand the reason for that

Sending emails with a PDF attachment (C#)

I have an intranet site to manage clients' communications. There are only a few controls: a textbox for the Subject, Attachment (fileUpload control), and a multiline textbox for the content of the email.
Using the fileUpload control, I select the pdf file that I want to send to clients. All the details about the clients (name, email address, etc) is coming from a sql table.
The sending works just fine, it sends the email with the attachment. However, the PDF attachment cannot be opened. The error is that the file hasn't been correctly decoded. I am not sure where the problem is. Does anyone have an idea on where the problem is?
Here is the code (for the sending procedure):
protected void BtnSendAcctClientsEmail_Click(object sender, EventArgs e)
{
if (uplAcctngAttachment.HasFile)
{
HttpPostedFile uploadedFile = uplAcctngAttachment.PostedFile;
if (IsAcctngFileHeaderValid(uploadedFile))
{
var fileName = Path.GetFileName(uplAcctngAttachment.PostedFile.FileName);
string strExtension = Path.GetExtension(fileName);
if (strExtension != ".pdf")
{
lblAcctngFileErr.Text = "Please attach pdf files only.";
return;
}
else
{
lblAcctngFileErr.Text = "";
}
try
{
DataSet ds_Emails = new DataSet();
constr = ConfigurationManager.ConnectionStrings["CS"].ConnectionString;
cn = new SqlConnection(constr);
cmd = new SqlCommand("getAcctClientsEmailAddresses", cn);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da_Emails = new SqlDataAdapter(cmd);
cn.Open();
da_Emails.Fill(ds_Emails);
cn.Close();
for (int vLoop = 0; vLoop < ds_Emails.Tables[0].Rows.Count; vLoop++)
{
string name_first = ds_Emails.Tables[0].Rows[vLoop]["contact_fname"].ToString();
email = ds_Emails.Tables[0].Rows[vLoop]["email"].ToString();
client_id = ds_Emails.Tables[0].Rows[vLoop]["id"].ToString();
clientType = "acctng";
// Build the Body of the message using name_first into a string and then send mail.
//send e-mail
string fromAddress = "associates#example.com";
string ccAddress = fromAddress;
string subject = txtAcctngSubject.Text;
string sendEmail = "Dear " + name_first + "," + Environment.NewLine + Environment.NewLine + txtAcctngMessage.Text;
sendEmail += Environment.NewLine + Environment.NewLine + "Go to https://www.example.com/crm_removal.aspx?id=" + client_id +
"&type=" + clientType + " to be removed from any future communications.";
MailAddress fromAdd = new MailAddress(fromAddress, "Associates");
MailAddress toAdd = new MailAddress(email);
MailMessage eMailmsg = new MailMessage(fromAdd, toAdd);
Attachment attachment;
attachment = new Attachment(uplAcctngAttachment.PostedFile.InputStream, fileName);
eMailmsg.Subject = subject;
eMailmsg.Attachments.Add(attachment);
eMailmsg.Body = sendEmail;
SmtpClient client = new SmtpClient();
client.Send(eMailmsg);
}
}
catch (Exception ex)
{
Response.Write("<script>alert('" + ex.Message + "')</script>");
sendingErr = ex.Message;
SendErr();
}
Response.Redirect("default.aspx", false);
}
}
}
private bool IsAcctngFileHeaderValid(HttpPostedFile uploadedFile)
{
Stream s = uplAcctngAttachment.PostedFile.InputStream;
StringBuilder buffer = new StringBuilder();
int value;
for (int i = 0; i < 2; i++)
{
value = s.ReadByte();
if (value == -1)
{
throw new Exception("Invalid file data.");
}
buffer.Append(value.ToString());
}
/*extension code list for files
* 7780 = exe
* 8075 = docx
* 3780 = pdf
* 7173 = gif
* 255216 = jpg
* 13780 = png
* 6677 = bmp
* 208207 =xls, doc, ppt
* 8075 = xlsx,zip,pptx,mmap,zip
* 8297 = rar
* 01 = accdb,mdb
*/
string[] input = { "208207", "8075", "3780", "255216", "13780", "6677" };
List<string> headers = new List<string>(input);
return headers.Contains(buffer.ToString());
}
When you pass the stream to the Attachment constructor it's offset by 2 bytes because you read from it earlier in IsAcctngFileHeaderValid corrupting the data.
Reset the stream position using uplAcctngAttachment.PostedFile.InputStream.Position = 0; when IsAcctngFileHeaderValid is done reading.

How can I get values from a csv file where some of the cells contain commas?

I have a script that imports a csv file and reads each line to update the corresponding item in Sitecore. It works for many of the products but the problem is for some products where certain cells in the row have commas in them (such as the product description).
protected void SubmitButton_Click(object sender, EventArgs e)
{
if (UpdateFile.PostedFile != null)
{
var file = UpdateFile.PostedFile;
// check if valid csv file
message.InnerText = "Updating...";
Sitecore.Context.SetActiveSite("backedbybayer");
_database = Database.GetDatabase("master");
SitecoreContext context = new SitecoreContext(_database);
Item homeNode = context.GetHomeItem<Item>();
var productsItems =
homeNode.Axes.GetDescendants()
.Where(
child =>
child.TemplateID == new ID(TemplateFactory.FindTemplateId<IProductDetailPageItem>()));
try
{
using (StreamReader sr = new StreamReader(file.InputStream))
{
var firstLine = true;
string currentLine;
var productIdIndex = 0;
var industryIdIndex = 0;
var categoryIdIndex = 0;
var pestIdIndex = 0;
var titleIndex = 0;
string title;
string productId;
string categoryIds;
string industryIds;
while ((currentLine = sr.ReadLine()) != null)
{
var data = currentLine.Split(',').ToList();
if (firstLine)
{
// find index of the important columns
productIdIndex = data.IndexOf("ProductId");
industryIdIndex = data.IndexOf("PrimaryIndustryId");
categoryIdIndex = data.IndexOf("PrimaryCategoryId");
titleIndex = data.IndexOf("Title");
firstLine = false;
continue;
}
title = data[titleIndex];
productId = data[productIdIndex];
categoryIds = data[categoryIdIndex];
industryIds = data[industryIdIndex];
var products = productsItems.Where(x => x.DisplayName == title);
foreach (var product in products)
{
product.Editing.BeginEdit();
try
{
product.Fields["Product Id"].Value = productId;
product.Fields["Product Industry Ids"].Value = industryIds;
product.Fields["Category Ids"].Value = categoryIds;
}
finally
{
product.Editing.EndEdit();
}
}
}
}
// when done
message.InnerText = "Complete";
}
catch (Exception ex)
{
message.InnerText = "Error reading file";
}
}
}
The problem is that when a description field has commas, like "Product is an effective, preventative biofungicide," it gets split as well and throws off the index, so categoryIds = data[8] gets the wrong value.
The spreadsheet is data that is provided by our client, so I would rather not require the client to edit the file unless necessary. Is there a way I can handle this in my code? Is there a different way I can read the file that won't split everything by comma?
I suggest use Ado.Net, If the field's data are inside quotes and it will parse it like a field and ignore any commas inside this..
Code Example:
static DataTable GetDataTableFromCsv(string path, bool isFirstRowHeader)
{
string header = isFirstRowHeader ? "Yes" : "No";
string pathOnly = Path.GetDirectoryName(path);
string fileName = Path.GetFileName(path);
string sql = #"SELECT * FROM [" + fileName + "]";
using(OleDbConnection connection = new OleDbConnection(
#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + pathOnly +
";Extended Properties=\"Text;HDR=" + header + "\""))
using(OleDbCommand command = new OleDbCommand(sql, connection))
using(OleDbDataAdapter adapter = new OleDbDataAdapter(command))
{
DataTable dataTable = new DataTable();
dataTable.Locale = CultureInfo.CurrentCulture;
adapter.Fill(dataTable);
return dataTable;
}
}

Sending mails automatically by console application

Create one console application for sending a birthday wishing mail for company employees is here there is send mail code of only one by one employee I try but can't got a multiple emails id from database
Here Code i try it:
class Program
{
static void Main(string[] args)
{
try
{
string connStr = ConfigurationManager.ConnectionStrings["EmpDBConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(connStr);
con.Open();
SqlCommand cmd;
cmd = new SqlCommand("SELECT empemail,EmpDOB,empname,Photo,BdayMessage,CC FROM EmpDetails where datepart(day,EmpDOB)= datepart(day,sysdatetime()) and datepart(month,EmpDOB)=datepart(month,sysdatetime())", con);
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
{
ArrayList list_emails = new ArrayList();
int i = 0;
string email, Bday;
int diff;
while (reader.Read())
{
email = reader.GetValue(i).ToString();
list_emails.Add(email); //Add email to a arraylist
i = i + 1 - 1;
}
string todaydate = DateTime.Now.ToString("dd/MM");
Bday = Convert.ToDateTime(reader["EmpDOB"]).ToString("dd/MM"); //date converted
diff = DateTime.Compare(DateTime.Today, Convert.ToDateTime(Bday)); //compare cuurent date and date of birthday from database of emplyees with only day and month
//string Bday = Convert.ToDateTime(reader["EmpDOB"]).ToString("dd/MM");
if (diff == 0)
{
//string Email = reader["EmpEmail"].ToString();
string Name = reader["EmpName"].ToString();
string Photo = reader["Photo"].ToString();
string cc = reader["CC"].ToString();
string Bdaymessage = reader["BdayMessage"].ToString();
string body = "<br><b><i><font Size=4 face=Comic Sans MS color= #FF2B9E> Dear</br><br><font Size=4 face=Comic Sans MS color=#FF2B9E>" + Name + "</i></b>" + "<br>" + "<br><img src=" + Photo + "></body></html></body></html>" + "<br><b><font Size=4 face=Comic Sans MS color=#FF2B9E><i>" + Bdaymessage + "</i></b></br> " + "<br><br><br>";
AlternateView av = AlternateView.CreateAlternateViewFromString(body, null, System.Net.Mime.MediaTypeNames.Text.Html);
LinkedResource inline = new LinkedResource(Photo, MediaTypeNames.Image.Jpeg);
inline.ContentId = Guid.NewGuid().ToString();
av.LinkedResources.Add(inline);
System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage();
msg.AlternateViews.Add(av);
//msg.To.Add(email);
msg.CC.Add(cc);
msg.Subject = " WIsH YoU MaNy MaNY HaPPy Birthday";
msg.From = new System.Net.Mail.MailAddress("example#gmail.com");
SmtpClient mailClient = new SmtpClient("smtp.gmail.com", 587);
NetworkCredential NetCrd = new NetworkCredential("eample#gmail.com", "password");
mailClient.UseDefaultCredentials = false;
mailClient.Credentials = NetCrd;
mailClient.EnableSsl = true;
mailClient.DeliveryMethod = SmtpDeliveryMethod.Network;
mailClient.Send(msg);
reader.Close();
con.Close();
}
else
{
Console.Write("its a earlier date");
}
}
}
}
catch (Exception ex)
{
Console.Write("There is No Birthday" + ex);
}
}
}
You are getting the multiple users form the database that have birthdays with DataReader in a while loop. You just need to move the email sending code inside the loop.
I would recommend you to extract population report (name, birthday, hiredate, email) as excel and let wishing application take care of everything
At minimal it just need two things excel file with wish details (Date, name, email) and a configuration file (application.properties) and that is it, you are good to go.
Further there various options to run the application locally (Command line, foreground, background, docker, windows scheduler, unix cron etc) Cloud.
Application is highly configurable , you can configure various details like:
Workbook loading options
Image options to send with wishes.
SMTP Configurations
Other application level configurations like, when to send wish, belated wish, logging etc.
Disclaimer : I am the owner of the application

sqlBulk insert C#

I have a page where I want to upload a CSV file from my computer to database on the server and I have my opentext that looks like the following
using (StreamReader sr = File.OpenText(#"c:\users\workstationUsername\FileName.csv"))
This works fine on my local machine but when I push this to the server it tries to read the server's C Drive and I want it to read the physical file location that is sitting on the desktop of the user's computer not the server, when they click browse and upload..
Thank you
below is the complete code:
if (IsPostBack)
{
// SetDefaultDates();
Boolean fileOK = false;
String dateString = DateTime.Now.ToString("MMddyyyy");
String UserName = User.Identity.Name;
String path = Server.MapPath("~/Uploads/CSVs/");
string stringpath = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
String fileName = System.IO.Path.GetFileName(FileUpload1.PostedFile.FileName);
stringpath = stringpath + fileName;
String LocationToSave = path + "\\" + fileName;
if (FileUpload1.HasFile)
{
String fileExtension =
System.IO.Path.GetExtension(FileUpload1.FileName).ToLower();
String[] allowedExtensions = { ".csv" };
for (int i = 0; i < allowedExtensions.Length; i++)
{
if (fileExtension == allowedExtensions[i])
{
fileOK = true;
}
}
}
if (fileOK)
{
try
{
//FileUpload1.PostedFile.SaveAs(LocationToSave + dateString + "-" + FileUpload1.FileName);
FileUpload1.PostedFile.SaveAs(LocationToSave);
Label1.Text = "File " + FileUpload1.FileName + " uploaded!";
DataTable dt = new DataTable();
string line = null;
int i = 0;
using (StreamReader sr = File.OpenText(stringpath))
{
while ((line = sr.ReadLine()) != null)
{
string[] data = line.Split(',');
if (data.Length > 0)
{
if (i == 0)
{
foreach (var item in data)
{
dt.Columns.Add(new DataColumn());
}
i++;
}
DataRow row = dt.NewRow();
row.ItemArray = data;
dt.Rows.Add(row);
}
}
}
using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["Myconnection"].ConnectionString))
{
cn.Open();
using (SqlBulkCopy copy = new SqlBulkCopy(cn))
{
copy.WriteToServer(dt);
}
}
}
catch (Exception ex)
{
Label1.Text = "File " + FileUpload1.FileName + " could not be uploaded." + ex.Message;
}
}
else
{
Label1.Text = "Cannot accept files of this type. " + FileUpload1.FileName;
}
}
SetDefaultDates();
}
If you have a FileUpload control, then instead of using (StreamReader sr = File.OpenText(#"c:\users\workstationUsername\FileName.csv")) which obvously is pointing to the server's hard drive you can do this:
(StreamReader sr = new StreamReader(fileUploadControl.FileContent))
//Do your stuff
You can't access the client's hard drive. That's a major security concern. You'll need to upload the file to your server, and read it from there.
It doesnt make sense to have a static read to the local machine, rather get user to upload it then update the database, this code is very limiting and has a high security risk. Rather create a steamreader object get the user to upload it then use the steam reader to process the csv.

Categories

Resources