Passing value from codebehind with asyncupload after complete? - asp.net

I'm trying to pass a value to a feedbacklabel after an asynch upload.
Protected Sub FileUploadComplete(ByVal sender As Object, ByVal e As EventArgs)
Try
Dim filename As String = System.IO.Path.GetFileName(AsyncFileUpload1.FileName)
AsyncFileUpload1.SaveAs(Server.MapPath("tmp/") + filename)
lblFeedback.Text = "File uploaded. Processing information"
'Get a StreamReader class that can be used to read the file
Dim objStreamReader As StreamReader
objStreamReader = File.OpenText(Server.MapPath("tmp/") + filename)
While objStreamReader.Peek <> -1
lblFeedback.Text += objStreamReader.ReadLine()
End While
objStreamReader.Close()
Catch ex As Exception
End Try
End Sub
The thing is I need to display how many rows have been uploaded in the database. How can I do this?

Add at the end of FileUploadComplete procedure following method call (I hope you can translate it from C# to VB):
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "feedback", string.Format("top.$get('{0}').innerText = '{1}'", lblFeedback.ClientID, lblFeedback.Text), true);

Related

Server.Execute() executes click handler again after calling asp file

I'm trying to generate a PDF using Winnovative Tools. In my click handler which fires after clicking on the "Print PDF button", I have the code below.
I expect control to resume to the printPDF_Click sub routine after calling Server.Execute() but instead it calls the printPDF_Click sub routine from scratch which causes a loop because Server.Execute() will be called again and so on.
It works as expected when I set preserveForm as False but then I lose my form data and the point is retaining it.
Private Sub printPDF_Click(sender As Object, e As EventArgs) Handles printPDF.Click
Dim outTextWriter As IO.TextWriter = New IO.StringWriter()
Server.Execute("Default_v3.aspx?isWinnovative=true", outTextWriter)
Dim baseUrl As String = HttpContext.Current.Request.Url.AbsoluteUri
Dim htmlStringToConvert As String = outTextWriter.ToString()
Dim downloadBytes As Byte() = PdfHelper.CreatePdf(htmlStringToConvert, baseUrl)
Dim response As HttpResponse = HttpContext.Current.Response
response.Clear()
response.AddHeader("Content-Type", "binary/octet-stream")
response.AddHeader("Content-Disposition", ("attachment; filename=" + (
"Rendered.pdf" + ("; size=" + downloadBytes.Length.ToString))))
response.Flush()
response.BinaryWrite(downloadBytes)
response.Flush()
response.End()
End Sub

Insert document name & document path in vb.net

I have file upload and upload link button and submit button .. so when i select file and click on upload then file name display in label and when i again click on browse file and select file and click on upload then file name again save in label so means multiple file name display in label i.e.
abc.docx
def.docx
.. and so on ..
now i try to save these files in database with different record means if these files save in database table then look like this
ID DocumentName DocumentPath
1 abc.docx /downloads/abc.docx
2 def.docx /files/def.docx
for this i try this
sp
alter procedure spupload_file
#DocumentName varchar(100),
#Doctype tinyint
as
insert into DocDownloads (DocumentID,DocumentName,DocType)
select (select max(DocumentID) from DocDownloads )+ROW_NUMBER() over(order by #DocumentName),#DocumentName,7
code
Protected Sub LinkButton1_Click(sender As Object, e As EventArgs) Handles LinkButton1.Click
uploadmultiple_file(fileUpEx.FileName)
End Sub
Public Sub uploadmultiple_file(filename As String)
If fileUpEx.HasFiles Then
For Each uploadedfile As HttpPostedFile In fileUpEx.PostedFiles
'Label4.Text = ("<b>File: </b>" + uploadedfile.FileName)
Label4.Text += String.Format("{0}<br />", uploadedfile.FileName)
Next
End If
End Sub
Protected Sub pb_Add_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles pb_submit.Click
Dim strKeyName() As String = {"DocumentName", "DocType"}
Dim objKeyVal() As Object = {Label4.Text,7}
structDb = objDataSet.ExecSP("tbl", "spupload_file", strKeyName, objKeyVal)
If structDb.intCode = 0 Then
Label5.Text = structDb.strMessage
Label5.CssClass = "error"
Exit Sub
End If
End Sub
when i try this ... this shows record in database table like
1 abc.docx<br />def.docx<br />
where as i want like this
1 abc.docx
2 def.docx
Index was outside the bounds of the array.
and how i insert also document path
any help ?
UPDATED
ok according to #Andy Reid
i try this
For Each file As HttpPostedFile In ListBox1.Items
Dim DocumentName As String = file.FileName
Dim strKeyName() As String = {"DocumentName", "DocType"}
Dim objKeyVal() As Object = {DocumentName, 7}
structDb = objDataSet.ExecSP("tbl", "spupload_file", strKeyName, objKeyVal)
Next
If structDb.intCode = 0 Then
Label5.Text = structDb.strMessage
Label5.CssClass = "error"
Exit Sub
End If
but this shows error
An exception of type 'System.InvalidCastException' occurred in DecibelCRM.dll but was not handled in user code
Additional information: Unable to cast object of type 'System.Web.UI.WebControls.ListItem' to type 'System.Web.HttpPostedFile'.
Using a listbox instead of the Label4, if dataset DocumentID is AutoIncrement
Protected Sub UploadLinkButton_Click(sender As Object, e As EventArgs) Handles UploadLinkButton.Click
uploadmultiple_file(FileUpEx.FileName)
End Sub
Public Sub uploadmultiple_file(filename As String)
If fileUpEx.HasFiles Then
'Add each PostedFile to list Box instead of using label
For Each uploadedfile As HttpPostedFile In fileUpEx.PostedFiles
FilesListBox.Items.Add(uploadedfile.FileName)
Next
End If
End Sub
Protected Sub pb_Add_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles SubmitButton.Click
Dim objDataSet As New objDataSet 'Or whatever you have
Dim DocType as Integer = 7
'Gets each file from FilesListBox to insert them into objDataSet
For Each file As HttpPostedFile In FilesListBox.Items
Dim DocumentName as String = file.FileName
'Because the DocumentID is AutoIncrement, you don't need to enter it here
objDataSet.DocDownloads.AddDocDownloadsRow(DocumentName, DocType)
Next
End Sub
This will be for the data table, it should put each PostedFile as a new Row into DocDownloads. Upon doing some more research, the full path isn't accessible due to security reasons
Your code:
Public Sub uploadmultiple_file(filename As String)
If fileUpEx.HasFiles Then
For Each uploadedfile As HttpPostedFile In fileUpEx.PostedFiles
'Label4.Text = ("<b>File: </b>" + uploadedfile.FileName)
Label4.Text += String.Format("{0}<br />", uploadedfile.FileName)
Next
End If
End Sub
Try
Public Sub uploadmultiple_file(filename As String)
If fileUpEx.HasFiles Then
Try
For Each uploadedfile As HttpPostedFile In fileUpEx.PostedFiles
Label4.Text += uploadedfile.FileName & vbCRLF
'Possibly something like: "Label4.Text += uploadedfile.FullPath & vbCRLF" for the document path
Next
Catch ex as Exception
'Whatever exception handling code
End try
End If
End Sub

parameters not passing to ssrs ServerReport - rendering report to pdf using ServerReport.Render

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.

A generic error occurred in GDI+

i am getting error A generic error occurred in GDI+
on line
bit.Save(str, Imaging.ImageFormat.Png)
please help me on this here is my full code
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If IsNothing(Request.QueryString("id")) = False Then
If Val(Request.QueryString("id")) > 0 Then
Dim dsFiles As New DataSet
dsFiles = oFileData.GetFile(Val(Request.QueryString("id")))
Dim bindata() As Byte = dsFiles.Tables(0).Rows(0).Item("FileData")
Dim str As New MemoryStream
str.Write(bindata, 0, dsFiles.Tables(0).Rows(0).Item("FileSize"))
Dim bit As Bitmap = New Bitmap(str)
Response.ContentType = ".png"
bit.Save(str, Imaging.ImageFormat.Png)
str.WriteTo(Response.OutputStream)
str.Close()
Else
Response.Write("<script language=""javascript"" type=""text/javascript"">window.close();</script>")
End If
Else
Response.Write("<script language=""javascript"" type=""text/javascript"">window.close();</script>")
End If
End Sub
There may be many reasons - may be the content of byte array is not valid image data. In fact no need to create Bitmap or MemoryStream to write image data/bytes to response stream.
Try this,
Dim bindata() As Byte = dsFiles.Tables(0).Rows(0).Item("FileData")
Response.ContentType = "image/png"
Response.BinaryWrite(bindata)
Response.Flush()
Response.End()

Java script alert msg in code behind Asp.net 3.5

How to use Java script alert msg in code behind? This message will be display after save the data.
Here is my code,
enter code here
Protected Sub Add_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Add.Click
'add new class
Dim DbClassMst = New ClassMst()
Dim dsClass As DataSet
Dim status As Integer = 0
Dim ResourceObject As Object
' 画面リソース定義
If SessionCtl.GetSession("RES_LANG").ToString = ResourceBase.LOCALE_JA Then
ResourceObject = New ResourceJa(SessionCtl.GetSession("RES_LANG"))
Else
ResourceObject = New ResourceEn(SessionCtl.GetSession("RES_LANG"))
End If
If NewClass.Text = "" Then
lblErrMsg.Text = ResourceObject.getMsg(ResourceBase.NEW_CLASS_REG)
Exit Sub
Else
'check to allow unique class
dsClass = DbClassMst.DisplayClass1(NewClass.Text)
If Trim(dsClass.Tables(0).Rows.Count > 0) Then
status = 1
End If
If dsClass.Tables(0).Rows.Count < 10 Then
If status = 0 Then
'insert class
DbClassMst.InsertClassNew(NewClass.Text, dsClass.Tables(0).Rows.Count + 1)
PopulateClassName()
NewClass.Text = ""
Dim AlertMsg As String = ""
AlertMsg = "<script language='javascript'>alert('Data has been saved');</script>"
*********Here I need alert msg.
Else
lblErrMsg.Text = ResourceObject.getMsg(ResourceBase.NEW_CLASS_EXIST)
Exit Sub
End If
Else
lblErrMsg.Text = ResourceObject.getMsg(ResourceBase.NEW_CLASS_MAX)
End If
End If
End Sub
but is not working. give me an idea.
A better way to do this is to have this as a utility method in a common class:
Friend Module MyUtilities
Public Sub Alert(ByVal page As Page, ByVal message As String)
Dim alertMessage As String = "alert('" & message & "');"
page.ClientScript.RegisterStartupScript(page.[GetType](), "showAlert", alertMessage, True)
End Sub
End Module
This can be used in a page like this:
MyUtilities.Alert(Me, "Sample alert!!!!!")
Your code looks so simpler. Hope this helps!
You should register this script to your page, so this script will be sent to the client.
Page.ClientScript.RegisterStartupScript(typeof(YourPage),
"myScripts",
"<script language='javascript'>alert('Data has been saved');</script>");
Dim someScript As String = ""
someScript = "alert('Your Leave request has been registered');"
Page.ClientScript.RegisterStartupScript(Me.GetType(), "onload", someScript)

Resources