ASP.NET Process Start PowerShell Script IIS 7.5 - asp.net

All works fine on my dev machine but if deployed to IIS the process doesn't get started. I am starting a powershell script by
private void RunScript()
{
Process process = null;
try
{
int timeout = 1800000;
var startInfo = new ProcessStartInfo
{
FileName = #"powershell.exe",
Arguments = string.Format("{0} {1}", "\path\toscript", "myParam"),
UseShellExecute = false,
CreateNoWindow = true
};
process = Process.Start(startInfo);
process.WaitForExit(timeout);
}
finally
{
if (!process.HasExited)
{
if (process.Responding)
process.CloseMainWindow();
else
process.Kill();
}
if (process != null)
{
process.Close();
process.Dispose();
}
}
}
Here's what's configured for the app pool this is running under.
Process Model
->Identity = domain user who is a Domain Admin.
->Load User Profile = True
Web App
Authentication is Windows
What else do I need to configure to so that I can run the Process?

As Start-Automating suggested I eventually ended up doing this:
using (Runspace runSpace = RunspaceFactory.CreateRunspace())
{
try
{
runSpace.Open();
RunspaceInvoke scriptInvoker = new RunspaceInvoke(runSpace);
scriptInvoker.Invoke("Set-ExecutionPolicy Unrestricted");
using (Pipeline pipeLine = runSpace.CreatePipeline())
{
var myCommand = new Command(scriptPath);
var myParam1 = new CommandParameter("-paramName", "someValue");
myCommand.Parameters.Add(myParam1);
pipeLine.Commands.Add(myCommand);
pipeLine.Commands.Add("Out-String");
Collection<PSObject> returnObjects = pipeLine.Invoke();
runSpace.Close();
return returnObjects;
}
}
finally
{
runSpace.Close();
}
}
On the IIS server I executed the following powershell command "Set-ExecutionPolicy RemoteSigned"

It's much better to embed the PowerShell APIs the call the .exe
Here's an old link that will get you a PowerShell runspace embedded in ASP.NET per user:
http://powershellpipeworks.com/

Check the permissions of the file system where powershell.exe lives.
Also, check the Security Log in the Event Viewer for authentication errors and access violations.

Related

ASP.NET IIS File create permission while using Thread

I am trying to create a file in my ASP.NET application (IIS 7.5). The file write is done in a separate thread and is giving access not available error.
What kind of permission does the directory need? I have tried giving full access to IIS_IUSRS and IUSR. But this did not work. Everything works okay in my local machine, but once deployed on the server, I get access error.
string filePath = MapPath("c:\FilePath\");
PrintFile printFile = new PrintFile();
Thread printFileThread = new Thread(delegate()
{
printFile.PrintFile(filePath);
});
printFileThread.Start();
public void PrintFile(string filePath)
{
if (Directory.Exists(filePath) == false)
{
Directory.CreateDirectory(filePath);
}
FileStream fs = new FileStream(filePath + "NewFile.pdf", FileMode.Create);
}

How do I launch my ASP.NET application from integration test code?

I have written a basic suite of Selenium integration tests for an application we are building. They work great. The only issue is that the application needs to be pre-deployed and running before the tests can run.
How do I launch an ASP.NET MVC application from integration test code?
I figured out how to launch my app my running MS build and then basically passing it the path to the sign and starting a new IISExpress process to host it:
ProcessStartInfo processStartInfo = new ProcessStartInfo()
{
ErrorDialog = false,
CreateNoWindow = true,
UseShellExecute = false,
Arguments = string.Format("/path:\"{0}\" /port:{1}", this.pathToSite, this.portNumber)
};
string path = (!string.IsNullOrEmpty(processStartInfo.EnvironmentVariables["programfiles(x86)"]) ? processStartInfo.EnvironmentVariables["programfiles(x86)"] : processStartInfo.EnvironmentVariables["programfiles"]) + "\\IIS Express\\iisexpress.exe";
processStartInfo.FileName = path;
this.iisProcess = new Process
{
StartInfo = processStartInfo
};
this.iisProcess.Start();
Hope this helps the next guy. Otherwise I will just leave this here for my own reference. I wrapped all this in a method called when starting TestFixtureSetup. Of course I run
public void Shutdown()
{
if(this.IisExpressProcess == null)
{
return;
}
this.IisExpressProcess.Stop();
}
on TestFixtureTearDown.

How to create an exe for a web application?

I had developed a web application using Visual studio 2012 (ASP.Net 4.5 - C#) and a web service. Both are laying in a single solution. I need to convert my solution to an EXE file (Creating EXE for my web application). What i need exactly is, if run my setup file, it should host my web application and web service in IIS. Kindly provide the steps to solve me the problem.
Quiet a late answer:
I cannot post the whole project here but i'll post the flow chart here and you may try it.
All the steps in the flowchart here should be controlled programmatically.
1. Steps in starting the application.
NOTE: Please ignore the third layer (Is website added) if you are using a local database(.mdf)
The connection string to be used for a local database:
public string ConnectionString =
"Data Source=(local);Initial Catalog=YOUR_DATABASE_NAME;Integrated Security=True";
But still remember that you need dotnet framework to be installed inorder to run your application. don't worry as you can set the pre-requisites in your application setup project.
All the codes for the flowchart process below.
Is IIS Installed:
NOTE: I am posting the code for IIS 7 and above.
public bool IsIISInstalled()
{
return Registry.GetValue(#"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\InetStp",
"VersionString", null) != null;
}
Install IIS
public int InstallIIS()
{
string DISM_CMD_CODE = "START /WAIT DISM /Online /Enable-Feature /FeatureName:IIS-ApplicationDevelopment /FeatureName:IIS-ASP /FeatureName:IIS-ASPNET /FeatureName:IIS-BasicAuthentication /FeatureName:IIS-CGI /FeatureName:IIS-ClientCertificateMappingAuthentication /FeatureName:IIS-CommonHttpFeatures /FeatureName:IIS-CustomLogging /FeatureName:IIS-DefaultDocument /FeatureName:IIS-DigestAuthentication /FeatureName:IIS-DirectoryBrowsing /FeatureName:IIS-FTPExtensibility /FeatureName:IIS-FTPServer /FeatureName:IIS-FTPSvc /FeatureName:IIS-HealthAndDiagnostics /FeatureName:IIS-HostableWebCore /FeatureName:IIS-HttpCompressionDynamic /FeatureName:IIS-HttpCompressionStatic /FeatureName:IIS-HttpErrors /FeatureName:IIS-HttpLogging /FeatureName:IIS-HttpRedirect /FeatureName:IIS-HttpTracing /FeatureName:IIS-IIS6ManagementCompatibility /FeatureName:IIS-IISCertificateMappingAuthentication /FeatureName:IIS-IPSecurity /FeatureName:IIS-ISAPIExtensions /FeatureName:IIS-ISAPIFilter /FeatureName:IIS-LegacyScripts /FeatureName:IIS-LegacySnapIn /FeatureName:IIS-LoggingLibraries /FeatureName:IIS-ManagementConsole /FeatureName:IIS-ManagementScriptingTools /FeatureName:IIS-ManagementService /FeatureName:IIS-Metabase /FeatureName:IIS-NetFxExtensibility /FeatureName:IIS-ODBCLogging /FeatureName:IIS-Performance /FeatureName:IIS-RequestFiltering /FeatureName:IIS-RequestMonitor /FeatureName:IIS-Security /FeatureName:IIS-ServerSideIncludes /FeatureName:IIS-StaticContent /FeatureName:IIS-URLAuthorization /FeatureName:IIS-WebDAV /FeatureName:IIS-WebServer /FeatureName:IIS-WebServerManagementTools /FeatureName:IIS-WebServerRole /FeatureName:IIS-WindowsAuthentication /FeatureName:IIS-WMICompatibility /FeatureName:WAS-ConfigurationAPI /FeatureName:WAS-NetFxEnvironment /FeatureName:WAS-ProcessModel /FeatureName:WAS-WindowsActivationService";
string command = DISM_CMD_CODE;
ProcessStartInfo pStartInfo = new ProcessStartInfo("cmd.exe", "/c " + command);
Process p = new Process();
p.StartInfo = pStartInfo;
//p.WaitForExit();
p.Start();
return 1;
}
Is Website added
public bool IsWebsiteAddedInIIS(string WebsiteName)
{
ServerManager serverManager = new ServerManager();
var site = serverManager.Sites.FirstOrDefault(s => s.Name == WebsiteName);
if (site == null)
{
//No site added
return false;
}
else
{
//site added
return true;
}
}
public int CreateNewWebsite(string SiteName, string PublishedFilesPath)
{
ServerManager serverManager = new ServerManager();
var site = serverManager.Sites.FirstOrDefault(s => s.Name == SiteName);
if (site == null)
{
serverManager.Sites.Add(SiteName, "http", "*:8080:", PublishedFilesPath);
serverManager.CommitChanges();
return 1;
}
else
{
return 2;
}
}
public void StartWebsite(string SiteName)
{
ServerManager serverManager = new ServerManager();
var site = serverManager.Sites.FirstOrDefault(s => s.Name == SiteName);
if (site != null)
{
site.Stop();
site.Start();
}
}
public void StopWebsite(string SiteName)
{
ServerManager serverManager = new ServerManager();
var site = serverManager.Sites.FirstOrDefault(s => s.Name == SiteName);
if (site != null)
{
site.Stop();
}
}
Get website URL
public string GetWebsiteURL(string SiteName)
{
//string SiteUrl = "";
//ServerManager serverManager = new ServerManager();
//var site = serverManager.Sites.FirstOrDefault(s => s.Name == SiteName);
//var siteBindings = site.GetCollection("bindings");
//string protocol = (string)siteBindings["protocol"];
//string bindingInfo = (string)siteBindings["bindingInformation"];
//if (protocol.StartsWith("http", StringComparison.OrdinalIgnoreCase))
//{
// string[] parts = bindingInfo.Split(':');
// if (parts.Length == 3)
// {
// //Get the port in use HERE !!!
// string port = parts[1];
// SiteUrl = "localhost:" + port;
// }
//}
//return SiteUrl;
int port = 0;
string SiteUrl = "";
ServerManager serverManager = new ServerManager();
var site = serverManager.Sites.FirstOrDefault(s => s.Name == SiteName);
foreach (Binding binding in site.Bindings)
{
port = binding.EndPoint.Port;
SiteUrl = "localhost:" + port + "/index.aspx";
break;
}
return SiteUrl;
}
Init Browsing the website
You have to install Cefsharp chromium browser to your windows forms
Install-Package CefSharp.WinForms -Version 75.1.143
public void InitBrowser(string Address)
{
Cef.Initialize(new CefSettings());
browser = new ChromiumWebBrowser(Address);
Controls.Add(browser);
browser.Dock = DockStyle.Fill;
}
Thank you..
Maybe you need to create a web setup project. "A Web setup project provides the
highest level of flexibility for deploying a website. Although Web Setup Projects are more
complex for the developer, they allow you to generate an MSI package, precompile a website,
and perform virtually any setup task that your application might require.
Many websites do not require custom configuration. In these cases, you can simply build
your MSI file and be ready to deploy. However, more complex scenarios include dependencies
(such as particular operating system versions or service packs), custom registry entries,
or administrator configuration. Web Setup Projects allow you to deploy websites that meet
these requirements."
Check the book "MCTS Self-Paced Training Kit (Exam 70-515) - Web Applications Development with Microsoft .NET Framework 4" at the chapter 8 "Debugging and deploying".
Hope this helps.

copy images from local machine to server in asp.net C#

I need to copy the images from C:/images folder to my web application folder which is running in the server.I used the following code which work well in local application but not work in server
string sourcePath = #"D:\images";
//string destinationPath = #"D:\a";
string destinationPath = Server.MapPath("SMSImages") + "\\";
if (System.IO.Directory.Exists(sourcePath))
{
string[] files = System.IO.Directory.GetFiles(sourcePath);
foreach (string s in files)
{
fileName = Path.GetFileName(s);
destFile = Path.Combine(destinationPath, fileName);
File.Copy(s, destFile, true);
}
how to copy
Servers often have a lot of security limitations for the IIS user.
Check if the user under which you are running your asp.net process has authorization to access this path.
You can log the exceptions that are occurring in this code to see if it is causing an access violation.
The following code can help you check if code if you have access
UserFileAccessRights rights = new UserFileAccessRights(sourcePath);
if (rights.canWrite() && rights.canRead()) {
lblLogMsg.Text = "R/W access";
} else {
if (rights.canWrite()) {
lblLogMsg.Text = "Only Write access";
} else if (rights.canRead()) {
lblLogMsg.Text = "Only Read access";
} else {
lblLogMsg.Text = rights.ToString();
}
}
It doesn't work because the program search a D:\ path in server not in local system.

programmatically added application pool (app pool) is not showing up in Internet Information Services (IIS) Manager

(Using IronPython), I'm adding an application pool as follows, but the app pool won't show up in Internet Information Services (IIS) Manager.
Anyone know why this discrepancy is happening? This is working because I see the app pool I added when I look through the app pools (serverManager.ApplicationPools).
import clr
clr.AddReference("Microsoft.Web.Administration")
from Microsoft.Web.Administration import *
import getpass
current_user = System.Security.Principal.WindowsIdentity.GetCurrent().Name
serverManager = ServerManager()
app_pool = serverManager.ApplicationPools.Add("my pool name")
app_pool.AutoStart = True
app_pool.ManagedPipelineMode = ManagedPipelineMode.Integrated
app_pool.ManagedRuntimeVersion = "v2.0"
app_pool.ProcessModel.IdentityType = ProcessModelIdentityType.SpecificUser
app_pool.ProcessModel.UserName = current_user
app_pool.ProcessModel.Password = getpass.getpass("Password:")
serverManager.CommitChanges()
Try this:
// Create the Server Manager Object:
ServerManager defaultManager = new ServerManager();
// Add the Application-Pool:
ApplicationPool defaultAppPool = defaultManager.ApplicationPools.Add("DefaultAppPool");
// Configure the Pool to Automatically Start.
defaultAppPool.AutoStart = true;
// If IIS Application-Pool Exceeds the CPU Limit Property:
defaultAppPool.Cpu.Action = ProcessorAction.KillW3wp;
// Pipeline:
defaultAppPool.ManagedPipelineMode = ManagedPipeLineMode.Integrated;
// Set Runtime:
defaultAppPool.ManagedRuntimeVersion = "v2.0";
// User Network Service Account:
defaultAppPool.ProcessModel.IdentityType = ProcessModelIdentityType.NetworkService;
// Idle:
defaultAppPool.ProcessModel.IdleTimeout = TimeSpan.FromMinutes(5);
// Max Number of IIS Worker Processes: (W3wp)
defaultAppPool.ProcessModel.MaxProcess = 1;
// Commit the Changes:
defaultManager.CommitChanges();
// Dispose:
defaultManager.Dispose();
It could happen because your not initiating the new ServerManager / Application-Pool. Then when it goes to create the user; it may not be an account that can actually create the user account. If You'd like to validate the application can indeed make those sort of changes also; you could use:
WindowsIdentity userIdentity = WindowsIdentity.GetCurrent();
// Test Operating System Version Vista or Greater for UAC
if (Environment.OSVersion.Platform != PlatformID.Win32NT || Environment.OSVersion.Version.Major < 6)
{
return false;
}
else
{
// If UserIdentity came back Null
if (userIdentity == null)
{
throw new InvalidOperationException("Unable to get current user");
}
else
{
// Set Security Principal to ensure user is in proper role.
WindowsPrincipal userPolicy = new WindowsPrincipal(userIdentity);
if (userPolicy.IsInRole(WindowsBuiltInRole.Administrator))
{
return true;
}
else
{
MessageBox.Show("Application isn't in proper administrative user role; please restart.");
return false;
}
}
}

Resources