I am trying to download an Excel file from the server on a button click, but it is not happening. It simply executes the code but the download is not happening.
Protected Sub btn_dwnldexcel_Click(sender As Object, e As EventArgs) Handles btn_dwnldexcel.Click
Dim fileToDownload = Server.MapPath("./Data/nd_format.xls")
''Response.ContentType = "application/octet-stream"
Response.ContentType = "application/vnd.ms-excel"
Dim cd = New ContentDisposition()
cd.Inline = False
cd.FileName = Path.GetFileName(fileToDownload)
Response.AppendHeader("Content-Disposition", cd.ToString())
Dim fileData As Byte() = System.IO.File.ReadAllBytes(fileToDownload)
Response.OutputStream.Write(fileData, 0, fileData.Length)
End Sub
Any idea would be appreciated.
Instead of trying to send the data from the same page, it is better to use a generic handler which does not have the overheads of processing an aspx page.
So, if you add a new item to the project and find "Generic handler (.ashx)" (or similar), and use code like this:
Imports System.Web
Imports System.Web.Services
Imports System.IO
Public Class DownloadExcelFile
Implements System.Web.IHttpHandler
Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
Dim actualFile = Server.MapPath("~/Data/nd_format.xls")
If File.Exists(actualFile) Then
context.Response.ContentType = "application/octet-stream"
context.Response.AddHeader("content-disposition", "attachment; filename=""" & Path.GetFileName(actualFile) & """")
context.Response.TransmitFile(actualFile)
Else
context.Response.Clear()
context.Response.TrySkipIisCustomErrors = True
context.Response.StatusCode = 404
context.Response.Write("<html><head><title>File not found</title><style>body {font-family: Arial,sans-serif;}</style></head><body><h1>File not found</h1><p>Error.</p></body></html>")
context.Response.End()
End If
End Sub
ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
Get
Return False
End Get
End Property
End Class
Then you can use a hyperlink instead of a Button:
Download Excel File
(You can style the hyperlink as a button with CSS if required.)
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.
I Tried to delete blank rows from excel using the code
Dim wb As New Workbook("d:\test\book1.xls")
Dim sheets As WorksheetCollection = wb.Worksheets
Dim sheet As Worksheet = sheets(0)
sheet.Cells.DeleteBlankRows()
wb.Save("d:\test\mybook.xls")
But i am getting syntax error.Any one know the Namespace requiered to do this?
Try
ApplicationClass excel = new ApplicationClass();
Microsoft.Office.Interop.Excel.Range cellToBeDeleted = (Range)excel.Cells[rowIndex, columnIndex];
cellToBeDeleted.Delete();
Include the following namespace
using Excel = Microsoft.Office.Interop.Excel;
Try This
-Add Reference (from COM section ) Micsrosoft Excel Object Library to your project
Imports Microsoft.Office.Interop.Excel
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
delBlankRows("d:\test\book1.xls", 1)
End Sub
Private Sub delBlankRows(ByVal excelFileName As String, sheetIndex As Integer)
Dim excel As Microsoft.Office.Interop.Excel.Application = New Microsoft.Office.Interop.Excel.Application
Dim fileName = excelFileName
Dim w As Workbook = excel.Workbooks.Open(fileName)
Dim r As Range = w.Worksheets(sheetIndex).UsedRange.EntireRow.SpecialCells(XlCellType.xlCellTypeBlanks)
r.Delete()
w.Save()
w.Close()
End Sub
End Class
Hi i have a xml file on the web and i would like to scrape it to get the relevant information
<M MId="1195772" LId="34923" _LId="34921" OId="569" SId="5" KId="122" LNr="2" C0="1392715800" ML="1" HId="13106" GId="5996" W="" HN="Musfat Banyas" GN="Omyyah Idlib" HRC="" HRCi="1" GRC="" GRCi="0" Info="" S1="1-1" S2="1-0" MStan="1" OTv="" L="0" A="3" Ao="11"/>
I would like to scrape every M and get the value of HN GN S1 S2
I have tried using the below code but i dont get any values returned
Imports System.Net
Imports System.IO
Imports System.Xml
Imports HtmlAgilityPack
Partial Class Grayhounds_home
Inherits System.Web.UI.Page
' Gettodaysmatches(cominguptable, "https://www.betfair.com/sport/football?selectedTabType=TODAY", ".//div[contains(#class, 'match event-information ui-event')]", ".//span[#class='home-team-name']", ".//span[#class='away-team-name']", ".//span[#class='ui-no-score']")
Private Sub Grayhounds_home_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim webGet As New HtmlWeb() 'open the system
Dim htmlDoc As HtmlDocument = webGet.Load("http://www.futbol24.com/matchDayXml/?Day=20140218") '' get the html from the webpage
Dim coll As HtmlNodeCollection = htmlDoc.DocumentNode.SelectNodes("//m")
If coll IsNot Nothing Then
For Each div As Object In coll ' select all the divs wi
test.Text = div.Attributes("HN").Value
Next
End If
End Sub
End Class
You have better options for parsing XML files, by using .NET built-in classes : XDocument or XmlDocument. For example, using XmlDocument :
Dim doc As New XmlDocument
doc.Load("http://www.futbol24.com/matchDayXml/?Day=20140218")
Dim coll = doc.SelectNodes("//M")
For Each M As XmlNode In coll
test.Text = M.Attributes("HN").Value
Next
I want to consume my blog's RSS feed from other asp.net site. I can't get rss data. I try different methods (like HttpWebRequest) for consuming RSS feed but I always get same error.
WebException was caught.
The underlying connection was closed: An unexpected error occurred during an import operation.
What was the problem ?
feed address: http://blog.melihmucuk.com/feed/
I need post title, link and posted date.
for example :
Try
Dim reader As XmlTextReader = New XmlTextReader("http://blog.melihmucuk.com/feed/")
Dim ds As DataSet = New DataSet()
ds.ReadXml(reader) // incorrect line
Catch ex As Exception
End Try
I think, that's a simple task, but I don't know what is the problem.
Also I try this:
Try
Dim title As String
Dim link As String
Dim description As String
Dim reader = XmlReader.Create("http://blog.melihmucuk.com/feed/")//incorrect line
Dim feed = SyndicationFeed.Load(reader)
For Each item In feed.Items
title = item.Title.Text
link = item.Links(0).Uri.ToString
Next
HyperLink1.Text = title
HyperLink1.NavigateUrl = link
Label1.Text = description
Catch ex As Exception
End Try
Try this out:-
Imports System.Web
Imports System.Net
Imports System.IO
Public Class Reader
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Try
Dim rssFeed = New Uri("http://blog.melihmucuk.com/feed/")
Dim request As WebRequest = WebRequest.Create(rssFeed)
Dim response As WebResponse = request.GetResponse()
Using reader As New StreamReader(response.GetResponseStream())
Dim xdoc As XDocument = New XDocument()
xdoc = XDocument.Load(reader)
'Read the nodes and display as per your requirement.
End Using
Catch ex As Exception
End Try
End Sub
End Class
Also add this block in your web.config file:-
<configuration>
<system.net>
<defaultProxy useDefaultCredentials="true">
<proxy usesystemdefault="true"/>
</defaultProxy>
</system.net>
</configuration>