Powershell runquery in clients machine ASP.NET - asp.net

I want to get the program names installed from Windows Store(client side). Heres my code. First of all is it possible? Secondly if yes why my code is not working?
StringBuilder stringBuilder = new StringBuilder();
var shell = PowerShell.Create();
// Add the script to the PowerShell object
shell.Commands.AddScript("Import-Module Appx");
shell.Commands.AddScript("Get-AppxPackage ");
Command c = new Command("Out-String");
c.Parameters.Add("width", 150);
shell.Commands.AddCommand(c);
// var results = shell.Invoke();
Collection<PSObject> results = shell.Invoke();
foreach (PSObject obj in results)
{
stringBuilder.AppendLine(obj.ToString());
}
No results returned (Only one and it is empty . )

Related

Is it possible to create an ADOX catalog in memory and populate it?

I tried creating one like this:
using (MemoryStream stream = new MemoryStream())
{
Catalog catalog = new Catalog(stream); // do I need to add more after this?
foreach (DataTable dt in ds.Tables)
{
Table adoxTable = new Table();
adoxTable.Name = dt.TableName;
adoxTable.ParentCatalog = catalog; // issue is here
catalog.Tables.Append(table);
}
return stream.ToArray();
}
However when I get to the line adoxTable.ParentCatalog = catalog; I get the exception: The connection cannot be used to perform this operation. It is either closed or invalid in this context.
Do I need to add additional steps after creating the catalog in order to properly utilize it?

Execute BizUnit 4.0 XML Test Case

Hi i have created a an xml test case in bizunit 4.0 called test1.xml
The problem I have is how to run the test. All the examples i find are for bizunit 2.0 and 3.0, but not for 4.0. In the examples i found it says to do this:
BizUnit.BizUnit bizUnit = new BizUnit.BizUnit("testl.xml");
bizUnit.RunTest();
but i get a note saying it is deprecated.
I'm using .net unit tests and calling bizunit from code
Here's an example
// create list of files
TestGeneratedFiles = new System.Collections.Generic.List<String>();
var TestCase = new BizUnit.Xaml.TestCase { Name = "Interface128UnitTestSetup" };
//Create the file validate step
var testStep = new FileReadMultipleStep
{
DirectoryPath = inputPath,
SearchPattern = InputTemplate,
ExpectedNumberOfFiles = 1,
Timeout = 3000,
DeleteFiles = false
};
//Create an XML Validation step
//This will check against the XSD for the document
var validation = new XmlValidationStep();
var schemaSummary = new SchemaDefinition
{
// test deployment copies this file to test directory
XmlSchemaPath = #"Publish_Employee.xsd",
XmlSchemaNameSpace = "http://AMC.Oracle.Employee"
};
validation.XmlSchemas.Add(schemaSummary);
TestCase.ExecutionSteps.Add(testStep);
// run the test case
var bizUnit = new BizUnit.BizUnit(TestCase);
bizUnit.RunTest();
For me this worked (w/o warning):
TestCase tc = TestCase.LoadFromFile("test1.xml");
BizUnit.BizUnit bizUnit = new BizUnit.BizUnit(tc);
bizUnit.RunTest();

imagemagick file paths? Getting a 'The system cannot find the file specified error'

I cannot figure out where I need to put files for ImageMagick to process them. I am trying to use it in my ASP.NET MVC website and having zero luck having it find my files to process. And if it does how do I specify where they will be output?
I have been looking here and I mut be missing something:
http://www.imagemagick.org/script/command-line-processing.php
Here is my code to call the process:
//Location of the ImageMagick applications
private const string pathImageMagick = #"C:\Program Files\ImageMagick-6.7.3-8";
private const string appImageMagick = "MagickCMD.exe";
CallImageMagick("convert -density 400 SampleCtalog.pdf -scale 2000x1000 hi-res%d.jpg");
private static string CallImageMagick(string fileArgs)
{
ProcessStartInfo startInfo = new ProcessStartInfo
{
Arguments = fileArgs,
WorkingDirectory = pathImageMagick,
FileName = appImageMagick,
UseShellExecute = false,
CreateNoWindow = true,
RedirectStandardOutput = true
};
using (Process exeProcess = Process.Start(startInfo))
{
string IMResponse = exeProcess.StandardOutput.ReadToEnd();
exeProcess.WaitForExit();
exeProcess.Close();
return !String.IsNullOrEmpty(IMResponse) ? IMResponse : "True";
}
}
We do something similar but use the environment variables (which is advantageous because it works on every system) to execute cmd.exe which we feed with convert and the parameters. This is how we create the ProcessStartInfo object:
// Your command
string command = "convert...";
ProcessStartInfo procStartInfo = new ProcessStartInfo {CreateNoWindow = true};
string fileName = Environment.GetEnvironmentVariable("ComSpec");
if (String.IsNullOrEmpty(fileName))
{
// The "ComSpec" environment variable is not present
fileName = Environment.GetEnvironmentVariable("SystemRoot");
if (!String.IsNullOrEmpty(fileName))
{
// Try "%SystemRoot%\system32\cmd.exe"
fileName = Path.Combine(Path.Combine(fileName, "system32"), "cmd.exe");
}
if ((String.IsNullOrEmpty(fileName)) || (!File.Exists(fileName)))
{
// If the comd.exe is not present, let Windows try to find it
fileName = "cmd";
}
}
procStartInfo.FileName = fileName;
procStartInfo.RedirectStandardInput = true;
procStartInfo.RedirectStandardOutput = true;
procStartInfo.UseShellExecute = false;
Process proc = Process.Start(procStartInfo);
proc.StandardInput.WriteLine(command);
proc.StandardInput.Flush();
Then we read from proc.StandardOutput in order to get error messages and result codes. Afterwards, we destroy the objects.
Sorry if this is not 100%, I copied it from a more complex OO code.

Running a batch file from an ASP.Net page

I'm trying to run a batch file on a server via an ASP.Net page, and it's driving my crazy. When I run the below code, nothing happnes - I can see from some log statements that this code runs, but the .bat file that I pass to the function never runs.
Could anybody please tell me what I'm doing wrong?
public void ExecuteCommand(string batchFileLocation)
{
Process p = new Process();
// Create secure password
string prePassword = "myadminpwd";
SecureString passwordSecure = new SecureString();
char[] passwordChars = prePassword.ToCharArray();
foreach (char c in passwordChars)
{
passwordSecure.AppendChar(c);
}
// Set up the parameters to the process
p.StartInfo.FileName = #"C:\\Windows\\System32\cmd.exe";
p.StartInfo.Arguments = #" /C " + batchFileLocation;
p.StartInfo.LoadUserProfile = true;
p.StartInfo.UserName = "admin";
p.StartInfo.Password = passwordSecure;
p.StartInfo.UseShellExecute = false;
p.StartInfo.CreateNoWindow = true;
// Run the process and wait for it to complete
p.Start();
p.WaitForExit();
}
In the 'Application' Event Viewer log on the server, every time I try to run this, the following issue seems to occur:
Faulting application cmd.exe, version 6.0.6001.18000, time stamp 0x47918bde, faulting module kernel32.dll, version 6.0.6001.18000, time stamp 0x4791a7a6, exception code 0xc0000142, fault offset 0x00009cac, process id 0x8bc,application start time 0x01cc0a67825eda4b.
UPDATE
The following code works fine (it runs the batch file):
Process p = new Process();
p.StartInfo.FileName = batchFileLocation;
p.StartInfo.WorkingDirectory = Path.GetDirectoryName(batchFileLocation);
p.StartInfo.UseShellExecute = false;
// Run the process and wait for it to complete
p.Start();
p.WaitForExit();
This however doesn't (when i try to run as a specific user):
Process p = new Process();
// Create secure password
string prePassword = "adminpassword";
SecureString passwordSecure = new SecureString();
char[] passwordChars = prePassword.ToCharArray();
foreach (char c in passwordChars)
{
passwordSecure.AppendChar(c);
}
p.StartInfo.FileName = batchFileLocation;
p.StartInfo.WorkingDirectory = Path.GetDirectoryName(batchFileLocation);
p.StartInfo.UseShellExecute = false;
p.StartInfo.UserName = "admin";
p.StartInfo.Password = passwordSecure;
// Run the process and wait for it to complete
p.Start();
p.WaitForExit();
Just call the batch file directly:
p.StartInfo.FileName = batchFileLocation;
Also, make sure the WorkingDirectory is set to the right location:
p.StartInfo.WorkingDirectory= Path.GetDirectoryName(batchFileLocation);
A little google on "Faulting application cmd.exe" points me to this IIS forum.
It seems that you cannot create a new process in the background under IIS, unless you use the CreateProcessWithLogon method. (I have not tested this).

DOS based printing through ASP.NET

Well my situation is like this:
I am generating a report as a text file at the server which needs to be printed using DOS mode on a dot matrix printer. I want to avoid Windows printing because it would be too slow. Is there a way in ASP.NET through which I can carry out DOS based printing as it is best suited for Dot matrix printers. I have scoured the net but could not come across any solution or pointers. Does any body have any pointers/solutions which they might have implemented or stumbled across.
This application is a Web based application.
Thanx.
If I understand you right, one option is to execute a batch file that would do the actual printing from ASP.NET. From here: (Obviously, you can omit some of the code writing the output to the page)
// Get the full file path
string strFilePath = “c:\\temp\\test.bat”;
// Create the ProcessInfo object
System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo("cmd.exe");
psi.UseShellExecute = false;
psi.RedirectStandardOutput = true;
psi.RedirectStandardInput = true;
psi.RedirectStandardError = true;
psi.WorkingDirectory = “c:\\temp\\“;
// Start the process
System.Diagnostics.Process proc = System.Diagnostics.Process.Start(psi);
// Open the batch file for reading
System.IO.StreamReader strm = System.IO.File.OpenText(strFilePath);
// Attach the output for reading
System.IO.StreamReader sOut = proc.StandardOutput;
// Attach the in for writing
System.IO.StreamWriter sIn = proc.StandardInput;
// Write each line of the batch file to standard input
while(strm.Peek() != -1)
{
sIn.WriteLine(strm.ReadLine());
}
strm.Close();
// Exit CMD.EXE
string stEchoFmt = "# {0} run successfully. Exiting";
sIn.WriteLine(String.Format(stEchoFmt, strFilePath));
sIn.WriteLine("EXIT");
// Close the process
proc.Close();
// Read the sOut to a string.
string results = sOut.ReadToEnd().Trim();
// Close the io Streams;
sIn.Close();
sOut.Close();
// Write out the results.
string fmtStdOut = "<font face=courier size=0>{0}</font>";
this.Response.Write(String.Format(fmtStdOut,results.Replace(System.Environment.NewLine, "<br>")));
The answer from BobbyShaftoe is correct. Here's a pedantic version of it:
public static void CreateProcess(string strFilePath)
{
// Create the ProcessInfo object
var psi = new ProcessStartInfo("cmd.exe")
{
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardInput = true,
RedirectStandardError = true,
WorkingDirectory = "c:\\temp\\"
};
// Start the process
using (var proc = Process.Start(psi))
{
// Attach the in for writing
var sIn = proc.StandardInput;
using (var strm = File.OpenText(strFilePath))
{
// Write each line of the batch file to standard input
while (strm.Peek() != -1)
{
sIn.WriteLine(strm.ReadLine());
}
}
// Exit CMD.EXE
sIn.WriteLine(String.Format("# {0} run successfully. Exiting", strFilePath));
sIn.WriteLine("EXIT");
// Read the sOut to a string.
var results = proc.StandardOutput.ReadToEnd().Trim();
// Write out the results.
string fmtStdOut = "<font face=courier size=0>{0}</font>";
this.Response.Write(String.Format(fmtStdOut,results.Replace(System.Environment.NewLine, "<br>")));
}
}

Resources