The request is not supported. Encrypting an Image in ASP.net - asp.net

I am trying to create a simple encryption program with visual basic on visual studio. My program is to encrypt an image then decrypt it. The system is saying that the request is not supported. As a note I am just learning about encrypting and not sure if I am even doing this correctly. Any comments or help would be much appreciated.
Error is from this: File.Encrypt(FileName)
if my encrypt is creating an error then my decrypt will most likely as well
Imports System
Imports System.IO
Imports System.Security.Cryptography
Partial Class _Default
Inherits System.Web.UI.Page
'My Encrypt button that takes the file from my FileUpload tool and Encrypts it, then outputs on my label
'that the file was successfully encrypted
Protected Sub EncryptButton_Click(sender As Object, e As EventArgs) Handles EncryptButton.Click
Dim FileName As String = FileUpload1.FileName
File.Encrypt(FileName)
Label1.Text = "Encrypt" + FileName
End Sub
'My Decrypt button that takes the file from my FileUpload tool and Encrypts it, then outputs on my label
'that the file was successfully encrypted
Protected Sub DecryptButton_Click(sender As Object, e As EventArgs) Handles DecryptButton.Click
Dim FileName As String = FileUpload1.FileName
File.Decrypt(FileName)
Label1.Text = "Decrypt" + FileName
End Sub
'Load page that will display a success output on the label if the upload is completed
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
If FileUpload1.HasFile = True Then
Label1.Text = "Success"
Else
Label1.Text = "Failed"
End If
End Sub
Protected Sub CustomValidator1_ServerValidate(source As Object, args As ServerValidateEventArgs) Handles CustomValidator1.ServerValidate
'Verify the control has a file
If Not FileUpload1.HasFile Then
CustomValidator1.ErrorMessage = "A file is required in order to proceed"
args.IsValid = False
Else
'next 2 lines are all one line
Dim ext As String =
System.Web.VirtualPathUtility.GetExtension(FileUpload1.FileName).ToUpper()
If Not ext = ".GIF" And Not ext = ".JPG" And Not ext = ".PNG" Then
'next 2 lines are all one line
CustomValidator1.ErrorMessage = String.Concat("Invalid file type '", ext, "' -must be .gif or .jpg or .png to continue")
args.IsValid = False
Else
args.IsValid = True
End If
End If
End Sub
End Class

I searched for "System.IO.IOException" and found Troubleshooting Exceptions: System.IO.IOException which states
Make sure the file and directory exist.
Then looking at the code:
Dim FileName As String = FileUpload1.FileName
I see that there is no directory specified for the file. So, you need to use Path.Combine so that you can give File.Encrypt the full filename including the path.
(There is no indiction in the posted code of which directory the uploaded file is in, so I can't help further with that. It could be that FileUpload1 has a property which gives that.)

Related

Excel download not happening from server

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.)

Serve Local Files in ASP.NET in Chrome

Chrome has a setting that blocks the opening of local files. The specific error you get is Not allowed to load local resource: file:///<file name>. I'm trying to develop an internal site for us to access these files but as many users are using Chrome, I need a workaround to serve these files.
Currently, to get my files and display them, I have this logic:
For Each file As String In Directory.GetFiles("<file path>")
fileInfo = New FileInfo(file)
fileList.Add(fileInfo)
Next
fileList.Sort(Function(x, y) x.Name.CompareTo(y.Name))
For i As Integer = 0 To fileList.Count - 1
pnlLinks.Controls.Add(New LiteralControl("<br />"))
pnlLinks.Controls.Add(New LiteralControl("" & fileList(i).Name & ""))
pnlLinks.Controls.Add(New LiteralControl("&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp"))
pnlLinks.Controls.Add(New LiteralControl("<span>" & GetByteSize(fileList(i).Length.ToString) & " </span>"))
pnlLinks.Controls.Add(New LiteralControl("<br />"))
Next
The a href is a little funky because I've been experimenting with different folder structures to get this working, but it should not be relevant.
I had the idea of implementing a function that could send this to a byte stream but I'm not experienced in that area and wouldn't be sure how to implement it.
I was able to resolve this with a FileStream and launching to a new page that handles it on Page_Load
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim pdfFileStream As FileStream = Nothing
Dim pdfFileSize As Long = 0
Dim pdfPath As String = "<file path>"
pdfFileStream = New FileStream(pdfPath, FileMode.Open)
pdfFileSize = pdfFileStream.Length
Dim Buffer(CInt(pdfFileSize)) As Byte
pdfFileStream.Read(Buffer, 0, CInt(pdfFileSize))
pdfFileStream.Close()
Response.ContentType = "application/pdf"
Response.OutputStream.Write(Buffer, 0, pdfFileSize)
Response.Flush()
Response.Close()
End Sub

Failed to open connection when exporting crystal report

I'm trying to export my crystal report to pdf but keep getting the "failed to open a connection" error. It seems as if the error is happening at the CR.Export line. I've tried everything but don't know how to fix it. FYI, it's working on my development server, but when I copy it to the production server, I get the error. So it's very hard to pin point where it's occurring.
Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init
'CODEGEN: This method call is required by the Web Form Designer
'Do not modify it using the code editor.
Try
InitializeComponent()
strPermitNo = Session("RecordID")
SpWithViewer(strPermitNo)
CrystalReportViewer2.DataBind()
Catch er As Exception
LogError(er.ToString, "PageInit-PrintPermit1.aspx")
Exit Try
Finally
End Try
End Sub
`
Protected Sub btnExport_Click(sender As Object, e As EventArgs) Handles btnExport.Click
strPermitNo = Session("RecordID")
Try
Dim CrExportOptions As ExportOptions
Dim CrDiskFileDestinationOptions As New DiskFileDestinationOptions()
Dim CrFormatTypeOptions As New PdfRtfWordFormatOptions()
CrDiskFileDestinationOptions.DiskFileName = "\\idsfmsrvr\wwwroot\FWPDFs\" & strPermitNo & ".pdf"
strAttachment = "\\idsfmsrvr\wwwroot\FWPDFs\" & strPermitNo & ".pdf"
Session("Attachment") = strAttachment
CrExportOptions = CR.ExportOptions
If True Then
CrExportOptions.ExportDestinationType = ExportDestinationType.DiskFile
CrExportOptions.ExportFormatType = ExportFormatType.PortableDocFormat
CrExportOptions.DestinationOptions = CrDiskFileDestinationOptions
CrExportOptions.FormatOptions = CrFormatTypeOptions
End If
CR.Export()
EmailPermitToApplicant()
File.Delete(strAttachment)
lblMsg.Text = "Permit has been emailed to applicant."
lblMsg.Visible = True
Catch er As Exception
LogError(er.ToString, "btnExport()-PrintPermit1.aspx")
Exit Try
Finally
connFTS.Close()
End Try`
Just a step:
Open a report first, follow this link
Export it whatever you want.
Take note: you can hide the form if you don't want to display the report.
Good Luck!

unable to view image using file path

Issue: Unable to display image using FilePath
I have File Upload button which captured the file path & when I click on Upload button, it should be display the image which I have selected. But its not happening?
What I missed here?? do I need to convert the path to image url?? If Yes then please provide me the code behind it??
Thanks in advance..
Here is my code....
Protected Sub Button1_Click(sender As Object, e As System.EventArgs) Handles Button1.Click
Dim path As String
path = Server.MapPath(FileUpload1.FileName)
Image1.ImageUrl = path
Label1.Text = Image1.ImageUrl
End Sub
You forgot to save the file?
FileUpload1.SaveAs(string SomeFileNameOnServer) should happen too, before you display from the server.
(not sure how the above line is written in VB.NET)
Protected Sub Button1_Click(sender As Object, e As System.EventArgs) Handles Button1.Click
Dim path As String
path = Server.MapPath("~/.") + FileUpload1.FileName;
FileUpload1.SaveAs(path)
Image1.ImageUrl = path
Label1.Text = Image1.ImageUrl
End Sub

Ajax Control Toolkit htmleditorextender AjaxFileUpload Path

I'm trying to save an image to a local path (I'm not going to be deploying my project on a server) and I'm having difficulty with putting my finger on the correct path for the file upload:
Protected Sub htmleditorextender_ImageUploadComplete(sender As Object, e As AjaxControlToolkit.AjaxFileUploadEventArgs)
Dim fullpath = Request.MapPath("~/img/ar") & "/" & e.FileName
TextBox1_HtmlEditorExtender.AjaxFileUpload.SaveAs(fullpath)
e.PostedUrl = fullpath
End Sub
This doesn't work, and no image is uploaded to the said folder. What's going wrong?
try this
Protected Sub HTMLEditorExtender_ImageUploadComplete(sender As Object, e As AjaxControlToolkit.AjaxFileUploadEventArgs)
Dim fullpath As String = Server.MapPath("~/img/ar/") + e.FileName
HTMLEditorExtender.AjaxFileUpload.SaveAs(fullpath)
e.PostedUrl = Page.ResolveUrl(fullpath)
End Sub

Resources