Getting filenames from a folder in Sharepoint with VBA - file

I've done alot of research on this and found a number of help sites but still can't understand why this sometimes doesn't work.
I'm trying to access a sharepoint site (to which there are no restrictions for me) and extract all the files in a folder within that site.
Sometimes my Path works and it does it, other times it does not. I have a feeling it works if I've gone into the sharepoint site on my browser before but can't confirm that (because I just tried it again now and it doesnt work ARGGH). But the same code below has worked in the past.
It's failing on the File System Object function below
Public Function GetFullFileName(strfilepath As String, _
strFileNamePartial As String) As String
Dim objFS As Variant
Dim objFolder As Variant
Dim objFile As Variant
Dim intLengthOfPartialName As Integer
Dim strfilenamefull As String
Set objFS = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFS.GetFolder(strfilepath)
'work out how long the partial file name is
intLengthOfPartialName = Len(strFileNamePartial)
For Each objFile In objFolder.Files
'Test to see if the file matches the partial file name
If Left(LCase(Replace(objFile.Name, " ", "")), intLengthOfPartialName) = LCase(strFileNamePartial) Then
'get the full file name
strfilenamefull = objFile.Name
Exit For
Else
End If
Next objFile
'Return the full file name as the function's value
GetFullFileName = strfilenamefull
End Function
I get a "Run-time error '76': Path not found" when it gets to the GetFolder(strfilepath) code
The strfilepath is just a regular sharepoint site name (e.g. like \teams.uk\gm\FX\SharedDocuments\London\11) November 2013\20 November\Reports)
As mentioned I've tried different variations of the file path including DavWWW but nothing seems to work and I dont know what else to try.
Any advice please?
Thanks
Raiyan

The webclient service must be started to Access SharePoint using the FileSystemObject.
This service is often not started when you first log on. However as you access SharePoint via the normal user interface it gets started. I think this is why your code works inconsistently.
If you have admin rights on the local machine you can start the service manually (or using code). However if you don't have rights then you can try a trick - it's clumsy but works.
Using VBA code open a known SharePoint folder in explorer view then close it. This will trigger webclient to start.

Related

prompt for users to browse database connection if current database connection fails

I am building a data-entry program in vb.net that 5 people will share using, and I have problems setting the right database connection. It would do basic things like: pulling up the stock units, save job, load jobs operations.
The database I'm using is Access database (.mdb). This database will be located in a local server drive (mine is in Z drive) and the connection string looks like this
Provider=Microsoft.Jet.OLEDB.4.0;Data Source="Z:\Jimmy's Files\Quality Enclosures.mdb"
This works fine on my computer, but the problem is it does not work on my coworkers computer.
d (\dc-qenclosures) (Z:) is the loacation to my local server drive, but on my coworker's computer, it is set up as
d (\dc-qenclosures) (Q:).
So, whenever I open the program on my co-worker's computer, it gives me an error saying that the database Provider=Microsoft.Jet.OLEDB.4.0;Data Source="Z:\Jimmy's Files\Quality Enclosures.mdb" does not exist (which makes sense because it is not under Z: on his computer)
I know how to use the OpenFileDialog to browse for mbd files.. but how do I set this as the new database connection?
I want to create a properties menu to set the database location.
This is the code I have so far to browse for the database file
Private Sub RadButton6_Click(sender As Object, e As EventArgs) Handles RadButton6.Click
Dim myStream As Stream = Nothing
Dim openFileDialog1 As New OpenFileDialog()
openFileDialog1.InitialDirectory = "c:\"
openFileDialog1.Filter = "mdb files (*.mdb)|*.mdb|All files (*.*)|*.*"
openFileDialog1.FilterIndex = 1
openFileDialog1.RestoreDirectory = True
If openFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
Try
myStream = openFileDialog1.OpenFile()
If (myStream IsNot Nothing) Then
myConString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & openFileDialog1.FileName
con.ConnectionString = myConString
con.Open()
End If
Catch Ex As Exception
MessageBox.Show("Cannot read file from disk. Original error: " & Ex.Message)
Finally
' Check this again, since we need to make sure we didn't throw an exception on open.
If (myStream IsNot Nothing) Then
myStream.Close()
End If
End Try
End If
End Sub
I'd second #OneFineDay's suggestion of trying the UNC path first, but to answer your main question of browsing for and saving a database path, you may want to look at storing elements of your connection string in My.Settings, so you could make the path a user-level setting. There's an MSDN article with examples here:
Using My.Settings in Visual Basic 2005
In short, you'd have the code sample you shared save the value to My.Settings.DataPath (or whatever you decide to call the setting). Then when you're connecting to the database and need the connection string, you'd make it read from My.Settings.DataPath.
Of course, that'd store your path to the database in a plain-text app.config file by default, so you'll want to be conscious of that and take appropriate steps if there are any security concerns around your app or database.

How can I read a file from a remote computer?

I have a VBScript where I am parsing out information from windowsupdate.log. I had it working locally just fine and when connecting to a server on the same domain as me.
I changed the way I am connecting to servers, I am doing
Set locator = CreateObject("WbemScripting.SWbemLocator")
Set objWmiService = locator.ConnectServer(strComputer,"root\cimv2",strUsername,strPassword)
objWmiService.Security_.ImpersonationLevel = 3
Now, the code that was working is
strFilePath = "\\" & strComputer & "\c$\Windows\windowsupdate.log"
set objFile = objFSO.OpenTextFile(strFilePath)
Do Until objFile.AtEndOfStream
strLine = objFile.ReadLine()
'Logic to parse line
...
loop
But as I said, it only works for localhost or a server on the same domain.
Is there a different way I can get a file, either I'm not searching correctly or it doesn't exist but I can't find a different way.
I was able to find the answer in this post - by creating a temporary network share.
Works well!

Locate Database in debug

I am just added database and while debugging it stops at this line.
Dim con As SqlCeConnection = New SqlCeConnection(Application.StartupPath & "albumDB.sdf")
ERROR 'Format of the initialization string does not conform to specification starting at index 0.'
The database is not going to bin during debug.
I am looking for a way to have this set once it's an executable for any PC so that's why I am not using "C:.........." for path.
Tried moving to "\Resource", with no luck.
Also connection has to be reset after each error. The database has NO password protection.
You must add Data Source= in front of the file path string

Reading a table from a webpage using msxml2.xmlhttp

I have tried to use a webbrowser in my VB program to load a web page and the table on the web page. It works but VERY slowly and a lot of the time it freezes.
I found some sample code that reads the web page without a web browser. It reads the text on the web page and puts it into a Rich Text Box called WebText.
This code works really quick and never locks up but it does not read the text that is in the table on the webpage.
The code I am using calls the function below:
WebText.Text = GetHTMLCode("http://xfinitytv.comcast.net/tv-listings")
Function GetHTMLCode(ByVal strURL) As String
Dim strReturn ' As String
Dim objHTTP ' As MSXML.XMLHTTPRequest
If Len(strURL) = 0 Then Exit Function
objHTTP = CreateObject("MSXML2.XMLHTTP")
objHTTP.open("GET", strURL, False)
objHTTP.send() 'Get it.
strReturn = objHTTP.responseText
objHTTP = Nothing
GetHTMLCode = strReturn
End Function
I am new to programming (hoping to get better with time). If I write something that sounds like I do not know what I am talking about it is probably because I don't. Any help would be appreciate.
Thanks,
Chris

How to avoid SSIS FTP task from failing when there are no files to download?

I'm using SQL Server 2005, and creating ftp tasks within SSIS.
Sometimes there will be files to ftp over, sometimes not. If there are no files, I don't want the task nor the package to fail. I've changed the arrow going from the ftp task to the next to "completion", so the package runs through. I've changed the allowed number of errors to 4 (because there are 4 ftp tasks, and any of the 4 directories may or may not have files).
But, when I run the package from a job in agent, it marks the job as failing. Since this will be running every 15 minutes, I don't want a bunch of red x's in my job history, which will cause us to not see a problem when it really does occur.
How do I set the properties in the ftp task so that not finding files to ftp is not a failure? The operation I am using is "Send files".
Here is some more information: the files are on a server that I don't have any access through except ftp. And, I don't know the filenames ahead of time. The user can call them whatever they want. So I can't check for specific files, nor, I think, can I check at all. Except through using the ftp connection and tasks based upon that connection. The files are on a remote server, and I want to copy them over to my server, to get them from that remote server.
I can shell a command level ftp in a script task. Perhaps that is what I need to use instead of a ftp task. (I have changed to use the ftp command line, with a parameter file, called from a script task. It gives no errors when there are no files to get. I think this solution is going to work for me. I'm creating the parameter file dynamically, which means I don't need to have connection information in the plain text file, but rather can be stored in my configuration file, which is in a more secure location.)
I understand that you have found an answer to your question. This is for other users who might stumble upon this question. Here is one possible way of achieving this. Script Task can be used to find the list of files present in an FTP folder path for a given pattern (say *.txt). Below example shows how this can be done.
Step-by-step process:
On the SSIS package, create an FTP Connection named FTP and also create 5 variables as shown in screenshot #1. Variable RemotePath contains the FTP folder path; LocalPath contains the folder where the files will be downloaed to; FilePattern contains the file pattern to find the list of files to download from FTP server; FileName will be populated by the Foreach loop container but to avoid FTP task design time error, it can be populated with / or the DelayValidation property on the FTP Task can be set to True.
On the SSIS package, place a Script Task, Foreach Loop container and FTP Task within the Foreach Loop container as shown in screenshots #2.
Replace the Main() method within the Script Task with the code under the Script Task Code section. Script Task will populate the variable ListOfFiles with the collection of files matching a given pattern. This example will first use the pattern *.txt, which yields no results and then later the pattern *.xls that will match few files on the FTP server.
Configure the Foreach Loop container as shown in screenshots #3 and #4. This task will loop through the variable **ListOfFiles*. If there are no files, the FTP task inside the loop container will not execute. If there are files, the FTP task inside the loop container will execute for the task for the number of files found on the FTP server.
Configure the FTP Task as shown in screenshots #5 and #6.
Screenshot #7 shows sample package execution when no matching files are found for the pattern *.txt.
Screenshot #8 shows the contents of the folder C:\temp\ before execution of the package.
Screenshot #9 shows sample package execution when matching files are found for the pattern *.xls.
Screenshot #10 shows the contents of the FTP remote path /Practice/Directory_New.
Screenshot #11 shows the contents of the folder C:\temp\ after execution of the package.
Screenshot #12 shows the package failure when provided with incorrect Remote path.
Screenshot #13 shows the error message related to the package failure.
Hope that helps.
Script Task Code:
C# code that can be used in SSIS 2008 and above.
Include the using statement using System.Text.RegularExpressions;
public void Main()
{
Variables varCollection = null;
ConnectionManager ftpManager = null;
FtpClientConnection ftpConnection = null;
string[] fileNames = null;
string[] folderNames = null;
System.Collections.ArrayList listOfFiles = null;
string remotePath = string.Empty;
string filePattern = string.Empty;
Regex regexp;
int counter;
Dts.VariableDispenser.LockForWrite("User::RemotePath");
Dts.VariableDispenser.LockForWrite("User::FilePattern");
Dts.VariableDispenser.LockForWrite("User::ListOfFiles");
Dts.VariableDispenser.GetVariables(ref varCollection);
try
{
remotePath = varCollection["User::RemotePath"].Value.ToString();
filePattern = varCollection["User::FilePattern"].Value.ToString();
ftpManager = Dts.Connections["FTP"];
ftpConnection = new FtpClientConnection(ftpManager.AcquireConnection(null));
ftpConnection.Connect();
ftpConnection.SetWorkingDirectory(remotePath);
ftpConnection.GetListing(out folderNames, out fileNames);
ftpConnection.Close();
listOfFiles = new System.Collections.ArrayList();
if (fileNames != null)
{
regexp = new Regex("^" + filePattern + "$");
for (counter = 0; counter <= fileNames.GetUpperBound(0); counter++)
{
if (regexp.IsMatch(fileNames[counter]))
{
listOfFiles.Add(remotePath + fileNames[counter]);
}
}
}
varCollection["User::ListOfFiles"].Value = listOfFiles;
}
catch (Exception ex)
{
Dts.Events.FireError(-1, string.Empty, ex.ToString(), string.Empty, 0);
Dts.TaskResult = (int) ScriptResults.Failure;
}
finally
{
varCollection.Unlock();
ftpConnection = null;
ftpManager = null;
}
Dts.TaskResult = (int)ScriptResults.Success;
}
VB code that can be used in SSIS 2005 and above.
Include the Imports statement Imports System.Text.RegularExpressions
Public Sub Main()
Dim varCollection As Variables = Nothing
Dim ftpManager As ConnectionManager = Nothing
Dim ftpConnection As FtpClientConnection = Nothing
Dim fileNames() As String = Nothing
Dim folderNames() As String = Nothing
Dim listOfFiles As Collections.ArrayList
Dim remotePath As String = String.Empty
Dim filePattern As String = String.Empty
Dim regexp As Regex
Dim counter As Integer
Dts.VariableDispenser.LockForRead("User::RemotePath")
Dts.VariableDispenser.LockForRead("User::FilePattern")
Dts.VariableDispenser.LockForWrite("User::ListOfFiles")
Dts.VariableDispenser.GetVariables(varCollection)
Try
remotePath = varCollection("User::RemotePath").Value.ToString()
filePattern = varCollection("User::FilePattern").Value.ToString()
ftpManager = Dts.Connections("FTP")
ftpConnection = New FtpClientConnection(ftpManager.AcquireConnection(Nothing))
ftpConnection.Connect()
ftpConnection.SetWorkingDirectory(remotePath)
ftpConnection.GetListing(folderNames, fileNames)
ftpConnection.Close()
listOfFiles = New Collections.ArrayList()
If fileNames IsNot Nothing Then
regexp = New Regex("^" & filePattern & "$")
For counter = 0 To fileNames.GetUpperBound(0)
If regexp.IsMatch(fileNames(counter)) Then
listOfFiles.Add(remotePath & fileNames(counter))
End If
Next counter
End If
varCollection("User::ListOfFiles").Value = listOfFiles
Dts.TaskResult = ScriptResults.Success
Catch ex As Exception
Dts.Events.FireError(-1, String.Empty, ex.ToString(), String.Empty, 0)
Dts.TaskResult = ScriptResults.Failure
Finally
varCollection.Unlock()
ftpConnection = Nothing
ftpManager = Nothing
End Try
Dts.TaskResult = ScriptResults.Success
End Sub
Screenshot #1:
Screenshot #2:
Screenshot #3:
Screenshot #4:
Screenshot #5:
Screenshot #6:
Screenshot #7:
Screenshot #8:
Screenshot #9:
Screenshot #10:
Screenshot #11:
Screenshot #12:
Screenshot #13:
Check this link that describes about gracefully handling task error in SSIS Package.
I had almost the same problem but, with retrieving files. I wanted the package NOT to fail when no files were found on FTP server. The above link stops the error bubbling up and causing the package to fail; something you would have thought FailPackageOnError=false should have done? :-S
Hope this solves it for you too!
I just had this issue, after reading some of the replies here, nothing really sorted out my problem and the solutions in here seem insane in terms of complexity.
My FTP task was failing since I did not allow overwriting files, lets say the job was kicked off twice in a row, the first pass will be fine, because some files are transferred over but will fail if a local file already exists.
My solution was simple:
Right click task - Properties
Set ForceExecutionResult = "Success"
(I can't accept my own answer, but this was the solution that worked for me.)
It may not be the best solution, but this works.
I use a script task, and have a bunch of variables for the ftp connection information, and source and destination directories. (Because, we'll be changing the server this is run on, and it will be easier to change in a config package.)
I create a text file on the fly, and write the ftp commands to it:
Dim ftpStream As StreamWriter = ftpFile.CreateText()
ftpStream.WriteLine(ftpUser)
ftpStream.WriteLine(ftpPassword)
ftpStream.WriteLine("prompt off")
ftpStream.WriteLine("binary")
ftpStream.WriteLine("cd " & ftpDestDir)
ftpStream.WriteLine("mput " & ftpSourceDir)
ftpStream.WriteLine("quit 130")
ftpStream.Close()
Then, after giving it enough time to really close, I start a process to do the ftp command:
ftpParameters = "-s:" & ftpParameterLoc & ftpParameterFile & " " & ftpServer
proc = System.Diagnostics.Process.Start("ftp", ftpParameters)
Then, after giving it some more time for the ftp process to run, I delete the temporary ftp file (that has connection information in it!).
If files don't exist in the source directory (the variable has the \\drive\dir\*.* mapping), then there is no error. If some other error happens, the task still fails, as it should.
I'm new to SSIS, and this may be a kludge. But it works for now. I guess I asked for the best way, and I'll certainly not claim that this is it.
As I pointed out, I have no way of knowing what the files are named, or even if there are any files there at all. If they are there, I want to get them.
I don't have a packaged answer for you, but since no one else has posted anything yet...
You should be able to set a variable in an ActiveX script task and then use that to decide whether or not the FTP task should run. There is an example here that works with local paths. Hopefully you can adapt the concept (or if possible, map the FTP drive and do it that way).
1) Set the FTP Task property ForceExecutionResult = Success
2) Add this code to FTP Task OnError event handler.
public void Main()
{
// TODO: Add your code here
int errorCode = (int)Dts.Variables["System::ErrorCode"].Value;
if (errorCode.ToString().Equals("-1073573501"))
{
Dts.Variables["System::Propagate"].Value = false;
}
else
{
Dts.Variables["System::Propagate"].Value = true;
}
Dts.TaskResult = (int)ScriptResults.Success;
}
Put it in a ForEach container, which iterates over the files to upload. No files, no FTP, no failure.
You can redirect on failure, to another task that does nothing, ie a script that just returns true.
To do this, add the new script task, highlight your FTP task, a second green connector will appear, drag this to the script task, and then double click it. Select Failure on the Value drop down. Obviously, you'll then need to handle real failures in this script task to still display right in the Job history.
Aha, OK - Thanks for clarification. As the FTP task cannot return a folder listing it will not be possible to use the ForEach as I initially said - That only works if you're uploading X amount of files to a remote source.
To download X amount of files, you can go two ways, either you can do it entirely in .Net in a script task, or you can populate an ArrayList with the file names from within a .Net script task, then ForEach over the ArrayList, passing the file name to a variable and downloading that variable name in a standard FTP task.
Code example to suit: http://forums.microsoft.com/msdn/ShowPost.aspx?PostID=2472491&SiteID=1
So, in the above, you'd get the FileNames() and populate the ArrayList from that, then assign the ArrayList to an Object type variable in Dts.Variables, then ForEach over that Object (ArrayList) variable using code something like: http://www.sqlservercentral.com/articles/SSIS/64014/
You can use the free SSIS FTP Task++ from eaSkills. It doesn't throw an error if the file or files don't exist, it support wild cards and gives you the option to download and delete if you need to do so.
Here's the link to the feature page:
http://www.easkills.com/ssis/ftptask
This is another solution that is working for me, using built-in stuff and so without manually re-writing the FTP logic:
1) Create a variable in your package called FTP_Error
2) Click your FTP Task, then click "Event Handlers" tab
3) Click within the page to create an event handler for "FTP Task/OnError" - this will fire whenever there is trouble with the FTP
4) From the toolbox, drag in a Script Task item, and double-click to open that up
5) In the first pop-up, ReadOnlyVariables - add System::ErrorCode, System::ErrorDescription
6) In the first pop-up, ReadWriteVariables - add your User::FTP_Error variable
7) Edit Script
8) In the script set your FTP_Error variable to hold the ReadOnlyVariables we had above:
Dts.Variables["FTP_Error"].Value = "ErrorCode:" + Dts.Variables["ErrorCode"].Value.ToString() + ", ErrorDescription=" + Dts.Variables["ErrorDescription"].Value.ToString();
9) Save and close script
10) Hit "OK" to script task
11) Go back to "Control Flow" tab
12) From the FTP task, OnError go to a new Script task, and edit that
13) ReadOnlyVariables: User::FTP_Error from before
14) Now, when there are no files found on the FTP, the error code is -1073573501
(you can find the error code reference list here: http://msdn.microsoft.com/en-us/library/ms345164.aspx)
15) In your script, put in the logic to do what you want - if you find a "no files found" code, then maybe you say task successful. If not, then task failed. And your normal flow can handle this as you wish:
if (Dts.Variables["FTP_Error"].Value.ToString().Contains("-1073573501"))
{
// file not found - not a problem
Dts.TaskResult = (int)ScriptResults.Success;
}
else
{
// some other error - raise alarm!
Dts.TaskResult = (int)ScriptResults.Failure;
}
And from there your Succeeded/Failed flow will do what you want to do with it.
An alternative is to use this FTP File Enumerator

Resources