Attempting Simultaneous File Operations - c#

I am attempting to create an ASP.NET 4.0 website (C#) that does the following: after the user clicks a button, take user inputs (from text boxes) and call a Powershell script on the server. The Powershell script output is logged to a textfile on the same machine. The script executes some stored procedures on a SQL server. Once the script is done executing, the page reads the contents of the log file and returns them in the page. The reason I log this as I do is because I need to capture the "verbose" output of these operations.
The problem I am having is that the whole set of commands that are run after the user clicks the button is queued if another user has the site open and is attempting the same operation. I am not clear as to why this happens. When run outside of the website, the Powershell scripts execute in parallel. The log files that the application writes to use a timestamp and user inputted information to ensure that they are different depending on who is inputting the info.
Here is the code that is executed when the button is clicked:
protected void Test_Click(object sender, EventArgs e)
{
// Get the current date/time to use a timestamp for the log file
DateTime curDate = DateTime.Now;
string logFileName = "D:\\test1\\logs\\" + curDate.Year + curDate.Month + curDate.Day +
curDate.Hour + curDate.Minute + curDate.Second + curDate.Millisecond + "_" +
TextBox1.Text.Replace("\\", "_") + "_Test.txt";
// Clean the Result TextBox
ResultBox.Text = string.Empty;
// Initialize PowerShell engine
var shell = PowerShell.Create();
// Add a script to the PowerShell shell object that will execute the instructions with the given input
shell.Commands.AddScript("powershell.exe -file D:\\test1\\ps_script0.ps1 '" + TextBox3.Text + "' '" +
TextBox1.Text + "' '" + TextBox2.Text + "' '" + TextBox4.Text + "' > " + logFileName);
// Execute the script
shell.Invoke();
// Create a StreamReader object to read the results of the script instructions and then store the file's contents in a string
StreamReader sr = File.OpenText(logFileName);
String results = sr.ReadToEnd();
results = results.Replace("VERBOSE: ", "");
sr.Close();
// Set the text of the result box to the string that was read in
ResultBox.Text = results;
}
I am hoping to find out if there is information I can read about allowing multiple users to click this button, and have the backend script run simultaneously for each of them. I looked into asynchronous pages and threads, but I don't think this is necessary in my case since each user's page should have its own thread. Any help here is much appreciated. Thanks!

Related

WPF: unable to map network drive for all users

I'm trying to create a function for an application to automatically copy over specific files during the final stage of a job. The only issue here is that the copy location is a protected share drive and uses a separate login instead of being validated by the active directory so I've got to do a bit of a workaround to get File.Copy() working. My workaround has been to call the built in net.exe utility and passing a command line argument that points to the share drive to open up a connection to the drive then using File.Copy() to get the file where it needs to go then deleting the connection. The issue at hand is that this works great on my computer but when anyone else on the team runs the same program a "Logon failure: unknown user name or bad password" is thrown. I'm at a bit of loss as to why this would happen since the username and password are static and not being changed and everyone on the team has the same network permissions I do. Here is the WPF/C# code I'm using to do this:
try
{
string mrdfDropPath = #"dropPathHere";
string MRDFPath = #"storePath\test.xml";
string command = #"use " + mrdfDropPath + #" /user:CORP\Username Password";
Process.Start("net.exe", command);
File.Copy(MRDFPath, mrdfDropPath + "test.xml");
string command2 = #"use " + mrdfDropPath + #" /delete";
Process.Start("net.exe", command2);
StreamWriter writer = new StreamWriter(#"logPath\log.txt", true);
writer.WriteLine(mrdfDropPath + "test.xml" + "," + File.GetLastWriteTime(MRDFPath).ToString());
writer.Close();
}
catch (Exception e)
{
StreamWriter writer = new StreamWriter(#"logPath\log.txt", true);
writer.WriteLine(e.Message);
writer.Close();
}
Like I said this works as expected during debug and when I run the application, but for anyone else it is throwing the error.

Process.GetProcessessByName doesnt work

i have just made an updater whihch also controls if app running.
Process[] processOfApp = Process.GetProcessesByName(setting.ExeName);
if (processOfApp.Length == 0)
{
Program = StartProcess(realPath + "\\" + setting.ExeName + ".exe");
AppDir = realPath + "\\" + setting.ExeName + ".exe";
ProcessExtensions.StartProcessAsCurrentUser(AppDir);
}
If no app process then start process. But these code start multiple instances.
What i did wrong?
Edit: these code block is in while(true) and this is the only start process in the code.
You may have copied this from somewhere without knowing what it does? I am guessing StartProcess function starts a process. And I assume, so does ProcessExtensions.StartProcessAsCurrentUser. So yes, it would start multiple (two) processes instead of one. If the updater should run a program for the current user from a windows service, delete the Program = ... line and retrive that information later on (using Process.GetProcessesByName, for example), if it is needed for something. That way the updater will be run as Current User, which is probably what you want.
// This line starts an instance
Program = StartProcess(realPath + "\\" + setting.ExeName + ".exe");
AppDir = realPath + "\\" + setting.ExeName + ".exe";
// This line also starts an instance
ProcessExtensions.StartProcessAsCurrentUser(AppDir);

Inconsistent results during debugging - Web API

I have some code that uses a library for a product called Fusion Pro. Based on some config and data files it will generate a PDF file. I have been getting consistent result of a complete lack of output without any thrown exceptions. However when debugging I have been able to get the PDF to generate by attaching the debugger to the code running in my local IIS and stepping through line by line. Nothing is consistent though. It seems to have a higher success rate if I use F11 instead of F10 and going "slow but steady" through each line. Unfortunately it doesn't always produce a PDF even with stepping through the code.
I have never experienced code behaving so inconstantly with the same inputs each time.
The only other relevant bits of information is this code is working in another asmx service without issue, it is running under a specific domain account (requires special security), and it is running in 32bit mode.
DLQueueClient client = new DLQueueClient();
DLQueueJob vdpQueueJob = new DLQueueJob();
string fileName = message.OutputFilePath;
var dataFilePath = CreateDataFile(fileName, message.DefFilePath, message.VariableDataContent, message.QTY);
var pdfFilePath = Path.Combine(new[] { message.OutputFilePath, dataFilePath.Replace(".txt", ".pdf") });
vdpQueueJob.Priority = priority;
vdpQueueJob.Queue = queueName;
string cmd = "\"" + Settings.FusionProExe + "\" \"" + dataFilePath + "\" \""
+ message.DiffFilePath + "\" \"" +
(isProof ? message.ProofConfigFilePath : message.PrintConfigFilePath) + "\" \""
+ pdfFilePath + "\"";
vdpQueueJob.CommandLine = cmd;
client.ConnectRemote(Settings.FusionProServer, Settings.FusionProUser, Settings.FusionProPassword, Settings.FusionProTimeout);
client.SubmitJob(vdpQueueJob, Settings.FusionProTimeout, true);
return pdfFilePath;

C# command-line argument with newline fails in C# but not in python. Need to make the c# work

Env: .NET 3.5 Visual Studio 2008 SP1, on Win XP SP3, Python 2.7. Corporate image, no admin rights.
In C# 3.5, I want to pass a parameter to a command-line program, and this parameter contains newlines. It works in Python 2.7 but not in C#.
When body contains newline, c# truncates the result, but python passes it correctly.
Python code
cmd = self.app_path + ' email -Subject "' + subject + '" -From "' + address_from + '" -To "' + address_to +'" -Body "' + body +'"'
cmd_result = subprocess.Popen(cmd, stdout=subprocess.PIPE).communicate()
C# code:
string Command = "<path to executable>";
string arguments = " email -From " + FromAddress + " -To " + ToAddress + " -Subject \"" + SubjectLine + "\" -Body \"" + emailBody + "\" ";
System.Diagnostics.ProcessStartInfo start = new System.Diagnostics.ProcessStartInfo(Command, arguments);
start.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
start.CreateNoWindow = false;
start.UseShellExecute = true;
System.Diagnostics.Process process = System.Diagnostics.Process.Start(start);
Any idea?
Update: body in the python example and emailBody in the c# example contain the same string, as strings are represented in each language.
Update: noticed the command wasn't terminated correctly in the python code. I added + '"' at the end of line 2. The code ran as before.
Also, as you can tell, the app called sends the body (emailBody) parameter content as an email body.
Sorry but I think it is the process you call that does not take the arguments correctly; it is not the C# that is involved, and as a proof of that:
Create a new windows form application
Make sure that the Main signature looks like this:
static void Main(string[] args)
Make sure that the call of your Main Form (named Form1) looks like this:
if (args==null)
{
Application.Run(new Form1());
}
else
{
Application.Run(new Form1(args));
}
Add a textbox to your form, with the multiline property set to true
Add a button to your form
Run the application once
Then Put this in the code of your button1_Click function (replace TheNameOfTheCurrentApp):
string Command = "TheNameOfTheCurrentApp";
string arguments = textBox1.Text;
System.Diagnostics.ProcessStartInfo start = new System.Diagnostics.ProcessStartInfo(Command, arguments);
start.WindowStyle = System.Diagnostics.ProcessWindowStyle.Maximized;
start.CreateNoWindow = true;
start.UseShellExecute = true;
System.Diagnostics.Process process = System.Diagnostics.Process.Start(start);
Add this constructor to your form:
public Form1(string[] args)
{
InitializeComponent();
textBox1.Text = string.Join(" ", args);
}
Then run your app, insert muliple lines in your textbox and click the button. The same app will appear with the textbox correctly filled with the line breaks

Implementing a MySQL command progress bar

We are trying to parse a file and store it in a MySQL database. The commands will be importing a large trace file the could be several gigabytes in size, so it it may of interest for the user to track the progress of the command. We are using the following command:
String commandText = "SET AUTOCOMMIT = 0; "
+ "START TRANSACTION; "
+ "LOAD DATA LOCAL INFILE \'" + filePath + "\' "
+ "INTO TABLE testdatabase.metadata "
+ #"FIELDS TERMINATED BY '\t' "
+ #"LINES TERMINATED BY '\n' "
+ "(Position,"
+ "Timespace,"
+ "Duration,"
+ "Disk,"
+ "Request,"
+ "Sector,"
+ "Length); "
+ "COMMIT;";
Is there a way to track the progress while the command is being executed in order to implement a progress bar?
You can make a progress bar that changes progress based on the stage a query is in. It's definitely possible to put a GUID in a comment somewhere in the query, then use SHOW FULL PROCESSLIST to figure which stage a query is in. But there's no exact way of gauging actual progress. With InnoDB you can try using SHOW INNODB STATUS but even this isn't precise.

Categories

Resources