File filtering (ASP.Net, VB.Net) - asp.net

I am making a filtering on files selected by user. Here is my coding that I currently use for button upload click event.
Dim validFileTypes As String() = {"jpg", "JPG", "jpeg", "JPEG", "png", "PNG"}
Dim ext As String = Path.GetExtension(fileUpload.PostedFile.FileName)
Dim isValidFile As Boolean = False
If fileUpload.HasFile Then
For i As Integer = 0 To validFileTypes.Length - 1
If ext = "." & validFileTypes(i) Then 'if selected url got extension like listed above
isValidFile = True 'file is valid
Dim hfc As HttpFileCollection = Request.Files
For j As Integer = 0 To hfc.Count - 1
Dim hpf As HttpPostedFile = hfc(j)
If hpf.ContentLength > 0 Then
hpf.SaveAs(Server.MapPath("source") & "\" & Path.GetFileName(hpf.FileName))
End If
Next
Else
Alert("Failed to upload! Please select file with valid extension.")
End If
Next
Else
Alert("Please select image!")
End If
So if user select file with wrong extension, file will not be uploaded into temporary file. Since the validFileTypes consist of 6 types so the Alert("Failed to upload! Please select file with valid extension.") will appear 6 times even though the file selected is only 1. I tried to fix it but need some guidance from you guys. Thank you.

I have made some improvements on your code and fixed some of the downsides for you.
Dim validExtensions As String() = {"jpg", "JPG", "jpeg", "JPEG", "png", "PNG"}
' Check if request has no file
If Request.Files.Count = 0 Then
Alert("Please select image!")
Else
'Otherwise get files from request
Dim files As HttpFileCollection = Request.Files
'Loop through file names
For Each fileName as String In files.AllKeys
'Get file from posted files
Dim file As HttpPostedFile = files(fileName)
'Check content length of file
If file.ContentLength > 0 Then
'Get file extension of file
Dim extension As String = Path.GetExtension(file.FileName)
'Check if file extension is valid
If validFileTypes.Contains(extension) Then
'Save file
file.SaveAs(Server.MapPath("source") & "\" & Path.GetFileName(file.FileName))
Else
Alert("Failed to upload! Please select file with valid extension.")
Exit For 'Break loop
End If
End If
Next
End If

Related

VB.Net OpenXML Conditional Page Break

I am using the OpenXML library to auto generate Word files. I have a function that takes a group of files and merges them into one document. As I merge a new file into a document, I want each file to start on a new page. But, I don't want to have any blank pages. The code I have mostly works, but an issue comes up is if a file being merged in is a filled page, then a page break is still added, resulting in an empty page being added. I am not sure how to best deal with this, to prevent blank pages from being added. Here is my code:
Public Sub MergeFiles(ByVal filePaths As List(Of String), ByVal fileName As String)
Dim newFile As String = HttpRuntime.AppDomainAppPath & "PDF_Templates\TempFolder\catalog-" & Guid.NewGuid.ToString & ".docx"
File.Copy(fileName, newFile)
Dim counter As Integer = 0
For Each filePath As String In filePaths
Dim wordDoc As WordprocessingDocument = WordprocessingDocument.Open(newFile, True)
Using wordDoc
Dim mainPart As MainDocumentPart = wordDoc.MainDocumentPart
Dim altChunkId As String = "altChunkId" & counter
Dim chunk As AlternativeFormatImportPart = mainPart.AddAlternativeFormatImportPart(AlternativeFormatImportPartType.WordprocessingML, altChunkId)
Dim fileStream As FileStream = File.Open(filePath, FileMode.Open)
Using fileStream
chunk.FeedData(fileStream)
End Using
Dim AltChunk As AltChunk = New AltChunk()
AltChunk.Id = altChunkId
' Dont add a page break to the first page.
If counter > 0 Then
Dim last As OpenXmlElement = wordDoc.MainDocumentPart.Document.Body.Elements().LastOrDefault(Function(e) TypeOf e Is Paragraph OrElse TypeOf e Is AltChunk)
last.InsertAfterSelf(New Paragraph(New Run(New Break() With {
.Type = BreakValues.Page
})))
End If
mainPart.Document.Body.InsertAfter(Of AltChunk)(AltChunk, mainPart.Document.Body.Elements(Of Paragraph).Last())
mainPart.Document.Save()
wordDoc.Close()
End Using
counter = counter + 1
Next
End Sub

VB.NET - Find a string in a XML String

I am working on a project to read InfoPath XML files into a .NET form. I'm trying to get the .xsn version from the href in order to determine what version of the InfoPath form I should display. Since there is only 1 .xsn string in the XML File, I can use that, but I'm having trouble parsing out the file name.
http://servername/foldername/forms/fileNameV100.xsn
Here is an example of how you would parse the filename. You can use these techniques to parse out the version. Additional notes are in the comments of the code.
Private Function ParseXsnFileName(ByVal strTarget As String) As String
Dim strResult As String = String.Empty
'Get the location of where the .xsn extension starts.
Dim intExtensionLocation As Integer = strTarget.IndexOf(".xsn")
If intExtensionLocation >= 0 Then
'Now we will initiate a loop that iterates back character by character until we find
'the forward slash of the URL that preceedes the filename.
Dim bolStartFound As Boolean = False
Dim intCursor As Integer = intExtensionLocation
Do Until intCursor = 0 OrElse bolStartFound
If strTarget.Substring(intCursor, 1) = "/" Then
'Setting this to true exist the loop.
bolStartFound = True
End If
intCursor -= 1
Loop
If bolStartFound Then
'We found all of the pieces we need to parse out the filename.
'Add 2 because of the "intCursor -= 1" and because we don't want the / in the filename.
Dim intStartLocation As Integer = intCursor + 2
'Add 4 to StartLocation because we want the extension.
'Subtract intStartLocation from intExtensionLocation to get the length.
strResult = strTarget.Substring(intStartLocation, (intExtensionLocation - (intStartLocation + 4)))
End If
End If
Return strResult
End Function
Example Usage:
Dim strParseThis As String = "http://servername/foldername/forms/fileNameV100.xsn"
Dim strFileName As String = ParseXsnFileName(strParseThis)

How to show window prompt for downloading excel file?

I have written code for exporting data to xlsx file. But i dont understand how to show window prompt for downloading that xlsx file at client end.
Here's my code:
Private Sub DataTableToExcel(ByVal tbl As DataTable)
Dim Excel As Object = CreateObject("Excel.Application")
Dim strFilename As String
Dim intCol, intRow As Integer
Dim strPath As String = "C:\"
If Excel Is Nothing Then
MsgBox("It appears that Excel is not installed on this machine. This operation requires MS Excel to be installed on this machine.", MsgBoxStyle.Critical)
Return
End If
Try
With Excel
.SheetsInNewWorkbook = 1
.Workbooks.Add()
.Worksheets(1).Select()
.cells(1, 1).value = "Complaint Detail Report" 'Heading of the excel file
.cells(1, 1).EntireRow.Font.Bold = True
Dim intI As Integer = 1
For intCol = 0 To tbl.Columns.Count - 1
.cells(2, intI).value = tbl.Columns(intCol).ColumnName
.cells(2, intI).EntireRow.Font.Bold = True
intI += 1
Next
intI = 3
Dim intK As Integer = 1
For intCol = 0 To tbl.Columns.Count - 1
intI = 3
For intRow = 0 To tbl.Rows.Count - 1
.Cells(intI, intK).Value = tbl.Rows(intRow).ItemArray(intCol)
intI += 1
Next
intK += 1
Next
If Mid$(strPath, strPath.Length, 1) <> "\" Then
strPath = strPath & "\"
End If
strFilename = strPath & "ComplaintDetail.xlsx"
.ActiveCell.Worksheet.SaveAs(strFilename)
End With
System.Runtime.InteropServices.Marshal.ReleaseComObject(Excel)
Excel = Nothing
MsgBox("Data's are exported to Excel Succesfully: Location: '" & strFilename & "'", MsgBoxStyle.Information)
' Response.AddHeader("content-disposition", "attachment;filename=ComplaintDetail.xlsx")
'Response.ContentType = "application/vnd.excel"
Catch ex As Exception
MsgBox(ex.Message)
End Try
Dim pro() As Process = System.Diagnostics.Process.GetProcessesByName("EXCEL")
For Each i As Process In pro
i.Kill()
Next
End Sub
Here I am saving .XLSX file directly to "C Drive".
Why I choose C Drive? : Because 99% of people have C: in there pc.
But I got some scenario where user don't allow access of their C drive or they don't give permission to write anything inside c drive.
That's why I am trying to add this window prompt where user will decide where to save that file. But i got some issue in above code.
Can you please help me to add window prompt in above code?
Save in the App_Data directory. You can find the absolute path with Server.MapPath("~/App_Data") This path is writeable by the application
Use Response.TransmitFile to make the file to be downloaded.
Try using something like a save file dialog (this can be added via the ui designer).
Then use:
If dialog.Show() = Windows.Forms.DialogResult.OK Then
strPath = dialog.FileName
End If

extract attachments from DB to separate folders for each document

Have an assignment to do - it's to extract data from Lotus Notes DB including documents and their attachments. The purpose of this is to put it and store on the Sharepoint as a library.
So far I have managed to create a view and export the data for it to structure in Excel.
Also, I have looked up some Agents examples for extracting the attachments. With implementation of the below script, I managed to export the attachments:
Dim sDir As String
Dim s As NotesSession
Dim w As NotesUIWorkspace
Dim db As NotesDatabase
Dim dc As NotesDocumentCollection
Dim doc As NotesDocument
Sub Initialize
Set s = New NotesSession
Set w = New NotesUIWorkspace
Set db = s.CurrentDatabase
Set dc = db.UnprocessedDocuments
Set doc = dc.GetFirstDocument
Dim rtItem As NotesRichTextItem
Dim RTNames List As String
Dim DOCNames List As String
Dim itemCount As Integer
Dim sDefaultFolder As String
Dim x As Integer
Dim vtDir As Variant
Dim iCount As Integer
Dim j As Integer
Dim lngExportedCount As Long
Dim attachmentObject As Variant
x = MsgBox("This action will extract all attachments From the " & CStr(dc.Count) & _
" document(s) you have selected, And place them into the folder of your choice." & _
Chr(10) & Chr(10) & "Would you like To continue?", 32 + 4, "Export Attachments")
If x <> 6 Then Exit Sub
sDefaultFolder = s.GetEnvironmentString("LPP_ExportAttachments_DefaultFolder")
If sDefaultFolder = "" Then sDefaultFolder = "F:"
vtDir = w.SaveFileDialog( False, "Export attachments To which folder?", "All files|*.*", sDefaultFolder, "Choose Folder and Click Save")
If IsEmpty(vtDir) Then Exit Sub
sDir = StrLeftBack(vtDir(0), "\")
Call s.SetEnvironmentVar("LPP_ExportAttachments_DefaultFolder", sDir)
While Not (doc Is Nothing)
iCount = 0
itemCount = 0
lngExportedCount = 0
Erase RTNames
Erase DocNames
'Scan all items in document
ForAll i In doc.Items
If i.Type = RICHTEXT Then
Set rtItem = doc.GetfirstItem(i.Name)
If Not IsEmpty(rtItem.EmbeddedObjects) Then
RTNames(itemCount) = CStr(i.Name)
itemCount = itemCount +1
End If
End If
End ForAll
For j = 0 To itemCount-1
Set rtItem = Nothing
Set rtItem = doc.GetfirstItem(RTNames(j))
ForAll Obj In rtItem.EmbeddedObjects
If ( Obj.Type = EMBED_ATTACHMENT ) Then
Call ExportAttachment(Obj)
Call doc.Save( False, True )
'creates conflict doc if conflict exists
End If
End ForAll
Next
'Scan all items in document
ForAll i In doc.Items
If i.Type = ATTACHMENT Then
DOCNames(lngExportedCount) = i.Values(0)
lngExportedCount = lngExportedCount + 1
End If
End ForAll
For j% = 0 To lngExportedCount-1
Set attachmentObject = Nothing
Set attachmentObject = doc.GetAttachment(DOCNames(j%))
Call ExportAttachment(attachmentObject)
Call doc.Save( False, True )
'creates conflict doc if conflict exists
Next
Set doc = dc.GetNextDocument(doc)
Wend
MsgBox "Export Complete.", 16, "Finished"
End Sub
Sub ExportAttachment(o As Variant)
Dim sAttachmentName As String
Dim sNum As String
Dim sTemp As String
sAttachmentName = sDir & "\" & o.Source
While Not (Dir$(sAttachmentName, 0) = "")
sNum = Right(StrLeftBack(sAttachmentName, "."), 2)
If IsNumeric(sNum) Then
sTemp = StrLeftBack(sAttachmentName, ".")
sTemp = Left(sTemp, Len(sTemp) - 2)
sAttachmentName = sTemp & Format$(CInt(sNum) + 1, "##00") & _
"." & StrRightBack(sAttachmentName, ".")
Else
sAttachmentName = StrLeftBack(sAttachmentName, ".") & _
"01." & StrRightBack(sAttachmentName, ".")
End If
Wend
Print "Exporting " & sAttachmentName
'Save the file
Call o.ExtractFile( sAttachmentName )
End Sub
So the issue I do have right now is that these attachments are being saved to the same folder, which means that I would manually have to put them into right folders of library (several thousands). Could anyone help on how should I change the above code to have the attachments saved to separate folder for each document from DB?
Also for some reason that I cant find out below line is causing error pop up with "Object Variable not set":
sAttachmentName = sDir & "\" & o.Source
Would anyone know why it causes failure and stops the whole process?
You need to use the MkDir statement to create directory and extract attachments in the folder. Probably write something like:
MkDir sDir
You need to write code that create a new directory for each document (make sure you check if the directory exists, and preferably you make sure each directory has a unique name).
I wrote a tool like that, that exports all the fields of a document into XML, as well as attachments and embedded images. It can be set to separate each document into it's own directory.
You can read more about it ate the link below, perhaps you can get some ideas from the description. I use the UniversalID of teh document to get a unique folder name.
http://www.texasswede.com/websites/texasswede.nsf/Page/Notes%20XML%20Exporter

search engine in asp classic

I already try a search engine script like below:
<HTML><BODY>
<B>Search Results for <%=Request("SearchText")%></B><BR>
<%
Const fsoForReading = 1
Dim strSearchText
strSearchText = Request("SearchText")
''# Now, we want to search all of the files
Dim objFSO
Set objFSO = Server.CreateObject("Scripting.FileSystemObject")
Dim objFolder
Set objFolder = objFSO.GetFolder(Server.MapPath("/"))
Dim objFile, objTextStream, strFileContents, bolFileFound
bolFileFound = False
For Each objFile in objFolder.Files
If Response.IsClientConnected then
Set objTextStream = objFSO.OpenTextFile(objFile.Path,fsoForReading)
strFileContents = objTextStream.ReadAll
If InStr(1,strFileContents,strSearchText,1) then
Response.Write "<LI><A HREF=""/" & objFile.Name & _
""">" & objFile.Name & "</A><BR>"
bolFileFound = True
End If
objTextStream.Close
End If
Next
if Not bolFileFound then Response.Write "No matches found..."
Set objTextStream = Nothing
Set objFolder = Nothing
Set objFSO = Nothing
%>
</BODY></HTML>
the output will show only the name of file, what i want is the title of the file.
my question is, how to get the string between in order to show up for the result? or is there any other script related to search engine in asp classic?
I'm not sure I get what you mean, but if you intend on grabbing the file name without the path nor extension, here's a snippet I use:
Public Function GetFileName(flname As String) As String
'From: http://www.freevbcode.com/ShowCode.asp?ID=1638
'By: Maria Rapini
'Get the filename without the path or extension.
'Input Values:
' flname - path and filename of file.
'Return Value:
' GetFileName - name of file without the extension.
Dim posn As Integer, i As Integer
Dim fName As String
posn = 0
'find the position of the last "\" character in filename
For i = 1 To Len(flname)
If (Mid(flname, i, 1) = "\") Then posn = i
Next i
'get filename without path
fName = Right(flname, Len(flname) - posn)
'get filename without extension
posn = InStr(fName, ".")
If posn <> 0 Then
fName = Left(fName, posn - 1)
End If
GetFileName = fName
End Function

Resources