Check for file on a remote server in Classic ASP [duplicate] - asp-classic

Is there a good way to access network shares from within a VBS script, with alternative credentials (not the credentials with which the VBS script is running)?
The intention is to perform two tasks:
programmatically navigate a remote share file structure, in order to confirm that a couple of remote files exist, and copy one file over the other (both remote)
copy files from a local drive (accessed with local username / permissions) to a remote drive (accessed with the alternate credentials)
As far as I can tell FSO (Scripting.FileSystemObject) is out of the picture, because it always runs with the credentials of the application using it - which would be the local machine user.(?)
The only viable-seeming approach I have found while googling to prepare a Batch file (or extended call to "cmd.exe") that uses "net use" to provide the remote share credentials, and then copies the files with robocopy or the like, from within the same command-shell "session". This would work OK for copying/deploying files from the local drive to the remote share, but it would ve very complicated and brittle to do any sort of file system browsing (like you would do with FSO) in this way.
Another possibility I have considered involves having two scripting sessions - you call the script (providing the alternate credentials in the command line) and it runs a cmd.exe session, which first does a "net use" to map the remote share to a temporary local drive, then runs itself in an "actually do stuff" mode and uses FSO, then when it's done (back in the cmd.exe shell) disconnects the temporary drive with "net use" again. This is clunky (multiple windows, temporary drive...) and I'm not even sure it would work.
Does anybody know either way, or know of a viable alternative? (sticking to VBScript / WScript on a windows 2000 machine - no PowerShell!)

OK, I was laboring under a misconception - that FSO would not "pick up" the network credentials established with "NET USE" (or Wscript.Network "MapNetworkDrive").
It turns out that it does, and the following sample code works very nicely (without needing to set up temporary network drives):
ServerShare = "\\192.168.3.56\d$"
UserName = "domain\username"
Password = "password"
Set NetworkObject = CreateObject("WScript.Network")
Set FSO = CreateObject("Scripting.FileSystemObject")
NetworkObject.MapNetworkDrive "", ServerShare, False, UserName, Password
Set Directory = FSO.GetFolder(ServerShare)
For Each FileName In Directory.Files
WScript.Echo FileName.Name
Next
Set FileName = Nothing
Set Directory = Nothing
Set FSO = Nothing
NetworkObject.RemoveNetworkDrive ServerShare, True, False
Set ShellObject = Nothing
Set NetworkObject = Nothing

Related

Read from VisualFoxPro .DBF remote location

I have problem with connecting to DBF files on remote location using OleDb.
When I use local path everything works fine.
My connection string:
string path_dbf = #"\\server\directory";
OleDbConnection conn = new OleDbConnection(#"Provider=VFPOLEDB.1;Data Source="+path_dbf+";");
I've tried to use OleDb and Odbc, but both have failed when I use remote location. I also try to use mapped directory under the OS, but it doesn't work.
I get error:
Error: Sys.Net.WebServiceFailedException: The server method 'MethodName' failed with the following error: System.Data.OleDb.OleDbException-- Invalid path or file name.
I also try to use Odbc DSN like this:
OdbcConnection conn = new OdbcConnection("dsn=MyDsnName;");
but it doesn't work. MyDsnName is Free Table directory type and it points to my mapped remote directory.
I don't have idea of any possible solution.
So I want to ask if there is a maybe some additional connection string options to do that or I do something wrong.
Thanks.
It is probably a permissions issue when running as a web app. The user which may be something like "USR_MACHINE" may not have proper permissions to the other server location and thus failing.
To confirm this, try changing your website service to "Run As" some other user that DOES have permissions, such as yourself... if STILL not a problem, then try running .net as the ADMINISTRATOR FOR CONFIRMATION PURPOSES ONLY, then revert back to the USR_MACHINE account.
Once you have confirmed, then you might want to create a somewhat restricted user so they only have access to the folder and features you want them to for security purposes.

Difference between starting process from Console applciation and ASP.NET application

I have a Web API application that needs to run a Python script which in turn runs a Perl script:) does some otehr stuff and get the output results from it.
The way I do this is with starting a Process:
var start = new ProcessStartInfo()
{
FileName = _pythonPath, //#"C:\Python27\python.exe",
Arguments = arguments, //#"D:\apps\scripts\Process.py
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true
};
using (Process process = Process.Start(start))
{
using (StreamReader reader = process.StandardOutput)
{
var result = reader.ReadToEnd();
var err = process.StandardError.ReadToEnd();
process.WaitForExit();
return result;
}
}
The script inside tries to connect to Perforce server using P4 Python API and then Perl script call a P4 command as well. When running this code from Console application, everything goes fine. The program automatically gets the Perforce settings (I've got a P4V client with all the settings specified). But when running from ASP.NET Web API, it doesn't get the settigns and says that it cannot conenct to perforce:1666 server (I guess this is the standard value when no settign specified).
I do understand that not so many people use Perforce, especially in such way and can help here, but would like to know what is the difference between running this script from Console app and Web API app that mich cause this different behaviour.
One of the most obvious differences between running code from a console application and running code in IIS* is that, usually, the two pieces of code will be running under different user accounts.
Frequently, if you're experiencing issues where code works in one of those situations and not the other, it's a permissions or a per-user-settings issue. You can verify whether this is the case by either running the console application under the same user account that is configured for the appropriate IIS application pool, or vice verse, configure the application pool to use your own user account, and then see whether the problem persists.
If you've confirmed that it's a permissions issue and/or per-user-settings, then you need to decide how you want to fix it. I'd usually recommend not running IIS application pools under your own user account - if you cannot seem to get the correct settings configured for the existing application pool user, I'd usually recommend creating a separate user account (either locally on the machine or as part of your domain, depending on what's required) and giving it just the permissions/settings that it requires to do the job.
*IIS Express being the exception here because it doesn't do application pools and the code does end up running under your own user account.

Adding printer via VBS script

I hope someone can help me with following issue:
I'm trying automatically install network printer: first script asks user for his network credentials and then run second one, installing a printer. Problem is: scripts not throws any errors but no printer added:
Dim objNetwork
Set objNetwork = CreateObject("WScript.Network")
set objShell = WScript.CreateObject("WScript.Shell")
strUserName = InputBox("What is your username? (domain\username)")
objShell.Run "runas /user:" & strUserName & " ""wscript.exe C:\pbg.vbs"" "
pbg.vbs:
Dim objNetwork
Set objNetwork = CreateObject("WScript.Network")
objNetwork.AddWindowsPrinterConnection "\\10.100.1.29\Canon"
objNetwork.SetDefaultPrinter "\\10.100.1.29\Canon"
I made such two-file design because first part is run during boot time and user key-in his username/pass (there can be different users at this shared workstation) and then script use username/pass to call second part of script which is installing network printer
Thank You in advance
You could make the connection in your VBScript to the print server by authenticating right inside the connect string with the user ID/Password.
Place the code you have in front of the code you have for PBG.vbs and do t all within the code itself (faster/cleaner). You could make PBG.vbs a function within new code too.
Here are some links with the different ways:
http://msdn.microsoft.com/en-us/library/aa389290%28v=vs.85%29.aspx
Secure LDAP object manipulation with VBscript using alternate credentials
How to make an Active Directory query from VBScript on a non-domain computer using domain credentials
Doing the same thing basically with Active Directory groups that install printers for users in various parts of the building. Just add them to the group and the associated script fires and installs the printer local to that area of the building.
Since you're also working with a domain environment you don't need the first script. When the user logs on the second script would execute using rights obtained from credentials used during windows log on and the printer would install for them.

SQLite: Cannot open network file programmatically, even though worked before

I have used the code below to open a SQLite database file that sits on a network computer for more than a year now almost on a daily basis. Suddenly this morning, I am not able to open the file programmatically.
private Boolean Connect(String strPathFile)
{
// Initialize the connection object.
this.DbConnection = null;
try
{
// DATABASE: Create the connection string and set the settings.
String strConnection = #"Data Source=" + strPathFile + #";Version=3;";
// DATABASE: Connect to the database.
this.DbConnection = new SQLiteConnection(strConnection);
this.DbConnection.Open();
return true;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return false;
}
The file is a network resource in the form "\Server\ShareName\FileName.db" (less the double quotes).
Here is the interesting thing. SQLite Administrator has no issues opening up the network database file, none, and repeatedly. I can also open up the file locally. I copied the file to my local drive and simply changed the path inside Visual Studio 2012 (VS2012).
The server seemed fine. It had gone through a reboot at some point since the last time that I checked on it. I presume a Microsoft Update. File Explorer has no issues browsing the folder, and as I said SQLite Administrator can open the network file.
I checked once again on permissions and everyone has full control as well as the server's users have full control, both on the security permissions and on the share permissions. I checked the folder and file, and permissions are the same. I expected as much, because SQLite Administrator can open the file. The server does not have a firewall set up, Windows Firewall or otherwise. I rechecked that this morning as well. Again, SQLite Administrator would have complained about that.
I verified writing, by making a copy of the file on the network drive using File Explorer. That had no issues.
The sever is a Windows Server 2003. I am using Windows 7 Professional 64-bit.
I also tried to open up the database in read only mode, but that failed as well. I was expecting that behavior. SQLite Administrator still works nicely.
I tried various other connection strings including SQLiteConnectionStringBuilder() just to see what happens, and all roads lead to Rome, namely:
System.Data.SQLite.SQLiteException occurred
HResult=-2147467259
Message=unable to open database file
Source=System.Data.SQLite
ErrorCode=14
StackTrace:
at System.Data.SQLite.SQLite3.Open(String strFilename, SQLiteConnectionFlags connectionFlags, SQLiteOpenFlagsEnum openFlags, Int32 maxPoolSize, Boolean usePool)
at System.Data.SQLite.SQLiteConnection.Open()
at SQL.cSQL.Connect(String strPathFile) in C:\<Path to source file>:line 367
InnerException:
Thoughts?
in version > 1.0.82.0
Double the leading two backslashes in the file name
(e.g. "\\\\network\share\file.db").
Use a mapped drive letter.
Use the SQLiteConnection constructor that takes the parseViaFramework
boolean argument and pass 'true' for that argument.
See the SQL post here
Assuming the db file is accessible (e.g. "because SQLite Administrator can open the file"), then option #2 from the answer by ranmoro and GEEF seems to work. This becomes:
bool parseViaFramework = true;
con = new SQLiteConnection( cs, parseViaFramework );
in code. The rationale is discussed in the SQLite check-in comment "mistachkin added on 2013-05-25 21:06:45" in https://system.data.sqlite.org/index.html/info/bbdda6eae2
My connection strings are of the form:
URI=file:\\SERVER\Data\SqlData\History.db
for UNC paths, or
URI=file:C:\Data\SqlData\History.db
for local paths.
I am using:
Visual Studio 2022
<TargetFramework>net5.0-windows</TargetFramework>
<PackageReference Include="System.Data.SQLite.Core" Version="1.0.115.5" />
I had a similar issue. Replacing the UNC (\server\share\folder\file.db) with a mapped drive path (S:\folder\file.db) resolve the issue in my instance.
The error message is very misleading + irritating. Applications working fine in the local environment get failed to start in client server situation.
It has mostly noting to do with the code. Its related to server side.
Make sure the Write access is available for the server folder containing the file.
UNC [IP based server path] is not supported still, the network path/folder should be mapped to overcome this issue.
Some sites+users are saying to mention the Version No. in the connection string. All my applications are working fine without using it.
Connection String:
Data Source=[Mapped Server Location]\[SubFolders]\[FileName].db;
Update:
I tried to prepend \\ to the UNC path and it worked (added additional \\ in the beginning only, not in-between).
Data Source=\\[UNC]\[SubFolders]\[FileName].db;

Programmatically open an email from a POP3 and extract an attachment

We have a vendor that sends CSV files as email attachments. These CSV files contain statuses that are imported into our application. I'm trying to automate the process end-to-end, but it currently depends on someone opening an email, saving the attachment to a server share, so the application can use the file.
Since I cannot convince the vendor to change their process, such as offering an FTP location or a Web Service, I'm stuck with trying to automate the existing process.
Does anyone know of a way to programmatically open an email from a POP3 account and extract an attachment? The preferred solution would reside on a Windows 2003 server, be written VB.NET and secure. The application can reside on the same server as the POP3 server, for example, we could setup the free POP3 server that comes with Windows Server and pull against the mail file stored on the file system.
BTW, we are willing to pay for an off-the-shelf solution, if one exists.
Note: I did look at this question but the answer points to a CodeProject solution that doesn't deal with attachments.
Try Mail.dll email component, it's very affordable, supports attachments national characters and is easy to use, it also supports SSL:
Using pop3 As New Pop3()
pop3.Connect("mail.server.com")
pop3.Login("user", "password")
Dim builder As New MailBuilder()
For Each uid As String In pop3.GetAll()
' Receive email message'
Dim mail As IMail = builder.CreateFromEml(pop3.GetMessageByUID(uid))
'Write out received message'
Console.WriteLine(mail.Subject)
'Here you can use mail.Attachmets collection'
For Each attachment As MimeData In mail.Attachments
Console.WriteLine(attachment.FileName)
attachment.Save("c:\" + attachment.FileName)
' you can also use attachment.Data here'
Next attachment
Next
pop3.Close(true)
End Using
You can download it here: http://www.lesnikowski.com/mail.
possible duplication of Reading Email using Pop3 in C#
Atleast, there's a shed load of suggestions there that you may find useful
I'll throw in a late suggestion for a more generalized "download POP3 messages and extract attachments" solution using existing software and minimal programming. I needed to do this for a client who switched to receiving faxes via email and was not pleased with manually saving the attachments to a location where they could be imported into an application.
For downloading messages on *nix systems fetchmail seems to be the standard and is very capable, but I chose mpop for both simplicity and Windows compatibility (but it is cross-platform). If mpop hadn't done the trick for me, I probably would have ended up doing something with the Python-based getmail, which was created when fetchmail's development stalled for a time (it's since resumed).
Mpop is controlled either via command line or configuration file, so I simply created multiple configuration files and specify via command line which file to load. I'm using it in "Exchange pickup directory" mode, which means it simply downloads the messages and drops them as text (.eml) files in a specified directory.
For extraction of the message attachments, UUDeview appears to be the standard (I'm using the Windows port of UUDeview) across just about any system you could want with just about any features you could want. My main alternative to this was a much-less-capable Python script that I'd developed for a different client back in 2007, but I'm happy to go with a precompiled executable over either installing Python or packaging with any of the Python-to-exe options.
Finally there's the configuration - along with the two mpop configuration files mentioned above (which I could do away with by using command-line options), I also have two 2-line .cmd files launched every 10 minutes by scheduled task - the first line to launch mpop to download into a working directory and the second line to launch UUDeview and extract attachments of specified types (.pdf or .tif) then delete each file from which it extracted attachments. Output is sent to another directory from which staff can directly attach files as needed.
This is overall not the most elegant way to reach these ends, but it was quick, simple, functional and reasonably robust - at each stage if something goes wrong it fails such that no data is lost. The only places where data could be lost are any non-attachment messages being sent to the dedicated fax email addresses, and even those will sit in the processing directory and be caught eventually.

Resources