Why VBA does not create file via external .exe file? - vba

I have this testing program written in C#. It simply creates a text file in directory where this exe file is.
class Program
{
static void Main(string[] args)
{
string exactPath = Path.GetFullPath("test.txt");
File.Create(exactPath);
Console.ReadLine();
}
}
Now VBA is running it by Call Shell
strProgramName = ActiveWorkbook.path & "\test.exe"
Call Shell("" & strProgramName & "")
Everything seems fine. Except it does not create any file and it should. If I run it manually it does creates a file.
MS documentation for Shell states that :
The Shell function requires unmanaged code permission, which might
affect its execution in partial-trust situations. For more
information, see SecurityPermission and Code Access Permissions.
So I think that somehow my test.exe does not have permission to create a file.

Related

Process.Start PDF in a folder

I can't get Process.Start to simply launch a PDF with default PDF viewer.
I tried so many combinations of shell execute, working folder etc etc. Keeps giving me either 'The system cannot find the file specified' or 'the directory name is invalid'
private void button1_Click(object sender, EventArgs e)
{
string filename = #"Milking and cooling software set 2018-39.pdf";
MessageBox.Show(currentpath + #"\Astronaut A5 v1.5(b7)\documentation\" + filename);
fullpath = currentpath + #"\Astronaut A5 v1.5(b7)\documentation";
fullfile = fullpath + filename;
ProcessStartInfo process = new ProcessStartInfo();
process.WorkingDirectory = fullpath;
process.UseShellExecute = false;
process.FileName = fullfile;
process.RedirectStandardOutput = true;
process.Verb = "run as";
Process.Start(process);
}
Why is this so hard, I have tried for hours to simply lauch Acrobat Reader to open a PDF file. I can double click it no problem in it's location but C# can't open it, either I get .NET errors or Adobe opens and says it can't find the file. Tried so many combinations of "\"", full path, hard coded path etc etc...unbelievable that this is so hard to code in this day and age.
You’ve told the system to not use ShellExecute. This means the path you’re giving should be an actual executable program. PDFs are not so if you want to open it with the default reader use ShellExecute.
process.UseShellExecute = true;
Also using “run as” as the verb doesn’t make any sense here, unless there is such a verb defined for PDFs which I’m pretty sure there isn’t. That should be removed.

Converting a doc to a pdf in a mvc c# environment

Hi I've got a c# MVC application running under a particular user (app.pool user).
I need to convert a doc or docx file to a pdf.
I thought a good option would be to use libreoffice to fire a process that would start this.
To make life easier for myself (and if libreoffice shouldn't work) I used a batch file.
echo on
SET var1=%2
IF "%var1:~-1%"=="\" SET var1=%var1:~0,-1%
cd %var1%
echo %1
echo %var1%
start /wait "" "C:\Program Files (x86)\LibreOffice 4\program\soffice" -headless -convert-to pdf %1 -outdir %var1%
My code for starting this is as follows.
var ba = #"C:\inetpub\wwwroot\apps\xxxxxxxxx\Services\convert.bat";
fullPath = #"C:\inetpub\wwwroot\apps\xxxxxxxxx\Files\Temp\636295920370843147.doc";
var tempPath = #"C:\inetpub\wwwroot\apps\xxxxxxxxx\Files\Temp";
string command = ba;
//Process.Start(command, fullPath + " " + tempPath);
var processInfo = new ProcessStartInfo("cmd.exe", "/c " + command + " "+ fullPath+ " "+ tempPath);
processInfo.CreateNoWindow = false;
processInfo.UseShellExecute = false;
processInfo.RedirectStandardError = true;
processInfo.RedirectStandardOutput = true;
var process = Process.Start(processInfo);
process.OutputDataReceived += (object sender, DataReceivedEventArgs e) =>
Trace.WriteLine("output>>" + e.Data);
process.BeginOutputReadLine();
process.ErrorDataReceived += (object sender, DataReceivedEventArgs e) =>
Trace.WriteLine("error>>" + e.Data);
process.BeginErrorReadLine();
process.WaitForExit();
Trace.WriteLine("ExitCode: {0}", process.ExitCode.ToString());
process.Close();
This does seem to work manually but when I run the code I can see the whole thing just stalls around the conversion. Looking at the threads and it seems to load the gdiplus.dll which I think is a graphics module which doesn't seem right.
The process though when I copy and paste that into my 'run' box in windows works fine and the pdf is made.
I've checked that the app.pool user has access to both libreoffice and also the folder with the files.
I've ran this as the app.pool user, in the c# it just stalls on the process.WaitForExit();
line. Until I kill the process.
Any ideas?
I've also tried many different ways of executing the soffice conversion. just straight from the c# - libreoffice 4,5.
I've seen some people use libreoffice as a service, is this an option? If so how?
Richard
EDIT
Ah, just changed the app Pool user to myself and now it works, so there is a permissions thing with the standard app pool user. How to find out what....
I added the user into the administrators group on the computer and restarted the machine, then it worked.
It might not be the best solution but after 2 days of trying to get this to work I'm not going to argue.
Richard

How to open/operate file in batch classes?

I have to import in a Table from file (csv for example).
I used this code:
public void run ()
{
TextIO textIO;
str filename, fileOpen, folder;
int handle;
Io thisMYFile;
FileIoPermission perm;
#File
#avifiles
#OCCRetryCount
[handle, filename] = WINAPI::findFirstFile(folder + "\\*.csv");
fileOpen = strFmt (folder + "\\" + filename);
perm = new FileIoPermission(fileOpen, 'w');
perm.assert();
thisMYFile = new CommaTextIo(fileOpen , 'w');
}
But in Debug the class IO thisMYFile is null and so I can't to read and get information.
In my class declaration I extends RunBaseBarch.
If I used a "normal" classes (not batch) I can read,write,move file etc, but now I can't to open.
I know the WinAPI classes not work in Batch, now I think there is also another way to read/open file in batch? With WinAPIServerclass I can findFirstFile ?
A clarification, I have also a same problem if I don't schedule the process batch : flag Batch processing is false, in the batch dialog, and clicked only Ok. (example image)
If you've a tutorial, any advice or help,
Thanks all,
enjoy!
Beware that the batch runs on an other machine, the AOS will not have access to your local files.
Therefore always use a full UNC file path to the file, ex. \\MyHost\Temp\x.csv
If new CommaTextIO fails to open the file, it returns null, it does not throw an exception. If you do not test for null your code will fail later.

I can't extract files in program files folder

I'm working on custom action and wix.The files are not extracting in program files (x86) folder.But the files are extracting correctly other than program files (x86). I have written code using .NET FRAMEWORK 4.0.
namespace Installer
{
public class CustomActions
{
[CustomAction]
public static ActionResult CustomAction1(Session session)
{
session.Log("Begin Extracting");
string FinalPath = session["APPDIR"];``
string zPath = #"C:\Users\AppData\Local\Temp\Install\7za.exe";
string ExtractPath = #"C:\Program Files (x86)\Samples\";
string sourcePath = #"C:\Program Files (x86)\Samples\source.zip";
try`
{
ProcessStartInfo pro = new ProcessStartInfo();``
pro.WindowStyle = ProcessWindowStyle.Hidden;
pro.FileName = zPath;
pro.Arguments = "x \"" + sourcePath + "\" -o" + ExtractPath;
Process x = Process.Start(pro);
x.WaitForExit();
}
catch (System.Exception Ex)
{
}
return ActionResult.Success;
}
}
}
First of all you need to debug it properly. You're throwing away any error that might be thrown. Sorry to say this, but your question is unfortunately more like "how can I find out why my code is not working when I've thrown away any exceptions it might raise?"
There's no guarantee that the zip extension will work correctly just by starting it. It might work if WinZip is installed, but not if all that happens is that Explorer opens to look at the files.
You should use the classes that will unzip it. Example here:
https://msdn.microsoft.com/en-us/library/ms404280(v=vs.110).aspx

How to get the name of a temporary file created by File.tmpfile in D2?

I need to generate a temporary file, fill it with some data and feed it to an external program. Based on description of D available here I'm using File.tmpfile() method:
auto f = File.tmpfile();
writeln(f.name());
which doesn't provide a way to get the generated file name. It's documented that name might be empty. In Python I would do that like this:
(o_fd, o_filename) = tempfile.mkstemp('.my.own.suffix')
Is there a simple, safe and cross-platform way to do that in D2?
Due to how tmpfile() works, if you need the name of the file you can't use it. However, I have already created a module to work with temporary files. It uses conditional compilation to decide on the method of finding the temporary directory. On windows, it uses the %TMP% environment variable. On Posix, it uses /tmp/.
This code is licensed under the WTFPL, so you can do whatever you want with it.
module TemporaryFiles;
import std.conv,
std.random,
std.stdio;
version(Windows) {
import std.process;
}
private static Random rand;
/// Returns a file with the specified filename and permissions
public File getTempFile(string filename, string permissions) {
string path;
version(Windows) {
path = getenv("TMP") ~ '\\';
} else version(Posix) {
path = "/tmp/";
// path = "/var/tmp/"; // Uncomment to survive reboots
}
return File(path~filename, permissions);
}
/// Returns a file opened for writing, which the specified filename
public File getTempFile(string filename) {
return getTempFile(filename, "w");
}
/// Returns a file opened for writing, with a randomly generated filename
public File getTempFile() {
string filename = to!string(uniform(1L, 1000000000L, rand)) ~ ".tmp";
return getTempFile(filename, "w");
}
To use this, simply call getTempFile() with whatever arguments you want. Defaults to write permission.
As a note, the "randomly generated filenames" aren't truely random, as the seed is set at compile time.