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.
Related
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.
I have Googled on this subject and I have coded as per what I saw, but the CrystalReportViewer is empty and I am not getting any errors. I am not sure what I am doing wrong. Below is all of my code.
strSQL = "select * from MMM_vw_Rpt_Summary where BudgetID = " & Master.lblBudgetIDText
ds = CreateDataset(strSQL, "cnn_rcg_mmm", "dt_Summary")
CreateSummary(ds)
Public Shared Function CreateDataset(ByVal strSQL As String, ByVal strCNN As String, ByVal strTable As String) As DataSet
Dim strConnString As String = ConfigurationManager.ConnectionStrings(strCNN).ConnectionString
Dim da As MySqlDataAdapter
Dim ds As DataSet
Dim strReturn As String
strReturn = ""
Try
Using con As New MySqlConnection(strConnString)
Dim cmd As New MySqlCommand(strSQL, con)
con.Open()
da = New MySqlDataAdapter(cmd)
ds = New dsLifeBudget
da.Fill(ds, strTable)
Return ds
con.Close()
End Using
Catch ex As Exception
strReturn = ex.Message
End Try
End Function
Protected Sub CreateSummary(ByVal ds As DataSet)
Dim strReportPath As String = Server.MapPath("~/Reports/LB_Summary.rpt")
Dim cr As New ReportDocument
Dim strError As String = ""
Master.HideMsg()
'Verify the path to the Crystal Report's .RPT file
If Not IO.File.Exists(strReportPath) Then
Throw (New Exception("Unable to locate report file:" & vbCrLf & strReportPath))
strError = "Unable to locate report file: " & strReportPath
Master.txtMsgText = "Error creating Summary - " & strError
Master.txtMsgVisible(True)
Exit Sub
End If
crLifeBudget.HasDrillUpButton = False
crLifeBudget.Height = "300px"
crLifeBudget.Width = "500px"
'Load the Crystal report's .RPT file and pass in the DataTable
cr.Load(strReportPath)
cr.SetDataSource(ds.Tables("dt_Summary"))
crLifeBudget.ReportSource = cr
crLifeBudget.RefreshReport()
End Sub
Any help would be greatly appreciated!
Eddi Rae
Try referring the following, It could solve the problem since your code lacks thecrLifeBudget.refresh() line.
Crystal Reports empty when printed during runtime
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()
My code that sets up a ServerReport object on a web forms page, and then renders the report from SSRS to a pdf. Parameter and report name is passed by URL.
Private Sub Page_Load(sender As Object, e As EventArgs)
Dim reportname As String
'Dim parameter(0) As ReportParameter
reportname = Request("reportname").ToString
Dim v As New ReportViewer
v.ProcessingMode = ProcessingMode.Remote
Dim serverreport As New ServerReport
serverreport = v.ServerReport
serverreport.ReportServerUrl = New Uri("http://xxxxxx:80/ReportServer")
serverreport.ReportPath = "/Reports/Aramid/Sheeter/" & reportname
Select Case reportname
Case Is = "NomexBlockCard" 'Or "NomexBlockLabel" Or "NomexInternalLabel"
Dim paramList As New Generic.List(Of ReportParameter)
paramList.Add(New ReportParameter("paramBlock", Request("paramBlock").ToString, False))
serverreport.SetParameters(paramList)
Case Is = "NomexRoutingData"
Dim paramList As New Generic.List(Of ReportParameter)
paramList.Add(New ReportParameter("paramWO", Request("paramWO").ToString, False))
serverreport.SetParameters(paramList)
End Select
serverreport.ReportServerCredentials = New ReportViewerCredentials(user name here, password here, "CORE")
Save(serverreport, "C:\WebReports\" & reportname & ".pdf")
'now print
Response.Redirect("reports.ashx?fileName=" & reportname)
End Sub
Public Sub Save(ByVal sr As ServerReport, ByVal savePath As String)
Try
Dim warnings As Warning() = Nothing
Dim streamids As String() = Nothing
Dim mimeType As String = Nothing
Dim encoding As String = Nothing
Dim extension As String = Nothing
Dim deviceInfo As String
Dim bytes As Byte()
deviceInfo = "True" '<DeviceInfo><SimplePageHeaders>True</SimplePageHeaders></DeviceInfo>"
bytes = sr.Render("PDF", Nothing, mimeType, _
encoding, extension, streamids, warnings)
Using Stream As New FileStream(savePath, FileMode.Create)
Stream.Write(Bytes, 0, Bytes.Length)
Stream.Close()
End Using
Catch ex As Exception
End Try
End Sub
The report renders and saves as a pdf but the parameter value does not seem to be getting used in the report.
I have confirmed over and over that there is a value in paramBlock.
I don't know what I am doing wrong.
Am I missing a step or something?
Ryan
As your report is being rendered and saved, I'm assuming the credentials are set up correctly.
You can use the ServerReport.GetParameters function before saving the report to check what the parameters (and their values/properties) actually are.
Also, make sure you're setting every parameter required by the report (even those hidden or internal), and that every parameter value is within the allowed values of the parameter (if limits are set).
If the problem doesn't lie in passing the parameters, you might want to take a look at the report itself and how it handles its parameters.
From your recent comment about a "Parameter validation failed" error, it sounds like your issue is not with your calling code structure, but rather matching the parameters to the report definition.
The most common issue is hidden or internal parameters which you are ignoring. You need to carefully review the parameter design in SSRS Report Designer, and make sure your passed parameters comply with what it expects.
Consider following suggestions. It might help you to resolve your issue. After considering every point, you can try your code
Place following code just above the Select Case reportname statement line
serverreport.ReportServerCredentials = New ReportViewerCredentials(user name here, password here, "CORE")
You can also try changing code line
serverreport.ReportServerCredentials = New ReportViewerCredentials(user name here, password here, "CORE")
To
ServerReport.ReportServerCredentials.NetworkCredentials = System.Net.CredentialCache.DefaultCredentials
If your report has default parameters, then remove default parameters and test your code
And also remove exception handling from your method
Public Sub Save(ByVal sr As ServerReport, ByVal savePath As String)
You can try following code:
Private Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
Dim reportname As String = Request("reportname").ToString
'Dim parameter(0) As ReportParameter
Dim v As New ReportViewer
v.ProcessingMode = ProcessingMode.Remote
Dim ServerReport As ServerReport
ServerReport = v.ServerReport
serverreport.ReportServerUrl = New Uri("http://xxxxxx:80/ReportServer")
serverreport.ReportPath = "/Reports/Aramid/Sheeter/" & reportname
ServerReport.ReportServerCredentials.NetworkCredentials = System.Net.CredentialCache.DefaultCredentials
Select Case reportname
Case Is = "NomexBlockCard" 'Or "NomexBlockLabel" Or "NomexInternalLabel"
Dim paramList As New Generic.List(Of ReportParameter)
paramList.Add(New ReportParameter("paramBlock", Request("paramBlock").ToString, False))
serverreport.SetParameters(paramList)
Case Is = "NomexRoutingData"
Dim paramList As New Generic.List(Of ReportParameter)
paramList.Add(New ReportParameter("paramWO", Request("paramWO").ToString, False))
serverreport.SetParameters(paramList)
End Select
Save(serverreport, "C:\WebReports\" & reportname & ".pdf")
End Sub
Public Sub Save(ByRef sr As ServerReport, ByVal savePath As String)
Try
Dim warnings As Warning() = Nothing
Dim streamids As String() = Nothing
Dim mimeType As String = Nothing
Dim encoding As String = Nothing
Dim extension As String = Nothing
Dim deviceInfo As String
Dim bytes As Byte()
deviceInfo = "True" '<DeviceInfo><SimplePageHeaders>True</SimplePageHeaders></DeviceInfo>"
bytes = sr.Render("PDF", Nothing, mimeType, _
encoding, extension, streamids, warnings)
Using Stream As New FileStream(savePath, FileMode.Create)
Stream.Write(bytes, 0, bytes.Length)
Stream.Close()
End Using
Catch ex As Exception
End Try
End Sub
Maybe this is not the case, but I remember that Parameters value can be lost during PostBack.
So I would try a syntax like this:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Me.Page.IsPostBack Then
'your code to setup and print report
End If
End Sub
If this solution doesn't work please provide the code used in Report Definition.