I have problem during running external process from ASP.NET application.
The process is run as follows:
[WebMethod(EnableSession = true)]
[ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]
public static WebResult generateSomething(string language)
{
ProcessStartInfo psi = new ProcessStartInfo();
psi.UseShellExecute = false;
psi.RedirectStandardError = true;
psi.RedirectStandardOutput = true;
psi.RedirectStandardInput = true;
psi.WindowStyle = ProcessWindowStyle.Hidden;
psi.CreateNoWindow = true;
psi.ErrorDialog = false;
psi.WorkingDirectory = Environment.CurrentDirectory;
psi.FileName = String.Format("\"{0}\"", Path.Combine(appDir, Properties.Settings.Default.PATH_TO_APP_TEXT));
psi.Arguments = arguments.ToString();
modeller.log.Info("Arguments: " + psi.Arguments);
var outputText = new StringBuilder();
int exitCode;
var result = new WebResult();
using (Process process = new Process())
{
process.StartInfo = psi;
process.OutputDataReceived += (sendingProcess, args) => { outputText.Append(args.Data); };
process.ErrorDataReceived += (sendingProcess, args) => { outputText.Append(args.Data); };
process.Start();
process.BeginOutputReadLine();
process.BeginErrorReadLine();
process.WaitForExit();
exitCode = process.ExitCode;
}
string outText = outputText.ToString();
Immediately after process finishes (succesfully or not) and the method leaves ASP.NET IIS session is ended, so any authentication context via cookie breaks.
Can anyone help with this issue?
Thanks in advance
Related
I run psexec in visual studio but I can not in IIS. I search some days all given solutions is old and there is not usable these days.
my OS is Windows 10 and it is my code:
string psFileName = Server.MapPath(".") + #"\\PSTools\\PsExec.exe";
string computerName = "computerName";
string userName = "DOMAIN\\userName";
string password = "password";
string exePath = "C:\\Program Files\\Mozilla Firefox\\firefox.exe";
string paramters = "\"https://www.google.com\"";
private void RunRemote(string psFileName, string computerName, string userName, string password, string exePath, string paramters)
{
// string path = Application.StartupPath+ #"\PSTools\PsExec.exe";
try
{
Process process = new Process();
ProcessStartInfo psi = new ProcessStartInfo(psFileName);
psi.UseShellExecute = false;
psi.RedirectStandardOutput = true;
psi.RedirectStandardError = true;
psi.RedirectStandardInput = true;
psi.WindowStyle = ProcessWindowStyle.Minimized;
psi.CreateNoWindow = true;
psi.Domain = "ITCPIDC-CENTER";
psi.UserName = "gholizadeh.al";
SecureString theSecureString = new NetworkCredential("", password).SecurePassword;
psi.Password = theSecureString;
psi.Arguments = $"\\\\{computerName} -d -u {userName} -p {password} \"{exePath}\" {paramters}";
process.StartInfo = psi;
process.Start();
string output = process.StandardOutput.ReadToEnd();
Label1.Text = output;
string errormessage = process.StandardError.ReadToEnd();
Label1.Text = errormessage;
process.WaitForExit();
}
catch (Exception ex)
{
Label1.Text = ex.Message;
}
}
I expected to run firefox by psexec in asp.net web form but just run in visual studio running
I have to run two commands using Process in asp.net as given below and the first command runs successfully while running the second command gets hung at result = p.StandardOutput.ReadToEnd()
How to implement this to run both commands successfully?
private static string FFMPEG_EXE_PATH = #"D:\ffmpeg\bin\ffmpeg.exe";
private static string FFPROBE_EXE_PATH = #"D:\ffmpeg\bin\ffprobe.exe";
protected void Page_Load(object sender, EventArgs e)
{
string firstArgs = #"-hide_banner -show_format -show_streams -pretty D:\Video\dolbycanyon.m4v";
var result1 = Execute(FFPROBE_EXE_PATH, firstArgs);
string secondArgs = #"-hide_banner -ss 00:00:05 -i D:\Video\dolbycanyon.m4v -r 1 -t 1 -f image2 D:\Video\test.jpg";
var result2 = Execute(FFMPEG_EXE_PATH, secondArgs);
}
private string Execute(string exePath, string parameters)
{
string result = String.Empty;
using (Process p = new Process())
{
p.StartInfo.UseShellExecute = false;
p.StartInfo.CreateNoWindow = true;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.FileName = exePath;
p.StartInfo.Arguments = parameters;
p.Start();
result = p.StandardOutput.ReadToEnd(); // the application hung here for the second command
p.WaitForExit();
}
return result;
}
I have changed the Execute method to as below and it worked for both commands.
public string Execute(string path, string args, int timeoutMs)
{
using (var outputWaitHandle = new ManualResetEvent(false))
{
using (var process = new Process())
{
process.StartInfo = new ProcessStartInfo(path);
process.StartInfo.Arguments = args;
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.CreateNoWindow = true;
var sb = new StringBuilder(1024);
process.OutputDataReceived += (sender, e) =>
{
sb.AppendLine(e.Data);
if (e.Data == null)
{
outputWaitHandle.Set();
}
};
process.Start();
process.BeginOutputReadLine();
process.WaitForExit(timeoutMs);
outputWaitHandle.WaitOne(timeoutMs);
process.CancelOutputRead();
return sb.ToString();
}
}
}
After uploading image through ASP.NET WEB API successfuly through localhost . I uploaded my project to the hosting server but this time i got the error as
an error has occured
This is my controller
tutorEntities entities = new tutorEntities();
[HttpPost]
public HttpResponseMessage ImageUp()
{
var httpContext = (HttpContextWrapper)Request.Properties["MS_HttpContext"];
img std = new img();
// std.Title = httpContext.Request.Form["Title"];
// std.RollNo = httpContext.Request.Form["RollNo"];
// std.Semester = httpContext.Request.Form["Semester"];
HttpResponseMessage response = new HttpResponseMessage();
var httpRequest = HttpContext.Current.Request;
if (httpRequest.Files.Count > 0)
{
string random = Guid.NewGuid().ToString();
string url = "/UserImage/" + random + httpRequest.Files[0].FileName.Substring(httpRequest.Files[0].FileName.LastIndexOf('.'));
Console.WriteLine(url);
string path = System.Web.Hosting.HostingEnvironment.MapPath(url);
httpRequest.Files[0].SaveAs(path);
std.Path = "http://localhost:2541/" + url;
}
entities.imgs.Add(std);
entities.SaveChanges();
return Request.CreateResponse(HttpStatusCode.OK);
}
Ensure that AppPoolIdentity user has write permissions on the UserImage folder. Also, catch the exception in code for debugging:
try {
var httpContext = (HttpContextWrapper)Request.Properties["MS_HttpContext"];
img std = new img();
// std.Title = httpContext.Request.Form["Title"];
// std.RollNo = httpContext.Request.Form["RollNo"];
// std.Semester = httpContext.Request.Form["Semester"];
HttpResponseMessage response = new HttpResponseMessage();
var httpRequest = HttpContext.Current.Request;
if (httpRequest.Files.Count > 0)
{
string random = Guid.NewGuid().ToString();
string url = "/UserImage/" + random + httpRequest.Files[0].FileName.Substring(httpRequest.Files[0].FileName.LastIndexOf('.'));
Console.WriteLine(url);
string path = System.Web.Hosting.HostingEnvironment.MapPath(url);
httpRequest.Files[0].SaveAs(path);
std.Path = "http://localhost:2541/" + url;
}
entities.imgs.Add(std);
entities.SaveChanges();
return Request.CreateResponse(HttpStatusCode.OK);
}
catch(Exception ex) {
var response = new HttpResponseMessage(HttpStatusCode.InternalServerError)
{
Content = new StringContent(ex.ToString()),
ReasonPhrase = "Error"
}
throw new HttpResponseException(response);
}
We have a requirement to enable SAML SSO login, we are implementing SSO using Kentor HttpModule.
I'm facing an issue when the Idp calls my application. The kentor service throws The given key was not present in the dictionary. Here the idp is ADFS.
We tried using the stubidp and it works fine.
Below is my Saml configuration
private static IdentityProvider CreateAuthServicesOptions()
{
var spOptions = GetServiceProviderOptions();
var idp = new IdentityProvider(new EntityId("http://IQTDEV01.domain.com/adfs/services/trust/"), spOptions)
{
AllowUnsolicitedAuthnResponse = true,
Binding = Saml2BindingType.HttpPost,
WantAuthnRequestsSigned=true,
//LoadMetadata = true,
SingleSignOnServiceUrl = new Uri("https://IQTDEV01.iqtrackdev.com/adfs/ls/")
};
idp.SigningKeys.AddConfiguredKey(
new X509Certificate2(AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "/ADFSService.cer"));
return idp;
}
private static SPOptions GetServiceProviderOptions()
{
var cultureInfo = CultureInfo.GetCultureInfo("en-US");
var spOptions = new SPOptions
{
EntityId = new EntityId("https://app.domain.com/AuthServices/"),
ReturnUrl = new Uri("https://app.domain.com"),
AuthenticateRequestSigningBehavior=SigningBehavior.Always
};
X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
X509Certificate2Collection cers = store.Certificates.Find(X509FindType.FindByThumbprint, "FDDAF5EAA6E2B232E0012C0E77955C13246D2DF4", false);
Kentor.AuthServices.ServiceCertificate ser = new Kentor.AuthServices.ServiceCertificate();
ser.Certificate = cers[0];
ser.Use = Kentor.AuthServices.CertificateUse.Signing;
spOptions.ServiceCertificates.Add(ser);
//spOptions.ServiceCertificates.Add(new X509Certificate2(
// AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "/ADFSService.cer"));
return spOptions;
}
protected void OnAuthenticateRequest(object sender, EventArgs e)
{
var application = (HttpApplication)sender;
// Strip the leading ~ from the AppRelative path.
var appRelativePath = application.Request.AppRelativeCurrentExecutionFilePath;
appRelativePath = (!string.IsNullOrEmpty(appRelativePath))
? appRelativePath.Substring(1)
: string.Empty;
if (application.Request != null)
{
Kentor.AuthServices.Configuration.Options op = new Options(GetServiceProviderOptions());
op.IdentityProviders.Add(CreateAuthServicesOptions());
Options = op;
}
var modulePath = Options.SPOptions.ModulePath;
if (appRelativePath.StartsWith(modulePath, StringComparison.OrdinalIgnoreCase))
{
var commandName = appRelativePath.Substring(modulePath.Length);
var command = CommandFactory.GetCommand(commandName);
var commandResult = command.Run(
new HttpRequestWrapper(application.Request).ToHttpRequestData(),
Options);
if (!commandResult.HandledResult)
{
commandResult.SignInOrOutSessionAuthenticationModule();
commandResult.Apply(new HttpResponseWrapper(application.Response));
}
}
}
Exception
Well, the title says it all.
I do the following now in my LanguageFilterAttribute class:
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var request = filterContext.HttpContext.Request;
string currentUrl = request.RawUrl;
var urlHelper = new UrlHelper(request.RequestContext);
string baseurl = urlHelper.Content("~");
string currentLanguageFromUrl = currentUrl.Split('/')[1];
string currentLanguageFromCulture = CultureHelper.CheckCulture();
var currentLanguageFromCookie = request.Cookies["_culture"];
var possibleCultures = UnitOfWork.CulturesRepository.GetListOfCultureNames();
if (possibleCultures.All(culture => currentLanguageFromUrl != culture))
{
string cultureName;
string newUrl;
if (currentLanguageFromCookie != null)
{
cultureName = currentLanguageFromCookie.Value;
CultureHelper.SetCulture(cultureName);
newUrl = baseurl + cultureName;
filterContext.Result = new RedirectResult(newUrl);
return;
}
if (currentLanguageFromCulture != null)
{
cultureName = currentLanguageFromCulture;
CultureHelper.SetCulture(cultureName);
newUrl = baseurl + cultureName;
filterContext.Result = new RedirectResult(newUrl);
return;
}
cultureName = possibleCultures[0];
CultureHelper.SetCulture(cultureName);
newUrl = baseurl + cultureName;
filterContext.Result = new RedirectResult(newUrl);
return;
}
CultureHelper.SetCulture(currentLanguageFromUrl);
base.OnActionExecuting(filterContext);
};
Which sets the language when you select a new one from the dopdown on the shared Layout page (this works btw, selecting a different language triggers respectively, the above and below class correctly).
public static void SetCulture(string culture)
{
var cultureCookie = HttpContext.Current.Request.Cookies["_culture"] ?? new HttpCookie("_culture");
cultureCookie.Value = culture;
var request = HttpContext.Current.Request;
cultureCookie.Domain = request.Url.Host;
cultureCookie.Expires = DateTime.Now.AddYears(1);
cultureCookie.Path = "/";
HttpContext.Current.Response.Cookies.Add(cultureCookie);
CultureInfo info = CultureInfo.CreateSpecificCulture(culture.ToString());
Thread.CurrentThread.CurrentCulture = info;
Thread.CurrentThread.CurrentUICulture = info;
}
The problem with this is, as you can guess, I will have to apply the [LanguageFilter] attribute on all my controllers.
Isn't there a file where I can place this that will change my language every time I go to another page?
http://msdn.microsoft.com/en-us/library/system.globalization.cultureinfo.aspx
When a new application thread is started, its current culture and
current UI culture are defined by the current system culture, and not
by the current thread culture.
Isn't this your case?