SSIS Delete Files older than 30 days - vb.net

I am attempting to use a VB.Net script in SSIS that will delete all files from an archive folder that are older than 30 days (based on creation date) using a VB.Net script. This is the script:
Imports System
Imports System.Data
Imports System.IO
Imports System.Math
Imports Microsoft.SqlServer.Dts.Runtime
<Microsoft.SqlServer.Dts.Tasks.ScriptTask.SSISScriptTaskEntryPointAttribute()>
<System.CLSCompliantAttribute(False)>
Partial Public Class ScriptMain
Inherits Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase
Public Sub Main()
Dim FilePath As String
Dim Days As Integer
Days = CInt(Dts.Variables("User::Days").Value)
FilePath = CStr(Dts.Variables("User::FilePath").Value)
For Each dir As DirectoryInfo In New DirectoryInfo(FilePath).GetDirectories()
For Each file As FileInfo In dir.GetFiles()
If (Now - file.CreationTime).Days > Days Then file.Delete()
Next
Next
End Sub
End Class
Where the FilePath variable (String) = ArchiveFolder file path and Days(INT32) = 30
They have both been set as ReadOnlyVariables.
The script task executes in SSIS "successfully" but is not actually deleting the files.
Any clue why?

Try this
Dim Days = CInt(Dts.Variables("User::Days").Value) * -1
Dim directory As DirectoryInfo = New DirectoryInfo(FilePath)
For Each file In directory.GetFiles("*", SearchOption.AllDirectories)
If (Now.AddDays(Days) <= file.CreationTime) Then file.Delete()
Next

Related

Problem With Zipping An AppData Folder In VB.Net

Code : ZipFile.CreateFromDirectory((Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\Folder"))
"Overload resolution failed because no accessible 'CreateFromDirectory' accepts this number of arguments."
Any Idea Why?
Here is a complete solution, which creates an archive called "tmp.zip" in the current directory, if the source folder exists.
Your example isn't compiling because you have to supply the path of the destination archive as well as the source folder to archive.
Imports System.IO
Imports System.IO.Compression
Module Module1
Sub Main()
Dim destArchive = "tmp.zip"
Dim sourceFolder As String = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "folder")
If Directory.Exists(sourceFolder) Then
If File.Exists(destArchive) Then
File.Delete(destArchive)
End If
ZipFile.CreateFromDirectory(sourceFolder, destArchive)
End If
Console.ReadLine()
End Sub
End Module

Rename files sequentially

with reference to Renaming all files in a folder
on running the below code, get type def errors:
Type 'DirectoryInfo' is not defined
Type 'FileInfo' is not defined
how to resolve these errors. Please suggest.
Dim sourcePath As String = "E:\testrenamerbackup\vbdotnet"
Dim searchPattern As String = "*.doc"
Dim curDir As New DirectoryInfo(sourcePath)
Dim i As Integer = 0
For Each fi As FileInfo In curDir.GetFiles(searchPattern).OrderBy(Function(num) num.CreationTime)
File.Move(fi.FullName, Path.Combine(fi.Directory.FullName, "docFile_" & i & ".doc"))
i += 1
Next
Add Import System.IO on top of your vb.net class file, for example
Imports System
Imports System.IO
Public Class Test
Public Shared Sub Main()
' your code...
End Sub
End Class
System.IO Namespace contains types that allow reading and writing to files and data streams, and types that provide basic file and directory support including DirectoryInfo, FileInfo. by adding Import System.IO you can use those types and methods in the namespace.

Missing Carriage Return in Downloaded Email Attachment ImapX

Here is my code:
#Region "Imports"
Imports System.Text.RegularExpressions
Imports System.Text
Imports Microsoft.VisualBasic.CallType
Imports ImapX
Imports System.Runtime.CompilerServices
Imports System.Security.Authentication
Imports System.IO
Imports ml = System.Net.Mail
Imports System.Net
Imports ImapX.Enums
Imports ImapX.Constants
Imports System.Security.Authentication.SslProtocols
#End Region
Module Module1
Sub Main()
Dim _messages As List(Of ImapX.Message)
Using MyImapClient = New ImapX.ImapClient
With MyImapClient
.Host = ImapServer
.Port = Port
.SslProtocol = Ssl3 Or Tls
.ValidateServerCertificate = True
.Credentials = New ImapX.Authentication.PlainCredentials(UserName, Password)
Dim IsConnected As Boolean = .Connect
.Login()
.Behavior.AutoDownloadBodyOnAccess = False
.Behavior.AutoPopulateFolderMessages = False
.Behavior.MessageFetchMode = MessageFetchMode.Full
.Behavior.ExamineFolders = False
.Behavior.RequestedHeaders = {MessageHeader.From, MessageHeader.[Date], MessageHeader.Subject, MessageHeader.ContentType, MessageHeader.Importance}
'Dim IsInboxSelected As Boolean = .SelectFolder(.Folders.Inbox.Name)
'Dim IsInboxSelected As Boolean = .Folders(.Folders.Inbox.Name).[Select]()
End With
Dim MyFolder As Folder = MyImapClient.Folders.Inbox
_messages = MyFolder.Search().OrderBy(Function(n) n.[Date]).ToList()
_messages.ForEach(Sub(n) n.Download(MessageFetchMode.Full))
_messages.ForEach(Sub(n) n.Download(MessageFetchMode.Full))
End Using
Dim MyAttachment As ImapX.Attachment = _messages.First.Attachments.First
MyAttachment.Download()
Dim FolderPath As String = "C:\Users\AAA\Downloads\"
Dim LocalFileName As String = "1212.txt"
MyAttachment.Save(FolderPath, LocalFileName)
End Sub
End Module
The code works without issue--it connects to the imap server, downloads the first attachment of the first email, which happens to be a .txt file, so I'm saving it as such.
The problem is that the contents of the file is prepended with " * 2 FETCH (" and is followed by " UID 45", and all carriage returns are removed from the file.
Can you please assist? Thanks,
My guess is the CRLF's ( Carriage Return Line Feeds ) are not the format whatever you're viewing the download in is looking for. I would look at your attachment using something like NotePad++ and make sure you're showing Carriage Returns. If all you see are cr's and you're viewing the file in something looking for crlf's then they will get ignored.
Another thing to look at is what default encoding is your .download call using and what encoding is the original attachment in.

How to get R.Net work with VB.Net

I am trying to get R.Net work with VB.NET. I translated an official example from c# to vb.net but it is not working. There are different things I tried. First I used the SetupHelper as explained on the official page.
Imports System.IO
Namespace RDotNetSetup
Public Class SetupHelper
Public Shared Sub SetupPath()
Dim oldPath = System.Environment.GetEnvironmentVariable("PATH")
Dim rPath = If(System.Environment.Is64BitProcess, "C:\Program Files\R\R-3.0.2\bin\x64", "C:\Program Files\R\R-3.0.2\bin\i386")
If Directory.Exists(rPath) = False Then
Throw New DirectoryNotFoundException(String.Format("Could not found the specified path to the directory containing R.dll: {0}", rPath))
End If
Dim newPath = String.Format("{0}{1}{2}", rPath, System.IO.Path.PathSeparator, oldPath)
System.Environment.SetEnvironmentVariable("PATH", newPath)
End Sub
End Class
End Namespace
and
Imports RDotNet
Imports ConsoleApplication36.RDotNetSetup
Imports System.Collections.Generic
Imports System.IO
Imports System.Linq
Imports System.Text
Imports System.Threading.Tasks
Module Module1
Sub Main()
SetupHelper.SetupPath()
Using engine As REngine = REngine.CreateInstance("RDotNet")
engine.Initialize()
Dim charVec As CharacterVector = engine.CreateCharacterVector({"Hello, R world!, .NET speaking"})
engine.SetSymbol("greetings", charVec)
engine.Evaluate("str(greetings)")
Dim a As String() = engine.Evaluate("'Hi there .NET, from the R engine'").AsCharacter().ToArray()
Console.WriteLine("R answered: '{0}'", a(0))
Console.WriteLine("Press any key to exit the program")
Console.ReadKey()
End Using
End Sub
End Module
I dont get an error, using the debugger at engine.Initialize my test stops running ( the green Start arrow reappears).
So I found another example that should (apparentely) works on VB.Net
Imports RDotNet
Imports System.IO
Imports System.Linq
Module Module1
Sub Main()
Dim envPath = System.Environment.GetEnvironmentVariable("PATH")
Dim rBinPath = "C:\Program Files\R\R-3.0.2\bin\i386"
System.Environment.SetEnvironmentVariable("PATH", envPath & Path.PathSeparator & rBinPath)
Dim engine As REngine = REngine.CreateInstance("RDotNet")
Dim group1 As NumericVector = engine.CreateNumericVector(New Double() {30.02, 29.99, 30.11, 29.97, 30.01, 29.99})
engine.SetSymbol("group1", group1)
' Direct parsing from R script.
Dim s = "group2 <- c(29.89, 29.93, 29.72, 29.98, 30.02, 29.98)"
Dim group2 = engine.Evaluate(s).AsNumeric()
Dim testResult As GenericVector = engine.Evaluate("t.test(group1, group2)").AsList()
Dim p As Double = testResult("p.value").AsNumeric().First()
Console.WriteLine("Group1: [{0}]", String.Join(", ", group1))
Console.WriteLine("Group2: [{0}]", String.Join(", ", group2))
Console.WriteLine("P-value = {0:0.000}", p)
End Sub
End Module
Looks like the writer had the same problem and just left the engine.initialize. If I execute the code I get the error: "Value out of range" at Dim group1 As NumericVector = engine.CreateNumericVector(New Double() {30.02, 29.99, 30.11, 29.97, 30.01, 29.99}).
Anyone who could help me get a sample code for VB.NET to work? And explain me why i cannot initialize.
fyi: I checked the path and set all needed references.
Ok, hours of trying and discussion later it works. What I did:
I changed .net 4.5 to .net 4.0
I changed compiler settings from "AnyCPU" to "x86"
First line in the 'SetupPath()' is: System.Environment.SetEnvironmentVariable("R_HOME", "C:\Program Files\R\R-3.0.2")

vb.net how to loop through a directory listing?

How can I loop through a folder getting each file listed and when its date/time?
Use DirectoryInfo.GetFiles() and extract the data (Name, CreationTime, etc.) from the FileInfo class.
I've pasted some code from the MSDN page here.
Imports System
Imports System.IO
Public Class GetFilesTest
Public Shared Sub Main()
' Make a reference to a directory.
Dim di As New DirectoryInfo("c:\")
' Get a reference to each file in that directory.
Dim fiArr As FileInfo() = di.GetFiles()
' Display the names of the files.
Dim fri As FileInfo
For Each fri In fiArr
Console.WriteLine(fri.Name)
Next fri
End Sub 'Main
End Class 'GetFilesTest
For Each LogFile In Directory.GetFiles(Application.StartupPath & "\Txt\")
' do whatever wtih filename
Next
we have the chance to develop in VB.Net (not in Java) and some variable's definitions can be shortened.
I still use GetFiles() and I have added the code to display the DateTime infos.
Imports System
Imports System.IO
...
Dim dir As New DirectoryInfo(sFolderName)
For Each f In dir.GetFiles()
Console.WriteLine(">> FILE-NAME: [" & f.Name & "]")
Console.WriteLine(">> UPDATE-DATE: " & f.lastWriteTime.toString("yyyy-MM-dd"))
Console.WriteLine(">> CREATE-DATE: " & f.creationTime.toString("yyyy-MM-dd"))
Next