Save filenames in arabic using classic asp - asp-classic

Hey guys i am creating a runtime jnlp file for download and in that i got stuck up with the filename since it has arabic or other languages some time as the filename takes from username... when creating with that i get the file name as "اخطاء البرنامج.jnlp"
my code for creating file
Set fs = Server.CreateObject("Scripting.FileSystemObject")
Set f = fs.CreateTextFile(Server.MapPath(id & "_" & user & ".jnlp"), true)
f.write(JNLPFile)
f.close
Set f = nothing
Set fs = nothing
where "user" in the CreateTextFile is the name given by the user which may sometimes contains unicode characters or other language characters...
any solutions for this problem....?

Well, FileSystemObject does not natively support UTF8.
What you should do instead of using File System Object and CreateTextFile to build a new text file is to use ADODB Stream object.
Following is an example of a VBScript procedure that would take your path as strPath and the content of the file as strOut.
Sub Generate_File(strPath,strOut)
Set objStream = Server.CreateObject("ADODB.Stream")
objStream.Open
objStream.Position = 0
objStream.Charset = "UTF-8"
objStream.WriteText strOut
objStream.SaveToFile server.mappath(strPath),2
objStream.Close
End Sub

Related

FileUpload file to Azure Blob Storage

I have a System.Web.UI.WebControls.FileUpload control that passes both Word and PDF files that need to be stored in Azure Blob Storage.
From the Code Behind page it passes to the common library to manage Azure Functions:
Private Sub UploadButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles UploadButton.Click
Dim fileExt As String = String.Empty
Dim newGuid As New Guid
Dim fileName As String
Dim documentType As Document.DocumentType
Page.Validate()
newGuid = Guid.NewGuid
If Page.IsValid() AndAlso Me.FileUploadNewDoc.HasFile Then
Try
'Test that MIME is either msword of pdf
If FileUploadNewDoc.PostedFile.ContentType.Contains("msword") Then
fileExt = "doc"
documentType = Document.DocumentType.LeaseWordDoc
ElseIf FileUploadNewDoc.PostedFile.ContentType.Contains("pdf") Then
fileExt = "pdf"
documentType = Document.DocumentType.LeasePDF
Else
fileExt = "na"
End If
If fileExt <> "na" Then
fileName = newGuid.ToString & "." & fileExt
AzureStorage.SaveBlob(FileUploadNewDoc.FileContent, fileName, mDocumentContainer, mStorageConnectionString)
End If
Catch ex As Exception
' Handle Error
Finally
FileUploadNewDoc.Dispose()
End Try
End If
End Sub
The AzureStorage.SaveBlob code:
Public Function SaveBlob(ByRef fileContent As Stream,
ByVal fileName As String,
ByVal containerName As String,
ByVal storageConnectionString As String) As Boolean
Dim storageAccount As CloudStorageAccount = CloudStorageAccount.Parse(storageConnectionString)
Dim blobClient As CloudBlobClient = storageAccount.CreateCloudBlobClient()
Dim container As CloudBlobContainer = blobClient.GetContainerReference(containerName)
Dim blockBlob As CloudBlockBlob = container.GetBlockBlobReference(fileName)
Using fileContent
fileContent.Position = 0
blockBlob.UploadFromStream(fileContent)
End Using
Return True
End Function
My questions:
Is this best way to take the File that has been uploaded and save it to Azure Blob Storage?
Am I handling the Stream correctly? I'm passing ByRef and have a Using statement around the usage.
Should I be setting content type explicitly when saving it to storage? If so how do I do that?
Note, I normally code in C# so an example in C# is fine if you're not familiar with VB.NET.
Is this best way to take the File that has been uploaded and save it
to Azure Blog Storage?
The best way depends on your use case. If it is just small files you're OK. If you want to support large files you might want to do chunked uploading. You can take blocks of 1 megabyte which you can upload separately or in parallel. Once you are done uploading all the blocks you commit the file and it is stiched together in Azure Blob storage. Look at CloudBlockBlob.PutBlock and CloudBlockBlob.PutBlockList.
Am I handling the Stream correctly? I'm passing ByRef and have a Using
statement around the usage.
You are but if you want to support larger files you might want to upload with JavaScript and create two endpoint to receive chunks and to commit after all chunks are sent. There are multiple libraries that can help you.
Should I be setting content type explicitly when saving it to storage? If so
how do I do that?
If you upload files that you want to embed in HTML it's wise to have a content type. If you want the links to the file to be download links you don't have to. Although it can never hurt.
blockBlob.Properties.ContentType = "image/jpeg";

Read text from a .doc or .docx file in asp.net using vb.net

I can upload a text file and read its text in a textbox.
Now I want to do the same for .doc or .docx files.
When I tried it in the similar way I read the text files I got some text which is in encrypted format in the whole document. The code for reading from a .txt file is as follows :
txtReadFiles.Text = My.Computer.FileSystem.ReadAllText(Path)
can anyone suggest me some idea?
What you want is an ifilter for .doc(x) files. Ifilters were designed to be used by Windows for its indexing service, but they are frequently pressed into use also for other applications to read text from binary files that contain text. IFilters are frequently released for free - I believe this contains the correct ifilters for doc/docx files (and other Office files).
That said, I've never used the ifilter interface in .net, only in unmanaged c++, but it should be possible. A quick googling turned up this as a likely place to start (it has some recommendations of things to avoid, and some code. I make no guarantee that the code works, you might have to find something else. But the ifilter technology itself does work, I've used it in projects before. Other than the ifilter for pdfs that ships with Reader, which only just "works", barely, last I checked. The Office ifilters work fine, though.)
Imports Microsoft.Office.Interop.Word 'above public class
If OpenFileDialogFile.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
TBfile.Text = OpenFileDialogFile.FileName 'alamat n nama file asli
'-----------
Dim ext As String
ext = Path.GetExtension(OpenFileDialogFile.FileName)
If ext = ".txt" Then
'tampilkan isi file
TB1.Text = My.Computer.FileSystem.ReadAllText(OpenFileDialogFile.FileName)
ElseIf ext = ".doc" Then
Dim App As Application = New Application
Dim doc As Document
Try
doc = App.Documents.Open(OpenFileDialogFile.FileName)
Dim co As Integer = doc.Words.Count
For i As Integer = 1 To co
Dim tex As String = doc.Words(i).Text
'tampilkan isi file
TB1.Text += tex
Next
doc.Close()
Catch ex As Exception
End Try
ElseIf ext = ".docx" Then
Dim App As Application = New Application
Dim doc As Document
Try
doc = App.Documents.Open(OpenFileDialogFile.FileName)
Dim co As Integer = doc.Words.Count
For i As Integer = 1 To co
Dim tex As String = doc.Words(i).Text
'tampilkan isi file
TB1.Text += tex
Next
doc.Close()
Catch ex As Exception
End Try
End If
'----------
Else
Call kosongkan()
CBkunci1.Focus()
End If

VBScript runtime error '800a0034' - Bad file name or number - When trying to write to server side text file

I'm trying to simply write to a text file for later use data collected from input elements on various pages. Admittedly I am likely missing the obvious, but of the variations I have tried and even some of the sample code I have found in many examples I always get the same error.
Code:
<%
Dim currentDirectoryPath, outFile, objFSO, objTextStream
Const fsoForWriting = 2
'Get and assign current directory path
currentDirectoryPath = Server.MapPath(".")
'Assign file name to be used
outFile = "\accdata.txt\"
Set objFSO = Server.CreateObject("Scripting.FileSystemObject")
'Open the text file
Set objTextStream = objFSO.OpenTextFile(currentDirectoryPath & outFile, fsoForWriting, True)
'Write new line to text file
objTextStream.WriteLine "output this as one line of text"
'Close the file and clean up
objTextStream.Close
Set objTextStream = Nothing
Set objFSO = Nothing
%>
Result:
Microsoft VBScript runtime error '800a0034'
Bad file name or number
/asp/accounting/datacollect.asp, line 23
(Line 23 of the code is:)
Set objTextStream = objFSO.OpenTextFile(currentDirectoryPath & outFile, fsoForWriting, True)
This is far from being my first language and thus I don't posses a heap load of experience with it so any help or suggestions will be very much appreciated.

I have path Manipulation issue. The following code is placed in Page_load method of ASPx page + VB

If Request.QueryString("ID") = "" Then
folderDirectory = Global.FileUpload.GetFolderDirectory(Request.QueryString("TFID"))
If Not File.Exists(folderDirectory + fileName) Then
If Not Directory.Exists(folderDirectory) Then
Directory.CreateDirectory(folderDirectory)
End If
Dim bufferSize As Integer = Me.fileUpload.PostedFile.ContentLength
Dim buffer As Byte() = New Byte(bufferSize) {}
' write the byte to disk
Using fs As New FileStream(Path.Combine(folderDirectory, fileName), FileMode.Create)
Dim bytes As Integer = Me.fileUpload.PostedFile.InputStream.Read(buffer, 0, bufferSize)
' write the bytes to the file stream
fs.Write(buffer, 0, bytes)
End Using
Else
CallOnComplete("error", "", "Error uploading '" & fileName & "'. File has been exists!")
Exit Sub
End If
But Fortify scan report for the above sample code shows Path Manipulation issue as high. I Need help to modify above code so that it can pass fortify scan
It is showing me error at folderDirectory
Usually, when your code works inside a web application you don't have the liberty to use the full file system as you do on your local PC. Any kind of 'Path Manipulation' is suspicious.
You should try to recode your works using Server.MapPath method.
Pay particular attention to this warning
For security reasons, the AspEnableParentPaths property has a default value set to FALSE.
Scripts will not have access to the physical directory structure unless AspEnableParentPaths
is set to TRUE.

ASP SaveToDisk method takes an incredible amount of time

This is a method in ASP Classic that saves a file to disk. It takes a very long time but I'm not sure why. Normally, I wouldn't mind so much, but the files it handles are pretty large so need this needs to faster than 100kB a second save. Seriously slow. (old legacy system, band aid fix till it gets replaced...)
Public Sub SaveToDisk(sPath)
Dim oFS, oFile
Dim nIndex
If sPath = "" Or FileName = "" Then Exit Sub
If Mid(sPath, Len(sPath)) <> "\" Then sPath = sPath & "\" '"
Set oFS = Server.CreateObject("Scripting.FileSystemObject")
If Not oFS.FolderExists(sPath) Then Exit Sub
Set oFile = oFS.CreateTextFile(sPath & FileName, True)
For nIndex = 1 to LenB(FileData)
oFile.Write Chr(AscB(MidB(FileData,nIndex,1)))
Next
oFile.Close
End Sub
I'm asking because there are plenty of WTF's in this code so I'm fighting those fires while getting some help on these ones.
I don't see your definition for "FileData" anywhere in your code - where is this coming from? Is there a reason you're writing it to disk a single character at a time? I'd suspect this is your problem - writing 100K of data takes 100K trips through this loop, which could be the reason for your slowdown. Why can't you replace the write loop at the bottom:
For nIndex = 1 to LenB(FileData)
oFile.Write Chr(AscB(MidB(FileData,nIndex,1)))
Next
with a single statement to write the file all at once?
oFile.Write FileData
What you should do is read the binary request into an ADODB.Stream object and convert it to plain ASCII text in a single fast step.
Set objStream = Server.CreateObject("ADODB.Stream")
objStream.Type = 1
objStream.Open
objStream.Write Request.BinaryRead(Request.TotalBytes)
objStream.Position = 0
objStream.Type = 2
objStream.Charset = "ISO-8859-1"
FormData = objStream.ReadText
objStream.Close
Set objStream = Nothing
Notice how the variable FormData now contains the form data as text. Then you parse this text and locate the start and length of each file, and use ADODB.Stream CopyTo method to extract the specific portion of the file and save it do disk.

Resources