Visual Basic 2008 File Search - vb.net

I need a file search for my Visual Basic 2008 program. Do you guys know a way to start off? I've heard that you need admin priveledge for some file searches, but I don't want any of those kind of things since it would be a bug to the user.

The System.IO.Directory Class should help you here.
Also you may want to build a catalog system or find a system that supports an API. This way you dont have to walk a directory structure every time the user performs a query.
Basically you can do (pseudo code, adjust to fit):
Dim fn as File
For Each fn in System.IO.Directory.GetFiles(SomePath,"*.*",System.IO.SearchOption.AllDirectories)
' Do something with the fn
End For
Now there is no way around the NTFS ACL's and you would need to handle this as appropriate.
Have a look at this post to hook into Windows Desktop Search from C#.
Microsoft Windows Search 3.x SDK
Brief Description
Version 1.0
Download the Windows Search Software
Development Kit to explore sample
applications and develop using Visual
Studio, C#, and .NET technology.
Update 1
Function that does things with files in directories (pseudo code, adjust to fit):
Public Function MyDirectoryFunction(ByVal dir as String, ByVal fileMatch as String, ByVal beRecursive as Boolean)
Dim fn as File
Dim searchOpt as System.IO.SearchOption
If beRecursive = True Then
searchOpt = System.IO.SearchOption.AllDirectories
Else
searchOpt = System.IO.SearchOption.TopDirectoryOnly
End If
If String.IsNullOrEmpty(fileMatch) Then
fileMatch = "*.*"
End If
For Each fn in System.IO.Directory.GetFiles(dir, fileMatch, searchOpt)
' Do something with the fn
End For
End Function

Related

An issue with reading DB when program runs at startup in vb.net

I'm new here and to vb.net and I'm stuck on something that I feel SHOULD be simple to resolve. I setup my program to let the user decide if he or she wants to have the program run at windows start. It actually works fine as it is assigning the registry value to CurrentUser instead of Local Machine because of admin rights needing to be bypassed. However, when I restart my computer the program comes up like normal, but it will not read my access db that is located in the same folder as the program; it tries to read the DB from Windows\System32.
Is there a way to force it to read from the executablepath instead of System32?
Here is my simple code:
Private Sub startup()
If cbStartup.Checked = True Then
My.Computer.Registry.CurrentUser.OpenSubKey("Software").OpenSubKey("Microsoft").OpenSubKey("Windows").OpenSubKey("CurrentVersion").OpenSubKey("Run", True).SetValue("CC_List", System.Windows.Forms.Application.ExecutablePath)
ElseIf cbStartup.Checked = False Then
My.Computer.Registry.CurrentUser.OpenSubKey("Software").OpenSubKey("Microsoft").OpenSubKey("Windows").OpenSubKey("CurrentVersion").OpenSubKey("Run", True).DeleteValue("CC_List", False)
End If
End Sub
So when the O/S starts your program the Current Directory is %windir%\System32.
You need to either adjust all your existing paths to be explicitly relative to Application.ExecutablePath, or put
My.Computer.FileSystem.CurrentDirectory = My.Application.Info.DirectoryPath
at the start of your program (which is the modern version of ChDir ...).

How to edit SSIS packages programatically in VB?

We have created a workflow process as an SSIS package and would like to find a way of gaining access to this code so that through vb.net we can dynamically access and run that code. For example, we would like to change the data sources being used, or change the column mappings of existing packages and then execute them from a vb.net application. Please advise the best way to do this.
You will find some of your tasks easy, others not so much.
Generally speaking, you'll be interested in reading the Developers Guide to Integration Services. Of particular interest will be Building Packages Programmatically and Running and Managing Packages Programmatically.
For example, to run a package from VB.NET
Imports Microsoft.SqlServer.Dts.Runtime
Module Module1
Sub Main()
Dim pkgLocation As String
Dim pkg As New Package
Dim app As New Application
Dim pkgResults As DTSExecResult
pkgLocation = _
"C:\Program Files\Microsoft SQL Server\100\Samples\Integration Services" & _
"\Package Samples\CalculatedColumns Sample\CalculatedColumns\CalculatedColumns.dtsx"
pkg = app.LoadPackage(pkgLocation, Nothing)
pkgResults = pkg.Execute()
Console.WriteLine(pkgResults.ToString())
Console.ReadKey()
End Sub
End Module
To change the connection manager programmatically, it'd be the VB.NET equivalent of
ConnectionManager item = ep.Connections["MyConnectionManagerName"]
item.ConnectionString = #"Provider=SQLNCLI10.1;Data Source=Server1;Initial Catalog=ABC;Integrated Security=SSPI;";
Changing column mappings, that's where it's going to get interesting, for all definitions of the word interesting. I'm have a distilled example but it takes some work and you'll want to really understand the whole object model (and I hope you like COM). EzAPI might be of some assistance in that area.

Is it possible to specify a location in a user's home directory for a shared library in VBA (in Office for Mac)?

I'm currently using the VBA code similar to the following to specify a location of a shared library for use in communicating (passing a string) from an Office application to a desktop application. The VBA code/macros will need to exist in an add-in (.ppa).
Private Declare Sub sharedLibPassString CDecl Lib "/Users/myUserName/Library/Application Support/myCompanyName/MySharedLib.dylib" Alias "PassString" (ByVal aString As String)
In code from a VBA Macro, I then can do the following.
Call sharedLibPassString(myString)
I've got the communication working, but I'd like to replace the /Users/myUserName/ part with the current user's home directory. Normally on a Mac, you'd specify ~/Library/Application Support/..., but the ~/ syntax doesn't work, producing a "File not found" runtime error.
I discovered that using the following Environment Variable method gets me the ~/ location that I need:
Environ("HOME")
However, I don't see a way to make this part of the CDecl Lib statement, since, as far as I can tell, Environ is evaluated at runtime.
Is there any way to specify a location of a shared library in the user's home directory (~/) in VBA?
Here are a few notes about my environment/approach:
I'm using a Mac, though I believe if there is a solution it would be similar on a PC.
I don't believe it shouldn't matter, but the Office application I'm using is PowerPoint (2011).
The reason I'm trying to access an area inside of the Application Support directory, instead of the default location for shared libraries is because I'd like the Desktop application to place the shared library in a location without an installer, and without requiring a user's or administrator's privileges. If there is a better solution or location to accomplish the same task, this would be very helpful as well.
Sorry for giving a long response, I just wanted to make sure I explained this fairly well.
From this page (Anatomy of a Declare Statement) we read that
The Lib keyword specifies which DLL contains the function. Note that
the name of the DLL is contained in a string within the Declare
statement.
(emphasis added)
From experimentation, the VBE scolds me if I try to give anything but a string constant.
The only work around that I'm aware of requires rewriting the string constant at runtime.
Here is an example of how this could be done: Let's say your delaration statement is in Module1 in your current project, and that you deliberately wrote the declaration in this format at the top of your module:
Private Declare Sub sharedLibPassString CDecl Lib _
"/Users/myUserName/Library/Application Support/myCompanyName/MySharedLib.dylib" _
Alias "PassString" (ByVal aString As String)
You can access that module via code through this (requires permissions to VBA in trust Center listed under Developer Macro Settings):
Dim myModule
set myModule = ActivePresentation.VBProject.VBComponents("Module1").CodeModule
Once you've gained the CodeModule, you can replace the 2nd line directly:
myModule.ReplaceLine 2, Environ("HOME") & " _"
Mission accomplished!
If you do this, you will need to update the path prior to attempting to call your declared sub. There must be a break in execution that allows VBA to recognize the change. Also, you will not be able to modify the code while in break mode.
Now if I were doing this, I'd want to make sure I replace the right line, to not break code. You can check the contents of the 2nd line by calling this myModule.Lines(2,1) which will return the string value of the line.
However, here is a more robust solution that will find the correct line and then replace it (assumes myModule has already been defined as listed above):
Dim SL As Long, EL As Long, SC As Long, EC As Long
Dim Found As Boolean
SL = 1 ' Start on line 1
SC = 1 ' Start on Column 1
EL = 99999 ' Search until the 99999th line
EC = 999 ' Search until the 999th column
With myModule
'If found, the correct line will be be placed in the variable SL
'Broke search string into two pieces so that I won't accidentally find it.
Found = .Find("/Users/myUserName/Library/Application Support/myCompanyName/" & _
"MySharedLib.dylib", SL, SC, EL, EC, True, False, False)
If Found = True Then
'Replace the line with the line you want, second paramater should be a string of the value.
.ReplaceLine SL, Environ("HOME") & " _"
End If
End With
I don't have a Mac, so this is an incomplete answer and I don't know if it will help, but it's a couple of ideas.
I know on Windows, VB doesn't load an external library until you first try to call a function declared with it, and if you specify only the filename in the declare statement, it will use the system path to look for it. Once I did the same thing you are doing, loading a library from a dynamic path, by specifying only a filename, then making a system API call to set the current working directory to the directory of the library before loading it. Changing the PATH environment variable would probably also work.
Second idea: you could hard-code the path to a filename in the /tmp directory; then automatically copy the desired library to that location before loading it. Watch out for the file being in use by another process, but that's only an error if it is a different version of the file to the one that you want.

Download file in VB.NET 2010

I have looked almost everywhere on the internet and I cannot find a way to download a file from the internet into a specific folder that works with VB.NET 2010. I would like to download a file called, for instance, example.txt, and download it into, for example, %HOMEDRIVE%%HOMEPATH%\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup so that it will run automatically at system startup. All help is appreciated
Guessing something based on...
Using webClient = New WebClient()
Dim bytes = webClient.DownloadData("http://www.google.com")
File.WriteAllBytes(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "MyFileName.ext"), bytes)
End Using
As for the startup, VB.NET has a pretty ease way to add Registry keys...
My.Computer.Registry.SetValue
To set something like HKEY_CURRENT_USER\Software\Microsoft\CurrentVersion\Run
UPDATE
How to: Create a Registry Key and Set Its Values in Visual Basic
http://msdn.microsoft.com/en-us/library/cy6azwf7(v=VS.100).aspx
I would suggest using WebClient.DownloadFile. Use Environment.SpecialFolder.Startup to get the path to save the file.
Sub Main()
Using wc As New WebClient()
Dim startupPath = Environment.GetFolderPath(Environment.SpecialFolder.Startup)
wc.DownloadFile("http://MyDomain.com/MyFile.txt", Path.Combine(startupPath, "test.txt"))
End Using
End Sub

How to get file size from within TSQL (path specified in column) in SSRS 2005

I need to get the Folder size and display the info on a report (SSRS). I need to do this for a number of Databases (loop!). These DB's are websites' backends.
Are any samples available for this? Does xp_filesize and the like the right solution?
Looking at the question and Tomalak's response, and I'm assuming the reporting server will be able to reach the folders held in the DB:
Firstly set up the query to get you back the result-set of paths - I assume you'll have no trouble with this part. Next you'll need to add a custom code function to your report: http://msdn.microsoft.com/en-us/library/ms155798.aspx - This function will take the folder path as a parameter, and pass back the size of the folder. You'll have to write in VB.Net if you want to embed the code in the report, or you could code up a DLL and bring that in.
An example VB.Net code block (Remember you may need to prefix objects with System.IO.) http://www.freevbcode.com/ShowCode.asp?ID=4287
Public Shared Function GetFolderSize(ByVal DirPath As String, _
Optional IncludeSubFolders as Boolean = True) As Long
Dim lngDirSize As Long
Dim objFileInfo As FileInfo
Dim objDir As DirectoryInfo = New DirectoryInfo(DirPath)
Dim objSubFolder As DirectoryInfo
Try
'add length of each file
For Each objFileInfo In objDir.GetFiles()
lngDirSize += objFileInfo.Length
Next
'call recursively to get sub folders
'if you don't want this set optional
'parameter to false
If IncludeSubFolders then
For Each objSubFolder In objDir.GetDirectories()
lngDirSize += GetFolderSize(objSubFolder.FullName)
Next
End if
Catch Ex As Exception
End Try
Return lngDirSize
End Function
Now, in your report, in your table, you'd have for the cell that shows the folder size an expression something like:
=Code.GetFolderSize(Fields!FolderPath.Value)
I doubt this approach will be performant for a manually-viewed report, but you might get away with it for small result sets, or a scheduled report delivered by email?
Oh, and this piece suggests you 'may' run into permissions issues using System.IO from within RS: http://blogs.sqlxml.org/bryantlikes/pages/824.aspx
Could you clarify who should do what in your scenario? Do you want SQL Server do get the info or do you want Reporting Server do that?
What exactly do you mean by "folder size"? Is "one folder, sum up each file" enough or does it need to be recursive? Either way, I'd go for a little custom .NET function that uses System.IO.Directory and it's relatives.
I'd consider splitting this into two pieces, maybe a Windows Service to scan the directories and aggregate the data into a database, then use SSRS to report on the database as usual.
The reason I suggest this is to use master..xp_filesize and it's kin the account the SQL Server service is starting with needs access to the paths to be scanned. Once this turns into accessing paths on other machines I'd be less comfortable with the security implications of that.
Hope this helps
In SSRS you can to do this with the help of custom data extension. U need give the path for the datasource as your folder name and it will retrive your files and its related informations and displayed
For further reference and custom dll use this
http://www.devx.com/dbzone/Article/31336/0/page/4
I have done this earlier.
Note: you have to make related changes to Report Designer and Report Manager configuration files.