unix script to replicate .net code logic - unix

I do not have any experience with Unix coding besides navigating through directories and was wondering if someone could help me with writing a script to replicate what I am doing within .NET. I was told it would run faster since the .NET code is deployed remotely and sometimes using a mapped drive to access large amounts of folders runs slow. I basically am sorting files by moving files from selected folders to a group of folders based on the filename and sorting each based on the file date which is included in the filename.
Private Sub moveAllfiles(ByVal directoryStuff As String)
Dim templist As New ArrayList
Dim finalDestination As String = String.Empty
Dim pathName As String = String.Empty
Dim fileToDelete As String = String.Empty
Dim folderDate As String = String.Empty
Dim counter As Integer = 0
Dim folders = Directory.EnumerateDirectories(directoryStuff)
For Each item In folders
Dim files As String() = Directory.GetFiles(item)
//' if directory is empty delete folder
If Directory.GetFiles(item).Count = 0 Then
Directory.Delete(item)
Continue For
End If
For i As Integer = 0 To files.Count - 1
Try
counter += 1
Dim oInfo As New FileInfo(files(i))
// ' if file is empty or small delete it
If oInfo.Length <= 1 Then
File.Delete(files(i))
Continue For
End If
If Not files(i).EndsWith(".gz") Then
CompressFiles(files(i))
Continue For
End If
Dim objInfo As New FileInfo(files(i))
If Not objInfo.Name.Contains("Data_G_E") Then
If objInfo.Name.Contains("Data_G_P") Then
Dim pfiledate As String = objInfo.Name.Remove(20)
pfiledate = pfiledate.Remove(7, 5)
Dim ftempDirectory As String
= "M:\Archive\DataP\" + pfiledate & "\"
If Not Directory.Exists(ftempDirectory) Then
Directory.CreateDirectory(ftempDirectory)
Dim destdirectory As String = ftempDirectory
Dim ff As String = files(i)
fileToDelete = ff
File.Move(ff, destdirectory + objInfo.Name)
File.Delete(ff)
Else
Dim destdirectory As String = ftempDirectory
Dim ff As String = files(i)
fileToDelete = ff
File.Move(ff, destdirectory + objInfo.Name)
File.Delete(ff)
End If
End If
Continue For
End If
Dim filedate As String = objInfo.Name.Remove(20)
filedate = filedate.Remove(7, 5)
Dim tempDirectory As String = String.Empty
tempDirectory = "M:\Archive\DataE\" + filedate & "\"
If Not Directory.Exists(tempDirectory) Then
Directory.CreateDirectory(tempDirectory)
Dim destdirectory As String = tempDirectory
Dim ff As String = files(i)
fileToDelete = ff
File.Move(ff, destdirectory + objInfo.Name)
File.Delete(ff)
Else
Dim destdirectory As String = tempDirectory
Dim ff As String = files(i)
fileToDelete = ff
File.Move(ff, destdirectory + objInfo.Name)
File.Delete(ff)
End If
Catch ex As Exception
If ex.Message.Contains("already exists") Then
File.Delete(fileToDelete)
Console.WriteLine("DELETING OLD FILE " & fileToDelete)
End If
Continue For
End Try
Next
Next
End Sub
Not sure if the logic makes sense but basically it searches all subfolders for files. Strips the filename to get the date and name which indicates where the file should go. Use the date to create a folder in the destination directory and move files accordingly. If someone can help get started or propose a better way to do this I would really appreciate it.

Not looking too closely (indeed, hardly at all) at your .NET code, it looks like you want to find all of the files in or below a given directory, extract a string from a fixed position in the filename to use as a destination directory, and then move each file to that directory. If that is indeed what you are trying to do, it is fairly simple. To move each file in or below the directory /p/a/t/h to /path2/xxx where xxx is taken from positions 7 to 10 in the file name (I selected the indexes 7 and 10 randomly), just do:
find /p/a/t/h -type f -exec sh -c 'd="/path2/${0:7:3}";
mkdir -p "$d"; mv -i "$0" "$d"' {} \;
The -i flag to mv will cause an interactive prompt if you are overwriting any files, and is here as a safety catch to help prevent the unwary from blowing away files. (But you, the reader, would never execute any code that you don't fully understand, so this is not necessary!) You may want to replace it with a -f or just remove it. Also note that the double quotes are only necessary if your filenames are pathological. (For example, if they contain whitespace.)

Related

Search files based on the date modified entered by user in console application VB.NET

i been given a assignment to create one console application using VB.NET. The assignment will able to open the file that based on the date modified entered by user. can anyone help me to solve my problem. I'm new in vb.net and most of the tutorial are using C# . together i put the latest code i has already done but still if i put the date modified the error file will display .
Thank you in advance
Imports System.IO
Module Module3
Sub Main()
While True
' Read value.
Dim s As DateTime = Console.ReadLine()
' Test the value.
If s = File.GetLastWriteTime("path") Then
Dim p As New Process()
p.StartInfo = New ProcessStartInfo("notepad.exe", "path")
p.Start()
Else
Dim p As New Process()
p.StartInfo = New ProcessStartInfo("notepad.exe", "path2")
p.Start()
End If
' Write the value.
Console.WriteLine("You typed " + s)
End While
End Sub
End Module
in the code snippet you are not searching for a file you are setting the time last modified which isn't what you want to do.
you will need to search through each file until you find the date modified information which is inputted by the user:-
dim s as datetime = console.readline()
'Target Directory
Dim directory = "C:\Users\Peter\Desktop\TestFolder\"
For Each filename As String In IO.Directory.GetFiles(directory, "*", IO.SearchOption.AllDirectories)
Dim fName As String = IO.Path.GetExtension(filename)
dim datemod as string = File.GetLastWriteTime(directory & fname)
If s = datemod Then
Dim p As New Process()
p.StartInfo = New ProcessStartInfo("notepad.exe", directory & fname)
p.Start()
Else
'do something else
endif
next
things that you will need to add are, what to do when it doesn't find a file with that variable.
hope this gets you a little further.

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)

VB Saving img file with path adds folder name to file name

Hi I am having some problems with saving img files using Visual Basic, the files are being named wrongly with the folder name being added to the start of the file name.
I parse a web address and then use the split address values to rename my files however the the path value seems to be added to the file as well.
The files in the photo should be named for example "DCAT040iMBE Test13.jpg"
but this file is being name "Test1DCAT040iMBE Test13.jpg"
Protected Sub GeneratedCode()
Dim path As String = "C:\Users\Grey\Documents\visual studio 2010\Projects\QRCodeGenerator\QRCodeGenerator\Output\"
LogoUpload.SaveAs(path + LogoUpload.FileName)
TextFile.SaveAs(path + TextFile.FileName)
Dim lines() As String = IO.File.ReadAllLines(path + TextFile.FileName)
For Each line As String In lines
Dim count As Integer
Dim encoder As New QRCodeEncoder()
encoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.H
encoder.QRCodeScale = 10
Dim img As Bitmap = encoder.Encode(line)
Dim logo As System.Drawing.Image = System.Drawing.Image.FromFile(path + LogoUpload.FileName)
Dim left As Integer = (img.Width / 2) - (logo.Width / 2)
Dim top As Integer = (img.Height / 2) - (logo.Height / 2)
Dim g As Graphics = Graphics.FromImage(img)
Dim parseLine = line
Dim replaceDelimiter As String
If Not String.IsNullOrWhiteSpace(line) Then
replaceDelimiter = Replace(line, "&", "=")
End If
Dim fileNameSplit() As String = replaceDelimiter.Split("=")
Dim newFileName As String
Dim partTwo = fileNameSplit(1)
Dim partSix = fileNameSplit(5)
Dim objFSO
Dim newFolder As String
newFolder = "C:\Users\Grey\Documents\visual studio 2010\Projects\QRCodeGenerator\QRCodeGenerator\Output\" + partSix
objFSO = CreateObject("Scripting.FileSystemObject")
If (Not System.IO.Directory.Exists(newFolder)) Then
System.IO.Directory.CreateDirectory(newFolder)
End If
count += 1
g.DrawImage(logo, New Point(left, top))
newFileName = partTwo & " " & partSix & count & ".jpg"
img.Save(newFolder + newFileName, ImageFormat.Jpeg)
amountCreatedLbl.Text = count & " QRCodes Created"
logo.Dispose()
Next
End Sub
Could it be that I am generating my newFolder Values wrongly?
edited to add an example of data from the parsed txt file.
https://mywebsite.com/QRCode/default.aspx?materialcode=DTAT050&Logo=MyLogo&Companyloc=Test1
https://mywebsite.com/QRCode/default.aspx?materialcode=DCAT055iMB&Logo=MyLogo&Companyloc=Test1
https://mywebsite.com/QRCode/default.aspx?materialcode=DCAT040iMBE&Logo=MyLogo&Companyloc=Test1
https://mywebsite.com/QRCode/default.aspx?materialcode=DTAB060&Logo=MyLogo&Companyloc=Test1
https://mywebsite.com/QRCode/default.aspx?materialcode=DTAT050&Logo=MyLogo&Companyloc=Test2
https://mywebsite.com/QRCode/default.aspx?materialcode=DCAT055iMB&Logo=MyLogo&Companyloc=Test2
https://mywebsite.com/QRCode/default.aspx?materialcode=DCAT040iMBE&Logo=MyLogo&Companyloc=Test2
https://mywebsite.com/QRCode/default.aspx?materialcode=DTAB060&Logo=MyLogo&Companyloc=Test2
https://mywebsite.com/QRCode/default.aspx?materialcode=DTAT050&Logo=MyLogo&Companyloc=Test3
https://mywebsite.com/QRCode/default.aspx?materialcode=DCAT055iMB&Logo=MyLogo&Companyloc=Test3
https://mywebsite.com/QRCode/default.aspx?materialcode=DCAT040iMBE&Logo=MyLogo&Companyloc=Test3
https://mywebsite.com/QRCode/default.aspx?materialcode=DTAB060&Logo=MyLogo&Companyloc=Test
Looks like you are missing a slash on the line:
img.Save(newFolder + newFileName, ImageFormat.Jpeg)
It should be:
img.Save(newFolder + "\" + newFileName, ImageFormat.Jpeg)
The program doesn't realize that the newDirectory variable is supposed to be a directory, it's just being concatenated to the filename directly. A better option would be to use:
img.Save(System.IO.Path.Combine(newFolder, newFileName), ImageFormat.Jpeg)
The System.IO.Path.Combine() function automatically adds the missing slash between the directory and filename, as well as some additional checks to make sure the result is valid.
As a side note, I would also recommend using & instead of + when joining strings together. Hard to debug issues can come up when you do it that way. I would also recommend turning Option Strict On, you will see a couple of other warnings that come up with your code as is. But, to resolve your issue, the above will work.

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

Resources