Check to see if file name exists in directory and rename if it does before completing upload? - asp.net

I am creating a application that allows users to upload an image to the server of my site. But I want to allow users to upload multiple files with the same name by renaming the new file.
But I don't know what methods to use to perform this check.
I am thinking about trying to put all of the filenames into an arraylist individually and creating a loop to check the new filename against the rest and if there is a match then I would randomly generate a string of letters to tag onto the new filename.
But I haven't figured out how to populate the arraylist yet and this is the code I have for checking for repeats against the arraylist:
Dim i As Integer = 0
For i = 0 To arrayFileNames.Count
If (fileName = arrayFileNames(i)) Then
Dim random As Random = New Random()
random.Next(1, 100000)
fileName = fileName & random.ToString
End If
i = i + 1
Next
But this code throws the following error:
Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
Any help would be appreciated, thank you.

If you're creating a For loop, you don't need to manually increase the counter. Remove the line i = i + 1.
Dim i As Integer = 0
For i = 0 To arrayFileNames.Count
If (fileName = arrayFileNames(i)) Then
Dim random As Random = New Random()
random.Next(1, 100000)
fileName = fileName & random.ToString
End If
Next

The for loop already takes care of increasing i.
You'll have a problem if you get a new fileName that is equal to a previous index.
When you create a new instance of random, you'll get the same value.
random.ToString() doesn't return what you think it does (check the output).
You might get a very big filename if you keep appending a big number.
You'll have to change your logic (I haven't tested this code, it's an example to help you out).
Dim random As Random = New Random()
Do While arrayFileNames.Contains(fileName)
fileName = fileName & random.Next(1, 9).ToString
Loop

Related

Classic ASP which folder does a file belong to

I have a folder structure which stores images by the thousand, take for example the following folder names;
00001-01000
01001-02000
02001-03000
03001-04000
04001-05000
05001-06000
06001-07000
I am then dynamically rendering a page to display all sorts of images. In the page i am trying to build a link to the image, but what i need is to figure out what folder an image belongs to. For instance, i am using the following to get the image id from the database
<%= rs.Fields("imageid") %>
If that were to return '04232' the folder name that would belong to would be '04001-05000'.
Is there any way that i could figure out what the folder name would be, by only having the imageid in classic asp?
For this you need two small methods. First, padding a string:
Function PadLeft(str, padChar, desiredLength)
Dim result
result = CStr(str)
Do Until Len(result)>=desiredLength
result = padChar & result
Loop
PadLeft = result
End Function
And the method to find the folder name:
Function ExtractFolderName(imageFileName)
Dim numericValue, rangeStart, rangeEnd
numericValue = CInt(imageFileName)
rangeStart = (Fix((numericValue / 1000)) * 1000) + 1
rangeEnd = (Fix((numericValue / 1000)) + 1) * 1000
ExtractFolderName = PadLeft(rangeStart, "0", 5) & "-" & PadLeft(rangeEnd, "0", 5)
End Function
To use it:
folderName = ExtractFolderName(rs("imageid"))
Basically, the method performs some math on the name to find the desired range. Note this will throw error in case of a non numeric value in the database.

Trouble with "string.contains" function

I am writing a web form that has a unique travelID per travel request. (see blank column in picture below, I'm not high enough reputation to embed the picture in here)
Some of the travel requests have attached documents and others do not. I wrote this code:
Dim dirs As String() = Directory.GetFiles("E:\DomainWebs\Intranet\fileups\TravelDocs\")
Dim i As Integer = 0
For Each GridRecord As GridRecord In TravelWebDataGrid.Rows
For Each doc As String In dirs
If doc.Contains(TravelWebDataGrid.Rows(i).Items(10).Value) = True Then
TravelWebDataGrid.Rows(i).Items(11).Value = True
End If
Next
i += 1
Next
Just for testing, only the top Travel Request has documents attached. As you can see, it is checking the second row checkbox as well even though it doesn't have any documents attached.
This is what is being compared to row 2:
"DocName" - E:\DomainWebs\Intranet\fileups\TravelDocs\RONNIEP20180124141116-Hello.docx
"TravelID" - RONNIEP20180124135357
Does anyone know why it is doing this? Let me know if you need any more information. Thanks in advance for your responses.
This might be off because I haven't worked with a datagrid but it looks like the code has been over-complicated with the counter. Can you do this?
' you're looping gridrecords/rows.
For Each GridRecord As GridRecord In TravelWebDataGrid.Rows
For Each doc As String In dirs
' use the gridrecord here, not rows(i).
If doc.Contains(GridRecord.Items(10).Value) = True Then
' and here.
GridRecord.Items(11).Value = True
End If
Next
Next

Getting documents of last 25 minutes with formula and lotusscript

In lotus I have a view with order documents.
I am building an agent to search for all orders which are modified in the last 25 minutes.
For this I have done code like:
strFormule = "Form=""Order"" & #Modified >= #Adjust(#Today;0;0;0;0;-25;0) & Deleted !=""J"""
Set ndcOrder = currentDB.Search( strFormule, Nothing, 0 )
If ndcOrder.Count <> 0 Then
Set doc = ndcOrder.GetFirstDocument
While Not doc Is Nothing
So if it is 11.00 then it need to take orders which are modified today from 10.35
But in the debugger I also get orders which where modified 2 hours earlier.
How is this possible?
I think it's might be because you're using #today which doesn't have a time element. Try #Now instead ?
In the past I used the LotusScript method GetModifiedDocuments which lets you specify a NotesDateTime object to retrieve any document modified since.
Your code could then look like this:
Dim session As New NotesSession
Dim db As NotesDatabase
Dim dc As notesdocumentcollection
Dim since As New NotesDateTime("")
Set db = session.CurrentDatabase
Call since.SetNow()
Call since.AdjustMinute(-25)
Set dc = db.GetModifiedDocuments(since)
My experience with this method was very good so far. More info on GetModifiedDocuments
Why use formula at all?
I would create a hidden view, first column is last modified date-time, sorted descending.
Then I would write my Lotusscript code to start at the top and work its way down until it encounters a date/time value that is older than 25 minutes ago.
Something like this:
Dim docs List As NotesDocument
Set dt25 = New NotesDateEntry(Now())
Call dt25.AdjustMinutes(-25)
Dim col as NotesViewEntryCollection
Dim entry as NotesViewEntry
Set col = view.AllEntries
Set entry = col.GetFirstEntry
Do Until entry Is Nothing
If Cdat(entry.ColumnValues(0))<Cdat(dt25.LSLocalTime) Then
Exit Loop
End If
Set docs(entry.Document.UniversalID) = entry.Document
Loop
' Now you have a list of documents created in the last 25 minutes.

How to autofill OpenOffice Math formula editor in OOo Calc?

I am using OpenOffice Calc spreadsheet formulas with psuedo-random numbers to generate arrays of arithmetic problems which I can easily update to creating new worksheets (I'm a teacher)
Problems are output as formula mark-ups in string form. OOo Math formulas use these string commands typed into the editor to display nicely formatted maths expressions.
I can do this next step manually:
1) go to source cell and copy string mark-up to clipboard
2) select target cell and clear existing contents and objects
3) create new Math object anchored to target cell
4) open Math editor window and paste in mark-up string
5) exit Math editor window and return cursor to source cell
Result: a nice maths expression of given arithmetic problem.
I need to be able to do this for entire columns of source cells on various sheets.
...even better, to then add a listener to dynamically update as sources are updated.
I found code here: Cell content inside formula that achieves this for a fixed pair of cells, but despite all my best efforts, I have had to admit defeat - generalising this code is simply beyond my expertise!
The absolute ideal would be a macro function that I could call like a spreadsheet function; with input arguments (sourceCell, targetCell, listenerON/OFF) that could run the above algorithm and dynamically update if required.
Can anybody help me? A solution like this, or any kind of workaround would be immensely helpful.
UPDATE 2016/10/27
Thank you Jim K, that did work, but use of the dispacher comes with a whole host of difficulties I hadn't foreseen.
I just found Charlie Young's post in the OpenOffice forum which makes use of the API. I have included my adaptation of his code below.
Can anybody help me to integrate it into a function in a similar way as I've described? I don't know how to solve placement of the Math object in to the target cell.
The API code is great as it will create a new Math object each time the code is updated. Existing ones do need to be deleted though.
I think the limitation of not being able to delete existing objects from within a function is going to persist. Would this be the case even if done by a subroutine called by the function?
function InsertFormula(paraFromCell, paraToCell)
Dim oDoc As Object
Dim oSheet As Object
Dim oShape As Object
oDoc = ThisComponent
oSheet = oDoc.Sheets(0)
oShape = oDoc.createInstance("com.sun.star.drawing.OLE2Shape")
oShape.CLSID = "078B7ABA-54FC-457F-8551-6147e776a997"
oSheet.Drawpage.Add(oShape)
oShape.Model.Formula = paraFromCell
oShape.setSize(oShape.OriginalSize)
end function
NEXT UPDATE
I've been managing to solve my own problems quite quickly now...
I've decided to go with a sub, not a function, so I can access the sheet to delete existing objects. Code is attached - Source cells are in Column C and target cells in matching rows of Column A. So far I am only able to send objects to $A$1.
How do I anchor each new object to a specific cell?
REM ***** BASIC *****
Sub InsertThisFormula
Dim oDoc As Object
Dim oSheet As Object
Dim oShape As Object
Dim sourceCell As Object
Dim targetCell As Object
oDoc = ThisComponent
oSheet = oDoc.Sheets(1)
Dim n As Integer
n = 1 'number of rows of formulas
for i = 0 To n-1
rem loop through cells
sourceCell = oSheet.getCellByPosition(2, i)
targetCell = oSheet.getCellByPosition(0, i)
rem clear target cell object/s
targetCell.ClearContents(128)
oShape = oDoc.createInstance("com.sun.star.drawing.OLE2Shape")
oShape.CLSID = "078B7ABA-54FC-457F-8551-6147e776a997"
oSheet.Drawpage.Add(oShape)
oShape.Model.Formula = sourceCell.string
oShape.setSize(oShape.OriginalSize)
Next i
End Sub
Starting from Mifeet's example, add this to My Macros:
rem ----------------------------------------------------------------------
rem Creates a math formula from text
Function InsertFormulaFromCell(paramCellFrom, paramCellTo)
dim document as object
dim dispatcher as object
document = ThisComponent.CurrentController.Frame
dispatcher = createUnoService("com.sun.star.frame.DispatchHelper")
rem go to cell containing markup and copy it
dim fromCellArgs(0) as new com.sun.star.beans.PropertyValue
fromCellArgs(0).Name = "ToPoint"
fromCellArgs(0).Value = paramCellFrom
dispatcher.executeDispatch(document, ".uno:GoToCell", "", 0, fromCellArgs())
dispatcher.executeDispatch(document, ".uno:Copy", "", 0, Array())
rem go to cell where I want the formula displayed
dim toCellArgs(0) as new com.sun.star.beans.PropertyValue
toCellArgs(0).Name = "ToPoint"
toCellArgs(0).Value = paramCellTo
dispatcher.executeDispatch(document, ".uno:GoToCell", "", 0, toCellArgs())
rem open Star.Math
oDesk = createUnoService ("com.sun.star.frame.Desktop")
dispatcher.executeDispatch(document, ".uno:InsertObjectStarMath", "", 0, Array())
document = ThisComponent.CurrentController.Frame
dispatcher = createUnoService("com.sun.star.frame.DispatchHelper")
rem paste clipboard using Array() as place-holder for variable name
dispatcher.executeDispatch(document, ".uno:Paste", "", 0, Array())
rem exit Star.Math
dispatcher.executeDispatch( _
document, ".uno:TerminateInplaceActivation", "", 0, Array())
InsertFormulaFromCell = "Math Formula updated " & Now()
End Function
To run it, put this formula in cell C5:
=INSERTFORMULAFROMCELL("$C$3","$C$20")
Now when the values get updated, it creates another formula.
Note: I could not get the .uno:Delete section of Mifeet's code to work, perhaps because functions are not supposed to access other cells. This may require manually deleting the formulas before creating new ones.
(Posted solution on behalf of the OP).
This is now solved. After a lot of searching, I found what I needed! Simple really. Future improvements might be to resize cells appropriately. Happy for now. Thanks to Jim K and the rest of the Stack Overflow community!
Complete macro below:
REM ***** BASIC *****
Sub InsertThisFormula
Dim oDoc As Object
Dim oSheet As Object
Dim oShape As Object
Dim sourceCell As Object
Dim targetCell As Object
oDoc = ThisComponent
oSheet = oDoc.Sheets(1)
Dim n As Integer
n = 6 'number of rows of formulas
for i = 0 To n-1
rem loop through cells
sourceCell = oSheet.getCellByPosition(2, i)
targetCell = oSheet.getCellByPosition(3, i)
rem clear target cell object/s
targetCell.ClearContents(128)
oShape = oDoc.createInstance("com.sun.star.drawing.OLE2Shape")
oShape.CLSID = "078B7ABA-54FC-457F-8551-6147e776a997"
oSheet.Drawpage.Add(oShape)
oShape.Model.Formula = sourceCell.string
oShape.setSize(oShape.OriginalSize)
oShape.Anchor = targetCell
oShape.MoveProtect = True
Next i
End Sub

How do I delete characters in a string up to a certain point in classic asp?

I have a string that at any point may or may not contain one or more / characters. I'd like to be able to create a new string based on this string. The new string would include every character after the very last / in the original string.
Sounds like you're wanting the file name from a URL. In any case, it's the same function. The key is using the InStrRev function to find the first / char, but starting from the right. Here's the function:
Function GetFilename(URL)
Dim I
I = InStrRev(URL, "/")
If I > 0 Then
GetFilename = Mid(URL, I + 1)
Else
GetFilename = URL
End If
End Function
Split it up into parts and get the last part:
a = split("my/string/thing", "/")
wscript.echo a(ubound(a))
note: Not safe when the string is empty.

Resources