I'm exporting code to a csv file and the process terminates with Response.End() as expected and the SendEmail routine in the Finally clause is never executed. I need to run SendEmail() after Response.End and looking for suggestions. If just remove Response.End, then the csv file is never created.
Protected Sub ExportExcel(ByVal Vendor As String)
Dim MyConnection As SqlConnection
MyConnection = New SqlConnection(ConfigurationManager.ConnectionStrings("BusOpsConnectionString").ConnectionString)
Dim cmd As New SqlCommand("p_BPOTracker_ClosedReport", MyConnection)
With cmd
.CommandType = CommandType.StoredProcedure
cmd.Parameters.AddWithValue("#Vendor", SqlDbType.VarChar).Value = Vendor
cmd.Parameters.AddWithValue("#IssueStatus", SqlDbType.VarChar).Value = "Closed"
End With
Dim da As New SqlDataAdapter(cmd)
Dim myDataTable As DataTable = New DataTable()
da.Fill(myDataTable)
Dim FileDate As String = Replace(FormatDateTime(Now(), DateFormat.ShortDate), "/", "")
Dim attachmentName As String = "BPOTracker_Closed_Report_" & Vendor & "_" & FileDate & "_.csv"
Try
MyConnection.Open()
Response.Clear()
Response.ClearHeaders()
Dim writer As New CsvWriter(Response.OutputStream, ","c, Encoding.Default)
writer.WriteAll(myDataTable, True)
writer.Close()
Response.AddHeader("Content-Disposition", "attachment;filename=" & attachmentName)
Response.ContentType = "application/vnd.ms-excel"
Response.End()
Finally
If MyConnection.State <> ConnectionState.Closed Then MyConnection.Close()
MyConnection.Dispose()
MyConnection = Nothing
myDataTable.Dispose()
myDataTable = Nothing
Thread.Sleep(3000)
SendEmail(Vendor, attachmentName)
End Try
End Sub
Sub SendEmail(ByVal Vendor As String, ByVal attachmentFileName As String)
'Send Email
End Sub
The root of the issue here is that you don't have a clear way of getting the generated file as an attachment to the file. Your CSVWriter is writing directly to the HTTP Response. Instead you can write to a file location on disk, or to memory. At that point you can send the email with the file as an attachment. Then you can write the file to the response and then end the response.
Your methods could use some more breakdown. I suggest one method for generating the file, one method for sending the file to an email (you've got that one already) and another method for writing the file to the response.
Related
I need to retrieve data from the database first and then update the table with the new entry, following is my code but I am having an error:
"Invalid attempt to call Read when reader is closed."
I know I need to open the datareader by commenting dr1.close, but as soon as I did that I face an another exception:
"there is already an open datareader associated with this command which must be closed first. vb.net"
Imports System.IO
Imports System.Data.Sql
Imports System.Data.SqlClient
Imports System.Data
Partial Class Officer_Module_GST_id_password
Inherits System.Web.UI.Page
Dim sscript As String
Dim sms As New smsgw
Dim mail As New MailSender
Dim cmd As New SqlCommand
Dim ds As New DataSet
Dim dr As SqlDataReader
Dim objconn As New connectioncls
Dim name As String
Dim pid As String
Dim pwd As String
Dim email_sent As Integer
Dim email_status As String
Dim mobile As String
Dim message As String
Dim subject As String
Dim email As String
Dim mtext As String
Protected Sub validatedeal_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles validatedeal.Click
containertwo.Visible = True
txt_subject.Text = "Communication of the Provisional Identification Number and Password"
txt_mail.Text = "Instance mail"
End Sub
Protected Sub btnsendmail_Click(ByVal sender As Object, ByVal e As System.EventArgs)
objconn.openconn()
cmd.Connection = objconn.conn
cmd.CommandText = "Select Trade_name,provissional_id,access_token,reg_mobile_no,reg_email_id,email_status,isnull(no_of_email_sent,0) from Provisional_details"
Dim dr1 As SqlDataReader = cmd.ExecuteReader()
While (dr1.Read())
name = dr1(0).ToString()
pid = dr1(1).ToString()
pwd = dr1(2).ToString()
mobile = dr1(3).ToString()
email = dr1(4).ToString()
email_status = dr1(5).ToString()
email_sent = dr1(6).ToString()
subject = "subject to instance"
mtext = "new instance email"
message = "new instance message"
Try
MailSender.SendEmail("riteshbhatt93" + "#gmail.com", "rock_on", email, subject, mtext, System.Web.Mail.MailFormat.Text, "")
Try
Call sms.SendSMSUsingNICGW(mobile, message)
Catch
sscript = "<script language=javascript>alert('Message not sent!!')</script>"
Page.ClientScript.RegisterStartupScript(Me.GetType(), "Empty", sscript)
sscript = Nothing
Exit Try
Finally
End Try
Try
Call sms.SendSMSUsingMGOVGW(mobile, message)
Catch
sscript = "<script language=javascript>alert('Message not sent!!')</script>"
Page.ClientScript.RegisterStartupScript(Me.GetType(), "Empty", sscript)
sscript = Nothing
Exit Try
Finally
End Try
Catch
Dim cmd1 As New SqlCommand
cmd1.Connection = objconn.conn
cmd1.Parameters.AddWithValue("#mobile", mobile)
cmd1.Parameters.AddWithValue("#Email_status", "NO")
cmd1.CommandText = "Update Provisional_details set Email_sent = #Email_status where reg_mob_no = #mobile"
cmd1.ExecuteNonQuery()
cmd1.Parameters.Clear()
Exit Sub
Finally
End Try
dr1.Close()
Dim cmd2 As New SqlCommand
cmd2.Connection = objconn.conn
cmd2.Parameters.AddWithValue("#mobile", mobile)
cmd2.Parameters.AddWithValue("#Email_status", "YES")
cmd2.Parameters.AddWithValue("#emailsent", email_sent + 1)
cmd2.CommandText = "Update Provisional_details set email_status = #Email_status,no_of_email_sent = #emailsent where reg_mobile_no = #mobile"
cmd2.ExecuteNonQuery()
cmd2.Parameters.Clear()
End While
sscript = "<script language=javascript>alert('Your Mail has been sent to all applied dealers!!')</script>"
Page.ClientScript.RegisterStartupScript(Me.GetType(), "Empty", sscript)
sscript = Nothing
End Sub
End Class
I've pared this down to just the method that matters (like you should have done when posting the question). Updates are in the method, using comments to annotate what's going on.
Protected Sub btnsendmail_Click(ByVal sender As Object, ByVal e As System.EventArgs)
'Best practice in .Net is use a brand new connection instance for most DB calls. Really.
'Don't try to be clever and re-use one connection. Just use the same string.
Dim connString As String = "Connection String Here"
'Using block will guarantee connection closes properly, even if an exception is thrown
Using cn As New SqlConnection(connString), _
cmd As New SqlCommand("Select Trade_name,provissional_id,access_token,reg_mobile_no,reg_email_id,email_status,isnull(no_of_email_sent,0) from Provisional_details", cn), _
cn2 As New SqlConnection(connString), _
cmd2 As New SqlCommand("Update Provisional_details set email_status = #Email_status,no_of_email_sent = #emailsent where reg_mobile_no = #mobile", cn2)
'Define your parameters as early as possible, and be explicit about parameter types and lengths
' This will avoid potentially crippling performance gotchas
cmd2.Parameters.Add("#mobile", SqlDbType.NVarChar, 14)
cmd2.Parameters.Add("#Email_status", SqlDbType.VarChar, 5)
cmd2.Parameters.Add("#emailsent", SqlDbType.Int)
'Separate SQL statements in a tight loop like this is one of the few places to re-use a connection object...
' Even here, it should be a BIG RED FLAG that there's a better way to handle this whole process that avoids multiple calls to the DB.
' For example, it might be better to assume success, Update the DB accordingly in the original statement, and then only write failures back when needed
cn2.Open()
cn.Open()
dr1 As SqlDataReader = cmd.ExecuteReader()
While (dr1.Read())
'Best practice in .Net are to declare these variables in the method where you use them
Dim name As String = dr1(0).ToString()
Dim pid As String = dr1(1).ToString()
Dim pwd As String = dr1(2).ToString() 'You're not really storing passwords in plain-text are you? Please say, "No".
Dim mobile As String = dr1(3).ToString()
Dim email As String = dr1(4).ToString()
Dim email_status As String = dr1(5).ToString()
Dim email_sent As Integer = dr1.GetInt32(6) 'It's a number. You do math on it later. Get the INTEGER value
Dim subject As String = "subject to instance"
Dim mtext As String = "new instance email"
Dim message As String = "new instance message"
cmd2.Parameters("#mobile").Value = mobile
Try
MailSender.SendEmail("riteshbhatt93" + "#gmail.com", "rock_on", email, subject, mtext, System.Web.Mail.MailFormat.Text, "")
Try
' Also... the "Call" keyword is a vb6-era relic that has no purpose any more. Don't use it
sms.SendSMSUsingMGOVGW(mobile, message)
Catch
Page.ClientScript.RegisterStartupScript(Me.GetType(), "Empty", "<script language=javascript>alert('Message not sent!!')</script>")
'Don't set values to "Nothing" to free them in VB.Net.
'It doesn't help the way it used to in vb6/vbscript, and can actually be HARMFUL in rare cases in .Net
End Try
' Do you really mean to try both gateways, even if the first succeeds?
' Because that's what the original code is doing.
Try
sms.SendSMSUsingNICGW(mobile, message)
Catch
Page.ClientScript.RegisterStartupScript(Me.GetType(), "Empty", "<script language=javascript>alert('Message not sent!!')</script>")
'No need to call Exit Try here,
' and no need for an empty Finally section
End Try
Catch
cmd2.Parameters("#emailsent") = email_sent
cmd2.Parameters("#Email_status") = "NO"
cmd2.ExecuteNonQuery()
End Try
cmd2.Parameters("#Email_status").Value = "YES"
cmd2.Parameters("#emailsent").Value = email_sent + 1
cmd2.ExecuteNonQuery()
End While
End Using
End Sub
I have an asp.net application which allows user to download PDF files. but instead of downloading it, the browser opens the file with unreadable block characters.
Download Code
Protected Sub btn_dwnd_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btn_dwnd.Click
cn.Open()
cmd.CommandText = "Select * from Syllabus where file_name ='" & txtdwd_file.Text & "'"
cmd.Connection = cn
dr = cmd.ExecuteReader
Do While dr.Read
Response.WriteFile(dr("file_name"))
Loop
cn.Close()
End Sub
I am trying to download my uploaded pdf file in my project's root directory D:\OLMS when I click download unreable characters opens up in browser (square characters). I think it opens up pfd file in browser
Upload Code
Protected Sub btnadd_sylbus_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnadd_sylbus.Click
Dim extension As String = System.IO.Path.GetExtension(FileUpload_sylbus.PostedFile.FileName).ToLower()
Dim Type As String = Nothing
If (extension = ".pdf") Then
Dim strFileNamePath As String
Dim strFileNameOnly As String
strFileNamePath = FileUpload_sylbus.PostedFile.FileName
strFileNameOnly = Path.GetFileName(strFileNamePath)
Dim newFileNamePath As String = Path.Combine("D:\OLMS", strFileNameOnly)
Dim br As New BinaryReader(FileUpload_sylbus.PostedFile.InputStream)
FileUpload_sylbus.PostedFile.SaveAs(newFileNamePath)
cmd.CommandText = "INSERT into Syllabus(sylbus_id, sylbus_name, file_name, content) values(#id,#name,#file,#cont)"
cmd.Connection = cn
cmd.Parameters.Add("#id", txtsylbus_id.Text)
cmd.Parameters.Add("#name", txtsylbus_name.Text)
cmd.Parameters.Add("#file", FileUpload_sylbus.FileName)
cmd.Parameters.Add("#cont", br.ReadBytes(FileUpload_sylbus.PostedFile.ContentLength))
cmd.ExecuteNonQuery()
cn.Close()
lbladd_sylbus.Visible = True
lbladd_sylbus.Text = "File Upload Success."
txtsylbus_id.Text = Nothing
txtsylbus_name.Text = Nothing
Else
lbladd_sylbus.Visible = True
lbladd_sylbus.Text = "Not a Valid file format"
End If
End Sub
Thanx guys it worked :D
Response.ClearHeaders()
Response.ClearContent()
Response.ContentType = "application/octet-stream"
Response.Charset = "UTF-8"
Response.AddHeader("content-disposition", "attachment; filename=" & dr("file_name"))
Response.WriteFile("D:\OLMS\" & dr("file_name"))
Response.End()
The code I'm troubleshooting exports a Crystal Report ReportDocument to Excel. Most of the time, the export works just fine. Unfortunately for some datasets, the ExportToHttpResponse method never returns and causes the app to hang. Eventually there is a Thread was being aborted exception along with a request timeout.
Here is the line that hangs:
reportDocument.ExportToHttpResponse(ExportFormatType.Excel,Response,True, fileName);
I also tried using ExportToStream from here which also hangs:
System.IO.Stream myStream;
byte[] byteArray;
myStream = boReportDocument.ExportToStream (ExportFormatType.PortableDocFormat);
I have tried different export formats, restarting IIS, etc. There seems to be a size limit or perhaps specific data scenarios that cause these methods to hang. Any workarounds or explanations for this behavior? Thanks!
Try this:
Public Shared Sub ExportDataSetToExcel(ByVal ds As DataTable, ByVal filename As String)
Dim response As HttpResponse = HttpContext.Current.Response
response.Clear()
response.Buffer = True
response.Charset = ""
'response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
response.ContentType = "application/vnd.ms-excel"
'response.AddHeader("Content-Disposition", "attachment;filename=""" & filename & ".xls")
Using sw As New StringWriter()
Using htw As New HtmlTextWriter(sw)
Dim dg As New DataGrid()
dg.DataSource = ds
dg.DataBind()
dg.RenderControl(htw)
response.Charset = "UTF-8"
response.ContentEncoding = System.Text.Encoding.UTF8
response.BinaryWrite(System.Text.Encoding.UTF8.GetPreamble())
response.Output.Write(sw.ToString())
response.[End]()
End Using
End Using
End Sub
and in your viewer add :
DT = New DataTable
DT = (Your Method)
ExportDataSetToExcel(DT, "ExportedReport")
also add :
Protected Sub Page_Unload(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Unload
ReportObject.Close()
ReportObject.Dispose()
End Sub
So report would not add restrictions on the number of loaded reports.
I using ASP.net program and SQL database
and I want to upload various files to the database
I used this code to do that, but it does upload the file twice in database
Imports System.Data
Imports System.Data.SqlClient
Imports System.IO
Partial Class Document
Inherits System.Web.UI.Page
Public Function InsertUpdateData(ByVal cmd As SqlCommand) As Boolean
'Dim strConnString As String = System.Configuration.ConfigurationManager.ConnectionStrings("conString").ConnectionString
Dim con As New SqlConnection("Data Source=SON\SQLDB;Initial Catalog=myDB;Integrated Security=True")
cmd.CommandType = CommandType.Text
cmd.Connection = con
Try
con.Open()
cmd.ExecuteNonQuery()
Return True
Catch ex As Exception
Response.Write(ex.Message)
Return False
Finally
con.Close()
con.Dispose()
End Try
End Function
Protected Sub btnUpload_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnUpload.Click
' Read the file and convert it to Byte Array
Dim filePath As String = FileUpload1.PostedFile.FileName
Dim filename As String = Path.GetFileName(filePath)
Dim ext As String = Path.GetExtension(filename)
Dim contenttype As String = String.Empty
'Set the contenttype based on File Extension
Select Case ext
Case ".doc"
contenttype = "application/vnd.ms-word"
Exit Select
Case ".docx"
contenttype = "application/vnd.ms-word"
Exit Select
Case ".xls"
contenttype = "application/vnd.ms-excel"
Exit Select
Case ".xlsx"
contenttype = "application/vnd.ms-excel"
Exit Select
Case ".jpg"
contenttype = "image/jpg"
Exit Select
Case ".png"
contenttype = "image/png"
Exit Select
Case ".gif"
contenttype = "image/gif"
Exit Select
Case ".pdf"
contenttype = "application/pdf"
Exit Select
End Select
If contenttype <> String.Empty Then
Dim fs As Stream = FileUpload1.PostedFile.InputStream
Dim br As New BinaryReader(fs)
Dim bytes As Byte() = br.ReadBytes(fs.Length)
'insert the file into database
Dim strQuery As String = "insert into ArchivedFile" _
& "(Name, contenttype, Data )" _
& " values (#Name, #ContentType, #Data)"
Dim cmd As New SqlCommand(strQuery)
cmd.Parameters.Add("#Name", SqlDbType.VarChar).Value = filename
cmd.Parameters.Add("#ContentType", SqlDbType.VarChar).Value _
= contenttype
cmd.Parameters.Add("#Data", SqlDbType.Binary).Value = bytes
InsertUpdateData(cmd)
lblMessage.ForeColor = System.Drawing.Color.Green
lblMessage.Text = "File Uploaded Successfully"
Else
lblMessage.ForeColor = System.Drawing.Color.Red
lblMessage.Text = "File format not recognised." _
& " Upload Image/Word/PDF/Excel formats"
End If
End Sub
End Class
I do not know what the exact problem is.
I hope someone can help me.
You have the code attached to a button - any chance someone is just double-clicking on the button?
The first thing I would do is determine what part(s) of your code are running twice. Use debugging and breakpoints to determine how many times Sub btnUpload_Click runs, how many times Function InsertUpdateData is called, etc.
Also, from the context of your question I gather the double-insert is happening when you test it, not just in production. Is that accurate?
If that doesn't lead you directly to the cause of the problem, please update your question with the results so we can examine further.
My suspicion is that btnUpload_Click fires twice for some reason, if that turns out to be the case please post the markup for your button, whether it is contained in an UpdatePanel, and any client script that may be applicable.
It's me your junior programmer extraodinaire
I'm trying to display an image from my database but when I try to extract the file it only contains 6 bytes of data which causes my program to throw an error. My instructor informed me that the file is too small for an image, leading me to believe that I'm not storing it properly. I would be most gracious if someone could identify any code that might cause this to happen.
this is my function grabbing/storing the file
Protected Sub btnUpload_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnUpload.Click
Dim _image As Byte()
_image = FileUpload1.FileBytes
Dim conn As New SqlConnection
Dim cmd As New SqlCommand
Dim dr As SqlDataReader
conn.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
cmd.Connection = conn
cmd.CommandText = "Insert INTO mrg_Image(Image, UserId) VALUES('#image', #id)"
cmd.Parameters.AddWithValue("#image", FileUpload1.FileBytes)
cmd.Parameters.AddWithValue("#id", 4)
conn.Open()
dr = cmd.ExecuteReader
conn.Close()
'FileUpload1.SaveAs()
End Sub
conn.Open()
file_bytes is the variable that contains 6 bytes as oppose to a thousand+ which an image should have
Dim file_bytes As Byte() = cmd.ExecuteScalar()
Dim file_bytes_memory_stream As New System.IO.MemoryStream(file_bytes)
Dim file_bytes_stream As System.IO.Stream = DirectCast(file_bytes_memory_stream, System.IO.Stream)
Dim the_image As New System.Drawing.Bitmap(file_bytes_stream)
context.Response.ContentType = "image/jpg"
the_image.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg)
conn.Close()
End Sub
Try replacing '#image' with #image.
Also replace ExecuteReader with ExecuteNonQuery.
I wasn't aware of the FileBytes property, I've always done it so...
Dim _image(FileUpload1.PostedFile.InputStream.Length) As Byte
FileUpload1.PostedFile.InputStream.Read(_image, 0, _image.Length)
Try this
cmd.CommandText = "Insert INTO mrg_Image(Image, UserId) VALUES(#image, #id)"
cmd.Parameters.Add("#image", SqlDbType.Image)
cmd.Parameters("#image") = FileUpload1.FileBytes
cmd.Parameters.AddWithValue("#id", 4)
Edit
Removed ";" forgot this was vb
Edit2
Changed [] to (). again forgot my VB