Auto generated code flagging errors in VB.Net? - asp.net

I have a VB.Net project in visual studio 2010 intended to let a user upload a video and then stick it in a DB. The file is called "Media/Test.aspx.vb".
When I tried to run the code to debug, tons of errors were generated for a file called App_Web_nkhy2w0y.0.vb
I couldn't locate this file anywhere, and I certainly didn't write it, so I double clicked on the error and it opened a file with about 350 lines of (apparently) auto-generated code, and I have no clue what I did to cause it to do this. Nor do I have any idea how to fix it.
I'll admit I'm new to VB.Net, but I've never seen anything like this online so I'm in the dark.
My original code is below for the code-behind file that handles nothing more than a fileupload control, button, and label in the actual page.
Imports System.IO
Imports System.Data.SqlClient
Imports System.Data
Partial Class Media_Test
Inherits System.Web.UI.UserControl
Protected Sub TryMe_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles TryMe.Click
Dim connection As SqlConnection
'check the file
Dim buffer As Byte()
If testFile.HasFile AndAlso testFile.PostedFile IsNot Nothing AndAlso testFile.PostedFile.FileName <> "" Then
Dim file As HttpPostedFile = testFile.PostedFile
'retrieve the HttpPostedFile object
buffer = New Byte(file.ContentLength - 1) {}
Dim bytesReaded As Integer = file.InputStream.Read(buffer, 0, testFile.PostedFile.ContentLength)
'the HttpPostedFile has InputStream porperty (using System.IO;)
'which can read the stream to the buffer object,
'the first parameter is the array of bytes to store in,
'the second parameter is the zero index (of specific byte)
'where to start storing in the buffer,
'the third parameter is the number of bytes
'you want to read (do u care about this?)
If bytesReaded > 0 Then
Try
Dim connectionString As String = ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
connection = New SqlConnection(connectionString)
Dim cmd As New SqlCommand("INSERT INTO Videos (Video, Video_Name, Video_Size)" & " VALUES (#video, #videoName, #videoSize)", connection)
cmd.Parameters.Add("#video", SqlDbType.VarBinary, buffer.Length).Value = buffer
cmd.Parameters.Add("#videoName", SqlDbType.VarChar).Value = testFile.FileName
cmd.Parameters.Add("#videoSize", SqlDbType.BigInt).Value = file.ContentLength
Using connection
connection.Open()
Dim i As Integer = cmd.ExecuteNonQuery()
Label1.Text = "uploaded, " & i.ToString() & " rows affected"
End Using
Catch ex As Exception
Label1.Text = ex.Message.ToString()
End Try
End If
Else
Label1.Text = "Choose a valid video file"
End If
End Sub
End Class
And the top of the generated page is:
#ExternalChecksum("C:\Users\handcm\Documents\Visual Studio 2010\WebSites\APPS\Media\Test.aspx","{406ea660-64cf-4c82-b6f0-42d48172a799}","F31F20662F14B4894B6FBF58215628CB")
'------------------------------------------------------------------------------
' <auto-generated>
' This code was generated by a tool.
' Runtime Version:4.0.30319.296
'
' Changes to this file may cause incorrect behavior and will be lost if
' the code is regenerated.
' </auto-generated>
'------------------------------------------------------------------------------
I can post the entire file if need be, but could someone shine some light on what's going on here? I have no clue how to debug a file I didn't write or have never seen.
Edit 2: I checked the "'InitializeCulture' is not a member of 'ASP.media_test_aspx" error and it usually is a discrepancy between the class being inherited on the aspx page not being the correct as in the aspx.vb file. However, in this case, there isn't a discrepancy as it's the correct file.
Edit: Some of the error messages I am getting:
Error 4 'GetWrappedFileDependencies' is not a member of 'ASP.media_test_aspx'. C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\apps\f1b28c0f\bab8f810\App_Web_nkhy2w0y.0.vb 103
Error 2 Class 'media_test_aspx' must implement 'ReadOnly Property IsReusable As Boolean' for interface 'System.Web.IHttpHandler'. Implementing property must have matching 'ReadOnly' or 'WriteOnly' specifiers. C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\apps\f1b28c0f\bab8f810\App_Web_nkhy2w0y.0.vb 84
Error 10 'ProcessRequest' is not a member of 'Media_Test'. C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\apps\f1b28c0f\bab8f810\App_Web_nkhy2w0y.0.vb 342
Error 1 'InitializeCulture' is not a member of 'ASP.media_test_aspx'. C:\Users\handcm\Documents\Visual Studio 2010\WebSites\APPS\Media\Test.aspx 1
I don't even know what the last one is referring to, as there is definitely not an "Initialize Culture" on the page.

Related

Print SSRS Report from Code (asp.net)

I have found good information on how to automatically download a file to the client advertised as a solution of how to print using code
(https://forums.asp.net/t/1233841.aspx?How+do+I+print+from+Reporting+Services+AUTOMATICALLY+in+VB+Net+web+app+)
but what I need to do is have the code print the document without the user interacting.
From what I have found it appears this can not be done as one might casually think. ReportViewer for example does not have a 'print' method.
The only two solutions appears to be to use ProcessStart (which then means saving the file to the file system before printing which I dont want to do)
or maybe (will be researching this today) create a subscription using code and then delete it later.
You are not able to print a report directly from your asp.net page. The reason for this is security. If it allowed you to send a file through the network and onto the clients computer, and then search the computer for a printer, this could cause major security issues. The report viewer does have a print icon, but this disappears when you deploy the project and run the page remotely. I have faced the same issue in the past and found it best to just export the report to say PDF and allow the user to Download it. I have used the below code to accomplish this task in the past:
Private Sub CreatePDFMatrix(fileName As String)
' ReportViewer1.LocalReport.DataSources.Clear()
Dim adapter As New ReportDataSetTableAdapters.vwPrintTagsTableAdapter
Dim table As New ReportDataSet.vwPrintTagsDataTable
Dim month = MonthName(Date.Today.Month)
Dim year = Date.Today.Year
Dim p(1) As ReportParameter
Dim warnings() As Warning
Dim streamIds As String()
Dim mimeType As String = String.Empty
Dim encoding As String = String.Empty
Dim extension As String = String.Empty
Dim adpt2 As New ReportDataSetTableAdapters.vwPrintTagsTableAdapter
adapter.FillForMainReport(table, DropDownList1.SelectedValue, g_Company, g_Division)
Me.ReportViewer1.LocalReport.DataSources.Add(New ReportDataSource("DataSet1", CType(table, DataTable))) 'Add(New ReportDataSource("ReportingData", CType(table, DataTable)))
Me.ReportViewer1.DataBind()
Dim viewer = ReportViewer1
viewer.ProcessingMode = ProcessingMode.Local
viewer.LocalReport.ReportPath = "Report1.rdlc"
p(0) = New ReportParameter("MonthYear", month & "-" & year)
Dim check = DropDownList1.SelectedValue
ReportViewer1.LocalReport.SetParameters(p(0))
p(1) = New ReportParameter("Location", DropDownList1.SelectedValue)
ReportViewer1.LocalReport.SetParameters(p(1))
Try
Dim bytes As Byte() = viewer.LocalReport.Render("PDF", Nothing, mimeType, encoding, ".pdf", streamIds, warnings)
Response.Buffer = True
Response.Clear()
Response.ContentType = mimeType
Response.AddHeader("content-disposition", Convert.ToString((Convert.ToString("attachment; filename=") & fileName) + ".") & extension)
Response.BinaryWrite(bytes)
' create the file
Response.Flush()
Catch ex As Exception
Debug.Print(ex.ToString)
End Try
End Sub

Download PDF using Response on ASPX Page only working in Page_Load

I've seen several questions relating to downloading a PDF from a Web browser using Response, but none seem to fit the mysterious issue I'm having.
I am working on a project that requires the user to be able to click a button (btnPDF) to instantly download a PDF of a Telerik report with a specific "ID" string to the Downloads folder. This process was originally located in an ASPX Page on an IIS separate from where the button is located. When btnPDF was clicked, I used Response.Redirect to download the PDF through that page. The code to download the PDF looked like this:
Response.Clear()
Response.ContentType = result.MimeType 'this is always "application/pdf"
Response.Cache.SetCacheability(HttpCacheability.Private)
Response.Expires = -1
Response.Buffer = True
Response.AddHeader("Content-Disposition", String.Format("{0};FileName={1}", "attachment", fileName))
Response.BinaryWrite(result.DocumentBytes)
Response.End()
Note that result.DocumentBytes is a byte array containing correct bytes for the PDF.
This code worked fine. Now, instead of having the process on a separate Page in a separate project, I need to merge the process onto the same page where btnPDFis located, so that when you click btnPDF, a subroutine is called that performs the same task. I thought this would be very easy, pretty much a copy and paste. With the same code added in a new subroutine, this is what my click event handler "ButtonPDF_Click" now looks like:
Protected Sub ButtonPDF_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnPDF.Click
DownloadReportPDF(Me.RadGrid1.SelectedValue.ToString())
Dim strMessage As String = "alert('Printed PDF Sheet.');"
ScriptManager.RegisterStartupScript(Me, Me.GetType, "MyScript", strMessage, True)
End Sub
Protected Sub DownloadReportPDF(ByVal releaseMasterId As String)
'Service call to generate report source
Dim service As New TelerikReportLibrary.ReportServices.PPSReportService
Dim source As Telerik.Reporting.TypeReportSource = service.GetReportSource(releaseMasterId)
'Render PDF and download
Dim reportProcessor As New ReportProcessor()
Dim result As RenderingResult = reportProcessor.RenderReport("PDF", source, Nothing)
Dim fileName As String = result.DocumentName + "_" + releaseMasterId + "." + result.Extension
Response.Clear()
Response.ContentType = result.MimeType 'this is always "application/pdf"
Response.Cache.SetCacheability(HttpCacheability.Private)
Response.Expires = -1
Response.Buffer = True
Response.AddHeader("Content-Disposition", String.Format("{0};FileName={1}", "attachment", fileName))
Response.BinaryWrite(result.DocumentBytes)
Response.End()
End Sub
But the PDF no longer downloads. An accurate byte array is still created, but the Response portion does not result in the PDF being downloaded from the browser. I've found that putting a call to DownloadReportPDF in the Page_Load handler on the same Page successfully generates and downloads a PDF as it did before.
I can't see any reason why this isn't working, but I'm new to ASP, and I'm not great in VB. I've tried using Response.OutputStream, Response.WriteFile, and making use of a MemoryStream, among several other things that I've lost track of. I'm hoping there's something simple, maybe some sort of property of the Page or btnPDF I could be missing. Here is the markup for btnPDF, just in case:
<asp:linkButton ID="btnPDF" CssClass="btn btn-default" runat="server" Width="115px">
<i class="fa fa-file-text" title="Edit"></i> PDF
</asp:linkButton>
What could be causing such a problem? Where should I look at this point?
Let me know if more information is needed.
Thanks,
Shane
EDIT:
I experimented with setting a session variable on btnPDF_Click, and handling the PDF download on postback. Again, a valid byte array was generated, but the HttpResponse did not cause the PDF to download from the browser.
EDIT:
Building on the last edit, this tells me that calling DownloadReportPDF from Page_Load works only when IsPostBack is false. I just tested this thought, and it holds true. In the above code, if I check IsPostBack at the moment I'm trying to download the PDF, it is true. Investigating further.
Alright, I finally found a solution I'm satisfied with (though I still don't understand why I can't download the PDF using Response while IsPostBack is true).
Inspired by this thread, I put the previously posted code in an HttpHandler called PDFDownloadHandler, then used Response.Redirect in the btnPDF_Click event handler to utilize PDFDownloadHandler. This article helped me a lot on that process, as it is something I have not done before.
In case anyone else runs into this problem, here is the new PDFDownloadHandler:
Imports Microsoft.VisualBasic
Imports System.Web
Imports Telerik.Reporting
Imports Telerik.Reporting.Processing
Public Class PDFDownloadHandler
Implements IHttpHandler
Public Sub ProcessRequest(ByVal context As _
System.Web.HttpContext) Implements _
System.Web.IHttpHandler.ProcessRequest
Dim request As HttpRequest = context.Request
Dim response As HttpResponse = context.Response
Dim path As String = request.Path
If path.Contains("pps.pdfdownload") Then
Dim releaseMasterId As String = request.QueryString("ID")
If releaseMasterId IsNot Nothing Then
'Service call to generate report source
Dim service As New TelerikReportLibrary.ReportServices.PPSReportService
Dim source As Telerik.Reporting.TypeReportSource = service.GetReportSource(releaseMasterId)
'Render PDF and save
Dim reportProcessor As New ReportProcessor()
Dim result As RenderingResult = reportProcessor.RenderReport("PDF", source, Nothing)
Dim fileName As String = result.DocumentName + "_" + releaseMasterId + "." + result.Extension
response.Clear()
response.ContentType = result.MimeType
response.Cache.SetCacheability(HttpCacheability.Private)
response.Expires = -1
response.Buffer = True
response.AddHeader("Content-Disposition", String.Format("{0};FileName={1}", "attachment", fileName))
response.BinaryWrite(result.DocumentBytes)
End If
End If
response.End()
End Sub
Public ReadOnly Property IsReusable() As Boolean _
Implements System.Web.IHttpHandler.IsReusable
Get
Return False
End Get
End Property
End Class
Any further insight on why the original technique did not work is greatly appreciated.

Docx File Corrupted after Upload

I have tired many things, searched the internet, and still I cannot figure out what is going on with this code. I still get that my docx files are corrupted, but when I do it with doc file everything is going great.
My Upload Code
Private Sub LbReqUploadAttachment1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles LbReqUploadAttachment1.Click
If FileUplReqAttachment1.HasFile Then
'Then save the attachment to the documents table
Dim type As String = Me.FileUplReqAttachment1.PostedFile.ContentType
Dim myFile As System.Web.HttpPostedFile = Me.FileUplReqAttachment1.PostedFile
Dim nFileLen As Integer = myFile.ContentLength
Dim myData(nFileLen) As Byte
myFile.InputStream.Read(myData, 0, nFileLen)
Dim DocDto As New DocumentsDto
DocDto.Month = Now.ToString("m")
DocDto.Year = Now.Year
DocDto.MimeType = type
DocDto.UploadedById = MyPage.LoggedOnUser.DtoUser.PersonId
DocDto.DocumentBytes = myData.ToArray
DocDto = MyPage.DelegateDocument.CreateDocumentsDto(DocDto)
'Update the order with the new document id
If Me.TbIntlFlagz.Checked Then
Item.AssetID = CStr(DocDto.DocumentID)
Else
Item.AssetID = "0"
End If
' Save Everything
SaveItem()
'Focus after postback
FileUplReqAttachment1.Focus()
End If
'Stay on order screen
Response.Redirect(String.Format("Default.aspx?i={0}&Item={1}", MyPage.DtoPage.PageID, Me.Item.Id))
End Sub
My download code:
Sub ProcessRequest(ByVal context As HttpContext) Implements ttpHandler.ProcessRequest
Dim docba As Byte() = docDto.DocumentBytes
Dim ext As String = Mime.GetExtensionFromMime(docDto.MimeType)
context.Response.ContentType = docDto.MimeType
If String.IsNullOrEmpty(ext) Then
'We can only use the attachment approach if we found a good extension based on the mime type
Else
Dim DispositionHeader As String
If Not context.Request.QueryString.Item("fn") Is Nothing Then
DispositionHeader = String.Format("attachment; filename={0}.{1}", AntiXss.UrlEncode(context.Request.QueryString.Item("fn")), ext)
Else
DispositionHeader = String.Format("attachment; filename={0}.{1}", AntiXss.UrlEncode("Document"), ext)
End If
context.Response.AppendHeader("Content-Disposition", DispositionHeader)
End If
context.Response.Expires = (60 * 24 * 1)
context.Response.OutputStream.Write(docba, 0, docba.Length)
context.Response.Flush()
docba = Nothing
End If
End Sub
I have tired these with no success:
Why are .docx files being corrupted when downloading from an ASP.NET page?
http://www.aspmessageboard.com/showthread.php?230778-Downloaded-docx-files-are-corrupted
https://social.msdn.microsoft.com/Forums/vstudio/en-US/88383fb2-03c6-49f5-afee-ce38497789bd/retrieving-docx-stored-in-sql-server-results-in-there-was-an-error-opening-the-file?forum=vbgeneral
I am uploading the file into a DB, and downloading the file by pressing a hyperlink. When I press the hyperlink and download the file. View at the file it is corrupted.
In VB, when declaring an array you give it the number of elements in the array. This is different from many languages where you specify the last index of the array.
For the code you show, you need to use
Dim myData(nFileLen - 1) As Byte
to make sure that you do not have an extra element in the array.
It appears that the .doc format is not sensitive to this, but .docx is.

Overload File Function VB.NET

I am trying to create an onclick function through ASP front end to check if a file exists, if not create it and write textbox text to it, currently getting an error on the below code saying that I cannot overload the file function, is there a better way of doing this?
UPDATE
The issue is the file is still open when trying to write to it which is throwing the error.
Please see below code:
Protected Sub Create_Click(sender As Object, e As EventArgs)
Dim txtFile As String = "E:Documents\Visual Studio 2013\Projects\SomeProject\Templates\" & FileName.Text & ".txt"
If File.Exists(txtFile) Then
Response.Write("A file of that name already exists.")
Else
File.Create(txtFile)
File.WriteAllText(eTemplate.Text)
End If
End Sub
I have also tried:
If File.Exists(txtFile) Then
Response.Write("A file of that name already exists.")
Else
System.IO.File.Create(txtFile)
Dim sw As New StreamWriter(txtFile, True)
sw.Write(eTemplate.Text)
sw.Close()
End If
You're right on the money, it is because it needs to be closed first.
I created a file stream instance first, created the file, closed it and then wrote to it. Put the below code in yours or write it out, but remember to correct the file path.
Protected Sub Create_Click(sender As Object, e As EventArgs)
Dim txtFile As String = "E:\wherever\" & FileName.Text & ".txt"
If System.IO.File.Exists(txtFile) Then
Dim message As String = "A file by this name already exists, choose another or update the existing file."
Else
Dim fs As FileStream = File.Create(txtFile)
fs.Close()
Dim sw As New StreamWriter(txtFile, True)
sw.Write(eTemplate.Text)
sw.Close()
End If
End Sub

Reading, parsing and posting data from a .csv file into a SQL database asp.net

I have the following data that basically I only need a few bits of information from:
Resource:X - Y;Z - Å;Type:(all) From Date:
07/12/2010 - To Date 07/12/2010 Sort
by:Time Include Referring
source/physician:No Footer:Default
Criteria:None
","Appointments","X,
Y","ZAssociates","Monday, July 12,
2010","Time","Patient Name","Patient
ID","Appt. Type","Ref. Source/
Physician","Phone","Type","DOB
","Z, X","Y","7/12/2010
12:00:00AM","Time","Patient
Name","Patient ID","Appt.
Type","Phone","Type","DOB "," 7:30
[snip]
The only things I need from this are:
Patients Name
Drs Name
Patients Phone Number
Appt Time
Appt Date
and the rest of the information I can discard. A customer uploads this as a .csv file (even though it really isn't as you can see) and I'd like to parse the needed information and post that to my SQL database and discard the rest. I think I can do this with a dataset but I've never built that before. The fields from the customer will always be the same and the fields I will need will always be the same.
Also, the date time has to be in the format of yyyy/mm/dd:hhmm and the phone number always has to have 512 as a prefix. Here is the code I currently have for my site:
Imports System.IO
Imports System.Data
Imports System.Data.SqlClient
Partial Class _Default
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
End Sub
Protected Sub Submit1_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Dim SaveLocation = "\\xxxWEB3\wwwroot\Webfile1\Reminders\Doug_Ancil\doug.csv"
If UploadFile(SaveLocation) Then
'the file was uploaded: now try saving it to the database
SaveToDatabase(SaveLocation)
End If
End Sub
Private Function UploadFile(ByVal SavePath As String) As Boolean
Dim fileWasUploaded As Boolean = False 'indicates whether or not the file was uploaded
'Checking if the file upload control contains a file
If Not File1.PostedFile Is Nothing And File1.PostedFile.ContentLength > 0 Then
Try
'checking if it was .txt file BEFORE UPLOADING IT!
'You used to upload it first...but the file could be a virus
If File1.FileName = ("doug.csv") = False Then
'The file is not the expected type...do not upload it
'just post the validation message
message.Text = "Sorry, thats not the correct file."
message2.Text = "Please locate and upload 'doug.csv'"
Else
'The file is a .txt file
'checking to see if the file exists already
'If it does exist Deleting the existing one so that the new one can be created
If IO.File.Exists(SavePath) Then
IO.File.Delete(SavePath)
End If
'Now upload the file (save it to your server)
File1.PostedFile.SaveAs(SavePath)
'After saving it check to see if it exists
If File.Exists(SavePath) Then
'Upload was sucessful
message.Text = "Thank you for your submission."
fileWasUploaded = True
Else
'the file was not saved
message.Text = "Unable to save the file."
End If
End If
Catch Exc As Exception
'We encountered a problem
message.Text = "Your file was not in the correct format. Please contact Customer Service at xxxx-xxxx-xxxx."
End Try
Else
'No file was selected for uploading
message.Text = "Please select a file to upload."
End If
Return fileWasUploaded
End Function
Private Sub SaveToDatabase(ByVal SavePath As String)
Try
Dim sqlQueryText As String = _
"BULK INSERT dialerresults " + _
"FROM '" & SavePath & "' " + _
"WITH ( FIELDTERMINATOR = ',' , ROWTERMINATOR = '\n' )"
' and bulk import the data:
'If ConfigurationManager.ConnectionStrings("Dialerresults") IsNot Nothing Then
'Dim connection As String = ConfigurationManager.ConnectionStrings("Dialerresults").ConnectionString
Dim connection As String = "data source=10.2.1.40;initial catalog=IVRDialer;uid=xxxx;password=xxxxx;"
Using con As New SqlConnection(connection)
con.Open()
' execute the bulk import
Using cmd As New SqlCommand(sqlQueryText, con)
cmd.ExecuteNonQuery()
End Using
End Using
'Else
'message.Text="ConfigurationManager.ConnectionStrings('Dialerresults') is Nothing!"
'End If
Catch ex As Exception
message.Text = "Your file was not in the correct format. Please contact Customer Service at xxxxxxx."
End Try
End Sub
End Class
Thank you,
Doug
Personally, I'd use a library like FileHelpers to parse/load the data then whatever my typical means of data access for this app is to update it.

Resources