Attatch Gridview to email body VB.NET - asp.net

I am currently sending emails programatically in my web page, the emails work fine but i would also like to attach a gridview into the email body.
this is my VB code I have for sending the email so far...
Dim Uname As String = Page.User.Identity.Name.Substring(Page.User.Identity.Name.IndexOf("\") + 1)
strFm = Uname + "#Inscapepeople.co.uk"
If strTo <> "" Then
Dim insMail As New System.Net.Mail.MailMessage(New MailAddress(strFm), New MailAddress(strTo))
With insMail
For Each y As String In strToREST.Split(";")
If y = "" Then
Else
.CC.Add(y)
End If
Next
.Subject = subject
.Body = Greet + "<br />" + "<br />" + bodyTxt.Text + "<br />" + PName + "- " + PNum + "<br />" + "<br />" + "The Required Date was: " + ReqDateNow.Text + " ,The Required Date is now: " + ReqDateAfter.Text + "<br />" + "Regards," + "<br />" + "<br />"
.IsBodyHtml = True
Sig = Uname
If Sig.ToLower = "djones" Then Sig = "GBennett"
Dim source As String = Path + Sig + ".jpg"
If System.IO.File.Exists(source) = False Then
Msgbox.ShowAlertMessage("Signature not found, but the email was still sent.")
Else
Dim lr As New LinkedResource(source)
lr.ContentId = "Signature"
Dim htmlView As AlternateView = AlternateView.CreateAlternateViewFromString(insMail.Body + "<img width=""500"" height=""400"" src=cid:Signature>", Nothing, "text/html")
htmlView.LinkedResources.Add(lr)
.AlternateViews.Add(htmlView)
End If
End With
Dim smtp As New System.Net.Mail.SmtpClient
smtp.EnableSsl = False
smtp.Host = "192.168.50.2"
smtp.Port = 25
smtp.UseDefaultCredentials = True
smtp.Send(insMail)
I have searched around online and i cannot find anything to help me, I was wondering if i could get some assistance with this, thank you in advance.
Any help at all would be appreciated.

I would suggest converting the gridview to Html using a function such as:
Private Function GridViewToHtml(ByVal gv As GridView) As String
Dim sb As New StringBuilder
Dim sw As New StringWriter
Dim hw As New HtmlTextWriter(sw)
gv.RenderControl(hw)
Return sb.ToString()
End Function
Then you could call this function and add it to the body of your email.

Related

How to upload xls file's data to SQL Server in devexpress popup control?

I have enquiry on how to insert xls file data into SQL Server. The upload button, and gridview control are placed inside the devexpress popup control and the code works without the popup control but doesn't work with popup control. When I inserted the xls file and clicked the upload button, the label display showed "Please select a file to upload!" although I have did this.
ASP.NET markup:
<dx:ASPxPopupControl ID="popupControl" ClientInstanceName="popupControl"
AllowDragging="true" ShowOnPageLoad="false" runat="server" AllowResize="true" >
<ContentCollection>
<dx:PopupControlContentControl runat="server">
<div class="flexs">
<dx:ASPxUploadControl ID="XXUpload" runat="server" UploadMode="Auto" ValidationSettings-AllowedFileExtensions=".xls" width="500px" >
</dx:ASPxUploadControl>
<dx:ASPxLabel ID="Label2" runat="server" Text=""></dx:ASPxLabel>
<dx:ASPxButton ID="DataUpload" runat="server" Text="UPLOAD" OnClick="DataUpload_Click ">
</dx:ASPxButton>
<dx:ASPxGridView ID="UpdateSplitGrid" ClientIDMode="Static" ClientInstanceName="UpdateSplitGrid" runat="server" Width="200%" DataSourceID="dtSource2" Theme="DevEx" >
.....
</dx:ASPxGridView>
</div>
</dx:PopupControlContentControl>
</ContentCollection>
</dx:ASPxPopupControl>
Vb.net code:
Function uploadExcel1(filePath As String) As String
Dim str As String = ""
Dim namestr1 As String = XXUpload.UploadedFiles.ToArray(0).FileName.ToString
If namestr1 <> "" Then
If Not XXUpload.UploadedFiles.ToArray(0).IsValid Then
str = "Fail to Upload " + namestr1
Else
XXUpload.UploadedFiles.ToArray(0).SaveAs(filePath)
str = " Successfully Uploaded!"
End If
Else
str = "Please select a File to upload!"
End If
Return str
End Function
Function getDTe(filename As String, ByVal sql As String) As DataTable
Dim dt As New DataTable()
Dim connectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filename + ";Extended Properties='Excel 8.0;HDR=YES;IMEX=1;';"
Dim connection As New OleDbConnection(connectionString)
Dim adapter As New OleDbDataAdapter(sql, connection)
adapter.Fill(dt)
Return dt
End Function
Protected Sub DataUpload_Click(sender As Object, e As EventArgs)
Dim filepath As String = "C:\New folder\" + XXUpload.UploadedFiles.ToArray(0).FileName.ToString + ".xls"
Dim msg As String = uploadExcel1(filepath)
Label2.Text = msg
If msg.Contains("Successfully") Then
Dim sql As String = "select * from [Sheet1$]"
Dim dt As New DataTable
dt = getDTe(filepath, sql)
If dt.Rows.Count > 0 Then
Dim i As Integer = 0
Dim colname() As String = {"LotID", "Split_Cat", "Engr_Time", "PLANDESC", "STEPSEQ", "EQPTYPE", "PPID", "STEPDESC", "Split", "Recipe", "F11", "F12", "F13", "F14", "F15", "F16", "F17", "F18", "F19", "F20", "F21", "F22"}
For Each dc As DataColumn In dt.Columns
If dc.ColumnName.ToString <> colname(i) Then
Label2.Text = " File is not in correct format - Details: " + dc.ColumnName.ToString
Return
End If
i = i + 1
Next
For Each dr In dt.Rows
Try
Dim LotID As String = dr("LotID").ToString
Dim Split_Cat As String = dr("Split_Cat").ToString
Dim Engr_Time As String = dr("Engr_Time").ToString
Dim PLANDESC As String = dr("PLANDESC").ToString
Dim STEPSEQ As String = dr("STEPSEQ").ToString
Dim EQPTYPE As String = dr("EQPTYPE").ToString
Dim PPID As String = dr("PPID").ToString
Dim STEPDESC As String = dr("STEPDESC").ToString
Dim Split As String = dr("Split").ToString
Dim Recipe As String = dr("Recipe").ToString
Dim a As String = dr("F11").ToString
Dim b As String = dr("F12").ToString
Dim c As String = dr("F13").ToString
.............
Dim insertsql2 As String = ""
insertsql2 += "insert into PTHOME.dbo.SplitTable (LotID,Split_Cat,Engr_Time,PLANDESC,STEPSEQ,EQPTYPE,PPID,STEPDESC,Split,Recipe,[1],[2],[3]) values "
insertsql2 += "('" + LotID + "','" + Split_Cat + "','" + Engr_Time + "','" + PLANDESC + "','" + STEPSEQ + "','" + EQPTYPE + "','" + PPID + "','" + STEPDESC + "','" + Split + "','" + Recipe + "', "
insertsql2 += " '" + a + "','" + b + "','" + c + "') "
Dim conn As New SqlConnection(connString)
Dim cmd As New SqlCommand(insertsql2, conn)
conn.Open()
Dim res As Integer = cmd.ExecuteNonQuery
conn.Close()
If res > 0 Then
Label2.Text = res.ToString + " Records Successfully Uploaded! "
UpdateSplitGrid.DataBind()
Else
Label2.Text = " NO Records Uploaded! "
End If
Catch ex As Exception
Label2.Text = " Failed to Upload, pls check your data or file format ! "
End Try
Next
End If
End If
End Sub
When i upload the xls file, the label displayed
"Please select a File to upload!", anything i missed out in the popup control? Please guide me on this, thanks in advance.
EDIT*
I have changed the upload control to this and it no longer showed the "Please select a File to upload!" now there is another error showed "File is not in correct format - Details: F11", the error seems to lie on the column [1]-[12], but the excel column is 1-12 and the column in database is [1]-[12].how can i achieve this? ( Solved by changing the number to F11 and so on.)
<dx:ASPxUploadControl runat="server" ClientInstanceName="XXUpload" ID="XXUpload" Width="600px" >
<ValidationSettings AllowedFileExtensions=".xls"></ValidationSettings>
</dx:ASPxUploadControl>
Edit 2*
The data has uploaded successfully to sql server and now another problem occurred, the data uploaded to sql server wont show in the UpdateSplitGrid gridview although i have declared this in my code.
If res > 0 Then
Label2.Text = res.ToString + " Records Successfully Uploaded! "
UpdateSplitGrid.DataBind()
Your ASPxUploadControl, the XXUpload, doesn't have any function to execute when upload is complete. I suggest you use OnFileUploadComplete event with FileUploadMode="OnPageLoad".

Read Outlook messages in ASP.NET catches out of bounds error

I am trying to integrate MS outlook in asp.net. My code(below) catches out of bounds error. What am I doing wrong? am I not getting the inbox messages properly? Thanks in advance
EDIT: based on my debugging
inbox = name.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox)
Returns nothing. I am not sure why
Dim ol As Outlook.Application = New Outlook.Application
Dim name As Microsoft.Office.Interop.Outlook._NameSpace
Dim inbox As Microsoft.Office.Interop.Outlook.MAPIFolder
Dim item As Microsoft.Office.Interop.Outlook.PostItem
Dim subF As Microsoft.Office.Interop.Outlook.MAPIFolder
Try
name = ol.GetNamespace("MAPI")
name.Logon(Nothing, Nothing, False, False)
inbox = name.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderInbox)
subF = inbox.Folders(0)
Dim ctr As Integer
For ctr = 0 To subF.Items.Count
item = subF.Items(ctr)
Label1.Text += "Subject: " + item.Subject + "<br/>"
Label1.Text += "Date: " + item.SentOn.ToLongDateString() + " " + item.SentOn.ToLongTimeString() + "<br/>"
Label1.Text += "Category: " + item.Categories + "<br/>"
Label1.Text += "Body: " + item.Body + "<br/>"
Label1.Text += "HtmlBody: " + item.HTMLBody + "<br/>"
Next
Catch ex As System.Runtime.InteropServices.COMException
End Try
Check your index base
Change
For ctr = 0 To subF.Items.Count
to
For ctr = 1 To subF.Items.Count
Or possibly to
For ctr = 0 To subF.Items.Count - 1
...if Microsoft finally got rid of the base-1-indexing scheme with the Outlook objects.
Make sure there's actually a folder!
Check to ensure that the inbox contains subfolders. If not, use the inbox itself.
inbox = name.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderInbox)
If inbox.Folders.Count > 0 Then
subf = inbox.Folders(1)
Else
subf = inbox
End If

Error when sending emails with asp.net ('At least one of the fields From or To are required')

I'm trying to send emails using asp.net. Here's what i've got so far:
objEmail = New Email
With objEmail
If (IsDBNull(rsConfigEmail.Fields("smtp").Value)) Then
Dim sSmtp As String = CarregarSMTP()
If (sSmtp = "") Then
'Throw New Exception("Não existem SMTPs cadastrados.")
MsgBox.Disparar("Erro ao enviar email. SMTP não cadastrado.")
Exit Sub
End If
.SMTP = sSmtp
Else
.SMTP = rsConfigEmail.Fields("smtp").Value
End If
.Remetente = Trim(rsConfigEmail.Fields("Remetente").Value)
.Titulo = Trim(rsConfigEmail.Fields("assunto").Value)
.Destinatario = sEmail
corpoEmail = rsConfigEmail.Fields("Mensagem").Value.ToString()
corpoEmail = corpoEmail.Replace("<guia>", sGuia)
corpoEmail = corpoEmail.Replace("<origem>", dplOrgao.SelectedItem.Text)
corpoEmail = corpoEmail.Replace("<destino>", Trim(rsDadosEmail.Fields("sigla").Value.ToString()) + " - " + Trim(rsDadosEmail.Fields("descricao").Value.ToString()))
Dim tabela As String = ""
tabela += "<table width='100%'><tr><td>Número Processo</td><td>Número Documento Origem</td><td>Assunto</td><td>Complemento</td><td>Interessado</td><td>Parecer</td></tr>"
Do While Not rsConfirmados.EOF
tabela += "<tr><td>" + rsConfirmados.Fields(0).Value.ToString() + "</td><td>" + rsConfirmados.Fields(1).Value.ToString() + "</td><td>" + rsConfirmados.Fields(2).Value.ToString() + "</td><td>" + rsConfirmados(3).Value.ToString() + "</td><td>" + rsConfirmados.Fields(4).Value.ToString() + "</td><td>" + rsConfirmados.Fields(5).Value.ToString() + "</td></tr>"
rsConfirmados.MoveNext()
Loop
tabela += "</table>"
corpoEmail = corpoEmail.Replace("<corpo>", tabela)
corpoEmail = corpoEmail.Replace("<total>", rsConfirmados.RecordCount.ToString())
.Mensagem = corpoEmail
.Enviar()
End With
When the 'Enviar' method is called (Send()), an exception is thrown saying that At least one of the fields 'from' or 'to' is required. But i'm setting values to these properties when i do this:
.Remetente = Trim(rsConfigEmail.Fields("Remetente").Value)
.Destinatario = sEmail
From and To fields respectively. Could it be something wrong with my smtp address?
Here's the Enviar() method in my Email class:
Public Sub Enviar()
Dim mail As MailMessage
Dim TemDestinatario As Boolean
Try
If sSMTP.Trim <> "" Then
SmtpMail.SmtpServer = sSMTP
Else
Throw New Exception("Falta o SMTP.")
End If
mail = New MailMessage
If sRemetente <> "" Then
mail.From = sRemetente
Else
Throw New Exception("Falta o Remetente.")
End If
TemDestinatario = False
If sDestinatario <> "" Then
mail.To = sDestinatario
TemDestinatario = True
End If
If sDestinatarioCCO <> "" Then
mail.Bcc = sDestinatarioCCO
TemDestinatario = True
End If
If Not TemDestinatario Then
Throw New Exception("Falta o Destino.")
End If
mail.Subject = sTitulo
mail.Body = sTexto
mail.BodyEncoding = System.Text.Encoding.UTF8
mail.BodyFormat = MailFormat.Text
If Not vetAnexo Is Nothing AndAlso UBound(vetAnexo) > 0 Then
Dim intContador As Integer
For intContador = 0 To UBound(vetAnexo) - 1
mail.Attachments.Add(New MailAttachment(vetAnexo(intContador)))
Next
End If
'se houver algum problema no envio, tenta outros SMTPs
Try
SmtpMail.Send(mail)
Catch ex As Exception
Dim cSig As Object
Dim rsSmtp As ADODB.Recordset
cSig = CreateObject("prSIG.cSMTP")
rsSmtp = cSig.ConsultarSMTP()
If (rsSmtp.RecordCount > 0) Then
Dim bEnviado As Boolean
'pega todos menos o que ja tentou, e ordena pela 'ordem'
rsSmtp.Filter = "smtp <> '" + SmtpMail.SmtpServer + "'"
rsSmtp.Sort = "ordem"
rsSmtp.MoveFirst()
Do While Not rsSmtp.EOF And Not bEnviado
Try
SmtpMail.SmtpServer = rsSmtp.Fields("smtp").Value
SmtpMail.Send(mail)
bEnviado = True
Catch
End Try
rsSmtp.MoveNext()
Loop
If (Not bEnviado) Then
Throw ex
End If
Else
Throw ex
End If
End Try
Catch ex As Exception
If ex.Message = "Could not access 'CDO.Message' object." Then
Throw New Exception("Falha ao acessar o SMTP (" + sSMTP + ").")
Else
Throw ex
End If
Finally
mail = Nothing
End Try
End Sub
Both of my SMTP adresses were not working. Had to ask for another STMP address. Now it works.

How to File Upload csv to SQL database on intranet VB.NET site

I am having problems uploading CSV files to my SQL Database. I am trying to achieve this through the File Upload technique on an intranet site. The intranet site is for me and another user to have the ability to file upload these CSVs (in case one of us is out).
I've used the following;
Dim errorList As String = String.Empty
Dim returnValue As Integer = 0
Dim SQLCon As New SqlClient.SqlConnection
Dim SQLCmd As New SqlClient.SqlCommand
Dim ErrString As String
Dim countRecs As Integer = 0
Dim batchid As Integer = GetNextBatchNumber("PartsImport")
Using tf As New TextFieldParser(fileandpath)
tf.TextFieldType = FileIO.FieldType.Delimited
tf.SetDelimiters(",")
SQLCon.ConnectionString = ConfigurationManager.ConnectionStrings("DB00ConnectionString").ConnectionString
SQLCon.Open()
SQLCmd.CommandType = CommandType.Text
SQLCmd.Connection = SQLCon
Dim recAdded As String = Now.ToString
Dim row As String()
While Not tf.EndOfData
Try
row = tf.ReadFields()
Dim x As Integer = 0
If countRecs <> 0 Then
Try
SQLCmd.CommandText = "insert into [Base].[PartsImport] " _
+ " (ID,PartName,PartID,Price,ShipAddress) " _
+ " values ('" + row(0) + "','" + row(1) + "','" _
+ row(2) + "','" + row(3) + "','" + row(4) + "')"
SQLCmd.ExecuteNonQuery()
Catch ex As Exception
ErrString = "Error while Creating Batch Record..." & ex.Message
End Try
End If
Catch ex As MalformedLineException
errorList = errorList + "Line " + countRecs + ex.Message & "is not valid and has been skipped." + vbCrLf
End Try
countRecs = countRecs + 1
End While
SQLCon.Close()
SQLCon.Dispose()
SQLCmd.Dispose()
When I click the form button to upload, it gives me a success message but when I look in the actual table, it is still blank.
Any ideas? Appreciate it
Thanks
Dave
private void UploaddataFromCsv()
{
SqlConnection con = new SqlConnection(#"Data Source=local\SQLEXPRESS;Initial Catalog=databaseName;Persist Security Info=True;User ID=sa");
string filepath = "C:\\params.csv";
StreamReader sr = new StreamReader(filepath);
string line = sr.ReadLine();
string[] value = line.Split(',');
DataTable dt = new DataTable();
DataRow row;
foreach (string dc in value)
{
dt.Columns.Add(new DataColumn(dc));
}
while ( !sr.EndOfStream )
{
value = sr.ReadLine().Split(',');
if(value.Length == dt.Columns.Count)
{
row = dt.NewRow();
row.ItemArray = value;
dt.Rows.Add(row);
}
}
SqlBulkCopy bc = new SqlBulkCopy(con.ConnectionString, SqlBulkCopyOptions.TableLock);
bc.DestinationTableName = "[Base].[PartsImport]";
bc.BatchSize = dt.Rows.Count;
con.Open();
bc.WriteToServer(dt);
bc.Close();
con.Close();
}
Try catching a SqlException and seeing if there is a formatting issue with your request. If you have an identity column on the ID, you shouldn't set it explicitly from your CSV as that may cause a potential duplicate to be submitted to your database. Also, I suspect that you have some type mismatches in your types since you are putting quotes around what appear to be number columns. I would recommend you consider replacing the string concatenation in your query to using parameters to avoid issues with improper quote escaping (ie. what would happen if you have a PartName of "O'Reily's auto parts"?) Something like this may work. Note, I've been in the LINQ world for so long, I may have some syntax errors here.
SQLCon.ConnectionString = ConfigurationManager.ConnectionStrings("DB00ConnectionString").ConnectionString
SQLCon.Open()
SQLCmd.CommandType = CommandType.Text 'Setup Command Type
SQLCmd.CommandText = "insert into [Base].[PartsImport] " _
+ " (PartName,PartID,Price,ShipAddress) " _
+ " values (#PartName, #PartID, #Price, #ShipAddress)'"
Dim partNameParam = New SqlParameter("#PartName", SqlDbType.VarChar)
Dim partIdParam = New SqlParameter("#PartID", SqlDbType.Int)
Dim partPriceParam = New SqlParameter("#Price", SqlDbType.Money)
Dim partAddressParam = New SqlParameter("#ShipAddress", SqlDbType.VarChar)
SQLCmd.Parameters.AddRange( {partNameParam, partIdPAram, partPriceParam, partAddressParam})
SQLCmd.Connection = SQLCon
Dim recAdded As String = Now.ToString()
Dim row As String()
While Not tf.EndOfData
Try
row = tf.ReadFields()
Dim x As Integer = 0
If countRecs <> 0 Then
Try
partNameParam.Value = row[1]
partIdParam.Value = row[2]
partPriceParam.Value = row[3]
partAddressParam.Value = row[4]
SQLCmd.ExecuteNonQuery()
Catch ex As Exception
ErrString = "Error while Creating Batch Record..." & ex.Message
End Try
End If
Catch ex As MalformedLineException
errorList = errorList + "Line " + countRecs + ex.Message & "is not valid and has been skipped." + vbCrLf
End Try
countRecs = countRecs + 1
End While
SQLCon.Close() 'TODO: Change this to a Using clause
SQLCon.Dispose()
SQLCmd.Dispose() 'TODO: Change this to a Using clause
With all that being said, if you have any significant number of items to insert, the bulk copy example is a better answer.

sending email in from asp.net page

I want to add this to my email body and i want it to look like this but it doesnt work.
Tour: lotour.text
Date: loddate.text
Party: lolnumparty.text
first name: locfname.text
last name: loclname.text
as you see i want them right after another and it doesnt work when i use a </br>
this is my email body.
objEmail.Body = "There was a booking rquest made by " & Request.QueryString("comp") & " to see more details click the link " + x
this is my full code
If Page.IsValid And ValidateCCNumber(cardnumber.Text) = True Then
SqlDataSource1.Insert()
Dim x As String
x = "http://www.clubabc.com/bookingrequest/confirm.aspx?date=" & HttpUtility.UrlEncode(now.Text) & "&tfname=" & HttpUtility.UrlEncode(p1fname.Text) & "&tlname=" & HttpUtility.UrlEncode(p1lname.Text) & "&comp=" & HttpUtility.UrlEncode(Request.QueryString("comp") & "&land=" & HttpUtility.UrlEncode(land.Text))
Dim objEmail As New MailMessage()
objEmail.To = "cnna#BC.com"
objEmail.From = "page#bc.com"
objEmail.Cc = memail.Text
objEmail.Subject = "Booking for " + p1fname.Text + " " + p1lname.Text + " made by " & Request.QueryString("comp")
objEmail.Body = "There was a booking rquest made by " & Request.QueryString("comp") & " to see more details click the link " + x
SmtpMail.SmtpServer = "mail.bc.com"
Try
SmtpMail.Send(objEmail)
Catch exc As Exception
Response.Write("Send failure: " + exc.ToString())
End Try
Response.Redirect("http://www.clubabc.com/bookingrequest/confirm.aspx?date=" + now.Text + "&tfname=" + p1fname.Text + "&tlname=" + p1lname.Text + "&comp=" + Request.QueryString("comp") & "&land=" & HttpUtility.UrlEncode(land.Text))
ElseIf ValidateCCNumber(cardnumber.Text) = False Then
invalidcard.Visible = True
End If
I guess you are searching for (MSDN):
Environment.NewLine
The <br> tag will only work in HTML Emails.
Update
This would be a very simple example, how you could use Environment.NewLine:
Imports System
Class Sample
Public Shared Sub Main()
Dim firstName As String = "John"
Dim lastName As String = "Doe"
Dim city As String = "Brooklyn"
Console.WriteLine("First name: " + firstName + Environment.NewLine + "Last name: " + lastName + Environment.NewLine + "City: " + city + Environment.NewLine)
End Sub
End Class
Try to set IsHtml property for objEmail variable to get some more formatting possibilities.
Do not use Enviornment.NewLine, instead use vbCrLf
Environment.NewLine may only output Cr or Lf, which may cause your email to either:
a)Be blocked because it's not RFC complient
or
b)Be marked as spammy
To have new lines in email, always use CrLf.
--Dave

Resources