Parse solution using DTE Visual Basic - vb.net

I have to parse my solution to list all files that it is using.
I have created this:
Imports EnvDTE
Imports EnvDTE80
Imports Microsoft.VisualBasic
Imports System.Collections
Public Class C
Implements VisualCommanderExt.ICommand
Sub Run(DTE As EnvDTE80.DTE2, package As Microsoft.VisualStudio.Shell.Package) Implements VisualCommanderExt.ICommand.Run
listing(DTE)
End Sub
Sub listing(DTE As EnvDTE80.DTE2)
Dim prj As Project
Dim prjs As Projects
prjs = DTE.Solution.Projects
For Each prj In prjs
Dim item As String
Dim itemEnum as IEnumerator = prj.GetEnumerator()
itemEnum.Reset()
While itemEnum.MoveNext()
item = itemEnum.Current().FullName
My.Computer.FileSystem.WriteAllText("C:\tmp\list.txt", item, True)
End While
Next
End Sub
End Class
Unfortunately I encounter the Exception:
System.Runtime.InteropServices.COMExcption(0x80020003): Member not found....
My solution has 10 projects.

Navigating projects and files is recursive because they can be nested.
See my articles:
HOWTO: Navigate the files of a solution from a Visual Studio .NET macro or add-in.
HOWTO: Navigate the files of a solution using the IVsHierarchy interface from an add-in.
http://www.visualstudioextensibility.com/articles/add-ins/

Related

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.

Reference to non-shared member requires an object reference

I am writing macro for Visual Studio in VB:
Imports EnvDTE
Imports EnvDTE80
Imports Microsoft.VisualBasic
Public Class C
Implements VisualCommanderExt.ICommand
Sub Run(DTE As EnvDTE80.DTE2, package As Microsoft.VisualStudio.Shell.Package) Implements VisualCommanderExt.ICommand.Run
FileNamesExample()
End Sub
Sub FileNamesExample()
Dim proj As Project
Dim projitems As ProjectItems
' Reference the current solution and its projects and project items.
proj = DTE.ActiveSolutionProjects(0)
projitems = proj.ProjectItems
' List the file name associated with the first project item.
MsgBox(projitems.Item(1).FileNames(1))
End Sub
End Class
And I got this after compilation:
Error (17,0): error BC30469: Reference to a non-shared member requires an object reference.
Have you any ideas what is wrong? I didn't develop in VB earlier and I just need instant help.
DTE is a type, as well as what you've given to the name of a parameter in your Run method. When used in this line:
proj = DTE.ActiveSolutionProjects(0)
It's using the type, rather than an instance of an object. You need to pass through the variable into your method:
Imports EnvDTE
Imports EnvDTE80
Imports Microsoft.VisualBasic
Public Class C
Implements VisualCommanderExt.ICommand
Sub Run(DTE As EnvDTE80.DTE2, package As Microsoft.VisualStudio.Shell.Package) Implements VisualCommanderExt.ICommand.Run
FileNamesExample(DTE)
End Sub
Sub FileNamesExample(DTE As EnvDTE80.DTE2)
Dim proj As Project
Dim projitems As ProjectItems
' Reference the current solution and its projects and project items.
proj = DTE.ActiveSolutionProjects(0)
projitems = proj.ProjectItems
' List the file name associated with the first project item.
MsgBox(projitems.Item(1).FileNames(1))
End Sub
End Class

Debugging SSIS vb.net Script

I am debugging a SSIS vb.net script in a Visual Studio 2005 SSIS project.
Is there a way to execute just the script without having to start in my control flow? Otherwise I have to work through my other steps and drill down through my Script Task into the Editor into the actual script.
As a side not my script is pretty simple, it just creates a directory if a directory with today's date is not found.
Imports System
Imports System.IO
Imports Microsoft.VisualBasic
Imports System.Data
Imports System.Math
Imports Microsoft.SqlServer.Dts.Runtime
Public Class ScriptMain
' Checks to see if todays folder exists on sqlzdocs -> if it doesnt it creates it. Else it errors
Public Sub Main()
Dim todaysdate As String = String.Format("{0:yyyyMMdd}", DateTime.Now)
Dim di As IO.DirectoryInfo = New IO.DirectoryInfo("\\MyServer\Path\Current\" + todaysdate )
If di.Exists = True Then
Dts.Variables("User::FolderExists").Value = True
Else
Try
Dim createdirectory As IO.DirectoryInfo = Directory.CreateDirectory(di.ToString)
Catch ex As Exception
Dts.Variables("User::Errors").Value = "Could not create the directory:" + di.ToString
Dts.Variables("User::FolderExists").Value = False
End Try
End If
Dts.TaskResult = Dts.Results.Success
End Sub
End Class
When i was developing ETL modules that had Script tasks, i followed couple of things to help in testing
Logging the Script task execution points - I wrote simple custom module to handle that
Seperated the functions in the script task and created a seperate Vb.net console project. I executed that project and once it was working successfully, i then included the same in the SSIS project.

Error in VB Function in SSIS but not in VisualStudio

I have some VB.Net code that I'm trying to add to a SSIS package. The code runs fine in VisualStudio 2012 and when I compile it there are no errors and the executable runs as well. When I insert the code into an SSIS package Script Task and copy/paste my code in I'm getting an error in one of my functions:
'Any' is not a member of 'System.Collections.Generic.IEnumerable(Of String)'.
I copied and pasted the main body of the code exactly and inserted one Imports line:
#Region "Imports"
Imports System
Imports System.Data
Imports System.Math
Imports System.IO 'Added this one Imports
Imports Microsoft.SqlServer.Dts.Runtime
#End Region
<Microsoft.SqlServer.Dts.Tasks.ScriptTask.SSISScriptTaskEntryPointAttribute()> _
<System.CLSCompliantAttribute(False)> _
Partial Public Class ScriptMain
Inherits Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase
Public Sub Main()
Dim sDirectoryRoot As String = "\\Server\Drive$\SubFolder\SubFolder2\"
Dim dirList As New DirectoryInfo(sDirectoryRoot)
ListFiles(dirList)
Dts.TaskResult = ScriptResults.Success 'left this line from SSIS default
End Sub
Public Sub ListFiles(ByVal dirList As DirectoryInfo)
Dim bEmpty As Boolean = False
[...] bunch of code with no errors. Actual function call below where clientdir is a directory path
bEmpty = IsDirectoryEmpty(clientdir.ToString)
End Sub
Public Function IsDirectoryEmpty(ByVal path As String) As Boolean
Return Not (Directory.EnumerateFileSystemEntries(path).Any())
End Function
The Directory.EnumerateFileSystemEntries(path).Any is underlined with the 'Any' is not a member of 'System.Collections.Generic.IEnumerable(Of String)' error. I can't figure out why it runs fine in Visual Studio, but when I use the Edit Script button in the Script Task Editor (which starts another instance of Visual Studio) it errors out.
Any is an extension method and, as with all extension methods, requires that you import the appropriate namespace. It is, in fact, the System.Linq.Enumerable.Any method, hence you must import the System.Linq namespace. That's probably done at the project level by default in your non-SSIS project. Note that you will also have to have referenced the System.Core.dll assembly.

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")