Get-WindowsOptionalFeature failing from C# - c#

I am trying to check if windows server 2012 has IIS installed.
I am using following program in C#. It is working fine in windows 7 / 10 but giving error in windows server 2012.
public static String ExecutePoswershellScript(String filepath)
{
log.Info(filepath);
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = "powershell.exe";
startInfo.Arguments = filepath;
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
startInfo.UseShellExecute = false;
startInfo.CreateNoWindow = true;
Process process = new Process();
process.StartInfo = startInfo;
process.Start();
string output = process.StandardOutput.ReadToEnd();
log.Info(output);
string err = process.StandardError.ReadToEnd();
if (err.Length>0)
{
log.Error(err);
}
// log.Info(output + "");
process.WaitForExit();
process.Close();
return output;
}
Error is as follows
Get-WindowsOptionalFeature : An attempt was made to load a program with an incorrect format.
At line:1 char:64
+ ... ocess; Import-Module Dism; Get-WindowsOptionalFeature -Online | where ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Get-WindowsOptionalFeature], CO
MException
+ FullyQualifiedErrorId : Microsoft.Dism.Commands.GetWindowsOptionalFeatureC
ommand
when I execute the command from powershell in windows server 2012 it works , only when I execute uing C# it fails
PowershellCommand
PowerShell version
Name Value
---- -----
PSVersion 5.0.10586.117
PSCompatibleVersions {1.0, 2.0, 3.0, 4.0...}
BuildVersion 10.0.10586.117
CLRVersion 4.0.30319.42000
WSManStackVersion 3.0
PSRemotingProtocolVersion 2.3
SerializationVersion 1.1.0.1
Please let me know if needs to be changed

On Desktops OSs use
Get-WindowsOptionalFeature -Online
On Servers OSs use
Get-WindowsFeature *IIS*

Open the IIS, right click on the applications application pool and go to "advanced settings" and change "Enable 32-Bit Applications" to "TRUE". Restart your website and it should work.
Or In Visual Studio, Right Click your project -> On the left pane click the Build tab, under Platform Target select x86.

Related

Issue with C# CMD output

I am creating a C# app that changes Windows Server edition from Standard Evaluation to Standard. I am trying to get a output of the CMD command, but when the DISM command is completed, it asks you if you want to restart the computer and you need to enter "y" or "n". I tried it doing by passing "echo n | " before the command and by using process.StandardInput.Write, but none of this works. The function works perfectly with other commands that doesn´t require user input. Do you have any idea what am I doing wrong? Thanks
public static string get_cmd_output(string cmd)
{
System.Diagnostics.Process process = new System.Diagnostics.Process();
process.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
process.StartInfo.FileName = "cmd.exe";
process.StartInfo.Arguments = "/C echo n | " + cmd;
process.StartInfo.UseShellExecute = false;
process.StartInfo.CreateNoWindow = true;
process.StartInfo.RedirectStandardOutput = true;
process.Start();
string q = "";
while (!process.HasExited)
q += process.StandardOutput.ReadToEnd();
return q;
}
get_cmd_output("DISM /Online /Set-Edition:ServerStandard /ProductKey:" + key + " /AcceptEula");
In the docs for DISM, one of the global parameters you can pass is /NoRestart:
/NoRestart
Suppresses reboot. If a reboot is not required, this command does
nothing. This option will keep the application from prompting for a
restart (or keep it from restarting automatically if the /Quiet option
is used).
So it should work if you do this:
get_cmd_output("DISM /Online /Set-Edition:ServerStandard /ProductKey:" + key + " /AcceptEula /NoRestart");

C# System.Diagnostics.Process launches on my local IIS, but doesn't launch on the server

I'm trying to make my program to run a bat file, that launches an exe file. It works fine on my local computer, but doesn't work on the server IIS. It doesn't work regardless of whether I specify the username and password in the ProcessStartInfo or not. I've searched forums and applied different stuff, but none of them help.
In Windows event viewer it doesn't give me any errors as well as the process output. If I change a directory and it can't find the bat file, the output gives me an error, but when it finds the file, it doesn't return anything and just doesn't launch the program.
Now, if I provide a credentials for the process, specifying psi.Domain, psi.UserName and psi. Password, the StandartOutput doesn't return any error, but Windows Events gives me two following errors:
Application popup: cmd.exe - Application Error : The application was unable to start correctly (0xc0000142). Click OK to close the application.
And
Application popup: conhost.exe - Application Error : The application was unable to start correctly (0xc0000142). Click OK to close the application.
Here's the code:
System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo(#"C:\inetpub\CopyToAD\pspasswd\passchange.bat");
psi.RedirectStandardOutput = true;
psi.RedirectStandardInput = true;
psi.RedirectStandardError = true;
psi.CreateNoWindow = true;
psi.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
psi.UseShellExecute = false;
System.Diagnostics.Process listFiles;
listFiles = new System.Diagnostics.Process();
listFiles.EnableRaisingEvents = false;
listFiles.StartInfo = psi;
listFiles.Start();
System.IO.StreamReader myOutput = listFiles.StandardOutput;
listFiles.WaitForExit(2000);
myOutput.ReadToEnd();
string output = myOutput.ReadToEnd();
ViewBag.View6 += output + "***";
if (listFiles.HasExited)
{
output = myOutput.ReadToEnd();
ViewBag.View6 += output;
}

C# svnadmin dump, strange behavior

i've written a c# application to check if a repository should be dumper or not (using some paramenters)
I've compiled this application on my computer (Winsows 8) where it works as intended.
When i try to use it on two different windows server (2003 and 2008) with .net 4.5 installed, there is something wrong..
before that i talk about the problems i get i'll show you part of the code i made to make this app work:
output[2] = exec("svnadmin dump " + dir + " > " + dir + ".dump");
where dir is the actual name of the repository, the exec function is as follow:
public string exec(object command)
{
try
{
System.Diagnostics.ProcessStartInfo procStartInfo =
new System.Diagnostics.ProcessStartInfo("cmd", "/c " + command);
procStartInfo.RedirectStandardOutput = true;
procStartInfo.UseShellExecute = false;
procStartInfo.CreateNoWindow = true;
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo = procStartInfo;
proc.Start();
return proc.StandardOutput.ReadToEnd();
}
catch (Exception objException)
{
return "Error: " + objException;
}
}
what i get is that, when i run this on Windows 8, it works as intended
when i run this on Server 2003 it dumps only revision 0
when i run this on Server 2008 it returns an error (it is not a repository!)
Windows 8 svn version: 1.7.8 (sliksvn)
Windows server 2003 svn verion: 1.5.8
Windows server 2008 svn version: 1.7.9
any help is appreaciated,
thanks in advance
I had a similar problem with the "it is not a repository!" problem. To fix this, I used svnserve.
svnserve -r .\ -d
This fixed my problem.

Using Drush Site-Install in C#

I'm trying to do a Drupal site install using Drush in C# as part of a full Windows Server site installation using MSI.
The Drush commmand I am using is the following one.
C:\ProgramData\Drush\Drush.bat -y si application_name --db-url=sqlsrv://admin_name:password(local)\SQLEXPRESS:/database_name --account-name=admin --account-mail=name#test.com --account-pass=Password1234 --site-mail="admin#company.com" --site-name="Site Name" install_configure_form.site_default_country=GB install_configure_form.date_default_timezone="Europe/London"
And this works perfectly when run from cmd.exe when in the working directory (inetpub\application_name).
The issue arises when the above is put into code and executed during an installation and always results in the following error (with a different file name each time).
Unable to decompress C:\ProgramData\Drush\lib\druFD63.tmp.gz
The C# code being used to execute the command is as follows:
public static ActionResult Drush_Configuration(Session session)
{
string strArgs = "-y si application_name --db-url=sqlsrv://admin_name:password(local)\SQLEXPRESS:/database_name --account-name=admin --account-mail=name#test.com --account-pass=Password1234 --site-mail="admin#company.com" --site-name="Site Name" install_configure_form.site_default_country=GB install_configure_form.date_default_timezone="Europe/London";
string strExeCmd = #"C:\ProgramData\Drush\Drush.bat ";
strExeCmd = strExeCmd + strArgs;
string strLocation = #"C:\inetpub\application_name";
session.Log("Starting Drush Configuration");
session.Log("Command line is: " + strExeCmd + " " + strArgs);
int exitCode;
ProcessStartInfo processInfo;
Process process;
try
{
processInfo = new ProcessStartInfo("cmd.exe", "/c " + strExeCmd);
processInfo.WorkingDirectory = strLocation;
processInfo.WindowStyle = ProcessWindowStyle.Normal;
processInfo.CreateNoWindow = true;
processInfo.UseShellExecute = false;
// *** Redirect the output ***
processInfo.RedirectStandardError = true;
processInfo.RedirectStandardOutput = true;
process = Process.Start(processInfo);
process.WaitForExit();
// *** Read the streams ***
string output = process.StandardOutput.ReadToEnd();
string error = process.StandardError.ReadToEnd();
exitCode = process.ExitCode;
session.Log("output>>" + (String.IsNullOrEmpty(output) ? "(none)" : output));
session.Log("error>>" + (String.IsNullOrEmpty(error) ? "(none)" : error));
session.Log("ExitCode: " + exitCode.ToString(), "ExecuteCommand");
process.Close();
}
catch (Exception e)
{
session.Log("Error: " + e);
return ActionResult.Failure;
}
session.Log("Drush Configuration completed successfully");
return ActionResult.Success;
}
And as stated above, this always results in the "unable to decompress" error.
Has anyone ever used c# to run Site-Install in Drush? Does anyone know why this might fail when executed in this way?
Any thoughts or advice would be greatly appreciated.
I am using Drush-5.8-2012-12-10-Installer-v1.0.20, Drupal 7, and Windows Server 2008 R2 x64.
The cause of this issue was the Environment Variables. The Drush MSI installer sets up User Path Environment Variables which are not recognized in an MSI machine context.
So, by adding System Path Variables for Drush, GnuWin32 and PHP to the site-install MSI the site can be programmatically installed.

BCDEDIT not recognized when running via C#

When i try to run BCDEDIT from my C# application i get the following error:
'bcdedit' is not recognized as an internal or external
command,
operable program or batch file.
when i run it via elevated command line i get as expected.
i have used the following code:
Process p = new Process();
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.FileName = #"CMD.EXE";
p.StartInfo.Arguments = #"/C bcdedit";
p.Start();
string output = p.StandardOutput.ReadToEnd();
String error = p.StandardError.ReadToEnd();
p.WaitForExit();
return output;
i have also tried using
p.StartInfo.FileName = #"BCDEDIT.EXE";
p.StartInfo.Arguments = #"";
i have tried the following:
Checking path variables - they are fine.
running visual studio from elevated command prompt.
placing full path.
i am running out of ideas,
any idea as to why i am getting this error ?
all i need is the output of the command if there is another way that would work as well.
thanks
There is one explanation that makes sense:
You are executing the program on a 64 bit machine.
Your C# program is built as x86.
The bcdedit.exe file exists in C:\Windows\System32.
Although C:\Windows\System32 is on your system path, in an x86 process you are subject to the File System Redirector. Which means that C:\Windows\System32 actually resolves to C:\Windows\SysWOW64.
There is no 32 bit version of bcdedit.exe in C:\Windows\SysWOW64.
The solution is to change your C# program to target AnyCPU or x64.
If you are stuck with x86 application on both 32it/64bit Windows and You need to call bcdedit command, here is a way how to do that:
private static int ExecuteBcdEdit(string arguments, out IList<string> output)
{
var cmdFullFileName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows),
Environment.Is64BitOperatingSystem && !Environment.Is64BitProcess
? #"Sysnative\cmd.exe"
: #"System32\cmd.exe");
ProcessStartInfo psi = new ProcessStartInfo(cmdFullFileName, "/c bcdedit " + arguments) { UseShellExecute = false, RedirectStandardOutput = true };
var process = new Process { StartInfo = psi };
process.Start();
StreamReader outputReader = process.StandardOutput;
process.WaitForExit();
output = outputReader.ReadToEnd().Split(new[] { Environment.NewLine }, StringSplitOptions.None).ToList();
return process.ExitCode;
}
usage:
var returnCode = ExecuteBcdEdit("/set IgnoreAllFailures", out outputForInvestigation);
Inspiration was from this thread and from How to start a 64-bit process from a 32-bit process and from http://www.samlogic.net/articles/sysnative-folder-64-bit-windows.htm

Categories