Process.Start and "The system cannot find the path specified" - .net-4.0

I am trying to run a console application from a mapped drive (T:\ is a mapped drive for a shared network folder) and get the error:
The system cannot find the path specified.
Why do I get this error? The administrator credentials are correct.
var password = new SecureString();
password.AppendChar(Convert.ToChar("P"));
password.AppendChar(Convert.ToChar("a"));
password.AppendChar(Convert.ToChar("a"));
password.AppendChar(Convert.ToChar("s"));
Process.Start(#"t:\ca\test.exe"), "", "Administrator", password, "domain");

Check if the mapped drive T: is also correctly mapped for the Administrator account.
Also, I'm not sure, but the Administrator must probably be logged in for the mapped drive to be available.
You could also try the following, starting cmd.exe, mapping your UNC path and then calling the application:
var password = new SecureString();
password.AppendChar(Convert.ToChar("P"));
password.AppendChar(Convert.ToChar("a"));
password.AppendChar(Convert.ToChar("a"));
password.AppendChar(Convert.ToChar("s"));
var startInfo = new ProcessStartInfo();
startInfo.FileName = "cmd.exe";
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
startInfo.CreateNoWindow = true;
startInfo.UseShellExecute = false;
startInfo.RedirectStandardInput = true;
startInfo.RedirectStandardOutput = true;
startInfo.UserName = "Administrator";
startInfo.Password = password;
startInfo.Domain = "domain";
var process = Process.Start(startInfo);
process.BeginOutputReadLine();
process.StandardInput.WriteLine(#"pushd \\your_unc_path\ca");
process.StandardInput.WriteLine("test.exe");
process.StandardInput.WriteLine("exit");
process.WaitForExit();

Related

TabTip.exe The requested operation requires elevation. .NET Core

TabTip.exe The requested operation require
I am trying to get TabTip to pop up when a function is called. I am trying to do this with this code in .NET Core but I get the following error:
{System.ComponentModel.Win32Exception: The requested operation requires elevation
at System.Diagnostics.Process.StartCore(ProcessStartInfo startInfo)
at myfunc() in myClass.cs:line 64}
Here is the Code
Process p = new Process();
ProcessStartInfo processStartInfo = new ProcessStartInfo(#"C:\Program Files\Common Files\microsoft shared\ink\TabTip.exe");
p.StartInfo = processStartInfo;
p.Start();
I am running Visual Studio in Administrator mode.
This is the code that I used to complete what I was trying to accomplish. I needed to copy TabTip.exe from its original location to my project's directory.
var processlist = Process.GetProcesses();
foreach (var process in processlist.Where(process => process.ProcessName == "TabTip"))
{
process.Kill();
break;
}
Process cmd = new Process();
cmd.StartInfo.FileName = "powershell";
cmd.StartInfo.RedirectStandardInput = true;
cmd.StartInfo.RedirectStandardOutput = true;
cmd.StartInfo.CreateNoWindow = true;
cmd.StartInfo.UseShellExecute = false;
cmd.Start();
cmd.StandardInput.WriteLine(".\\TabTip.exe");
cmd.StandardInput.Flush();
cmd.StandardInput.Dispose();
cmd.WaitForExit();
Debug.WriteLine(cmd.StandardOutput.ReadToEnd());

Cannot execute linux commands from a Dotnet Core ASP.NET solution

Whenever I try to execute shell commands, I get an error saying
/bin/hostname: /bin/hostname: cannot execute binary file
fail: Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware[0]
An unhandled exception has occurred: Index was outside the bounds of the array.
I currently have
public MachineData FindHostname()
{
Thread.Sleep(3000);
ProcessStartInfo psi = new ProcessStartInfo();
psi.FileName = "/bin/bash";
psi.Arguments = "/bin/hostname && /bin/uname";
psi.UseShellExecute = false;
psi.RedirectStandardOutput = true;
Process proc = new Process
{
StartInfo = psi
};
proc.Start();
...
}
Does anyone know of a workaround?

Azure Pack REST API Authentication

After hours of search in Microsoft messed up API documentation for its products, i am still no where on how to authenticate a rest API request in windows azure pack distribution.
Primarily i want to create an API which automate the process of deploying virtual machine, but I cant find any documentation on how to acquire the authentication token to access the resources.
Some documentation states the use of ADFS, but don't provide any reference on the ADFS REST API for authentication.
And I don't want to use ADFS in the first place. I want to authenticate using AZURE tenant and admin interface.
In conclusion, if anyone can provide any help on the REST API authentication, it will make my day.
Thanks in advance.
You can use the following PowerShell to acquire an access token.
Add-Type -Path 'C:\Program Files\Microsoft Azure Active Directory Connect\Microsoft.IdentityModel.Clients.ActiveDirectory.dll'
$tenantID = "<the tenant id of you subscription>"
$authString = "https://login.windows.net/$tenantID"
# It must be an MFA-disabled admin.
$username = "<the username>"
$password = "<the password>"
# The resource can be https://graph.windows.net/ if you are using graph api.
# Or, https://management.azure.com/ if you are using ARM.
$resource = "https://management.core.windows.net/"
# This is the common client id.
$client_id = "1950a258-227b-4e31-a9cf-717495945fc2"
$creds = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.UserCredential" `
-ArgumentList $username,$password
$authContext = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext" `
-ArgumentList $authString
$authenticationResult = $authContext.AcquireToken($resource,$client_id,$creds)
# An Authorization header can be formed like this.
$authHeader = $authenticationResult.AccessTokenType + " " + $authenticationResult.AccessToken
I am doing some similar job like you did.
static string GetAspAuthToken(string authSiteEndPoint, string userName, string password)
{
var identityProviderEndpoint = new EndpointAddress(new Uri(authSiteEndPoint + "/wstrust/issue/usernamemixed"));
var identityProviderBinding = new WS2007HttpBinding(SecurityMode.TransportWithMessageCredential);
identityProviderBinding.Security.Message.EstablishSecurityContext = false;
identityProviderBinding.Security.Message.ClientCredentialType = MessageCredentialType.UserName;
identityProviderBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.None;
var trustChannelFactory = new WSTrustChannelFactory(identityProviderBinding, identityProviderEndpoint)
{
TrustVersion = TrustVersion.WSTrust13,
};
//This line is only if we're using self-signed certs in the installation
trustChannelFactory.Credentials.ServiceCertificate.SslCertificateAuthentication = new X509ServiceCertificateAuthentication() { CertificateValidationMode = X509CertificateValidationMode.None };
trustChannelFactory.Credentials.SupportInteractive = false;
trustChannelFactory.Credentials.UserName.UserName = userName;
trustChannelFactory.Credentials.UserName.Password = password;
var channel = trustChannelFactory.CreateChannel();
var rst = new RequestSecurityToken(RequestTypes.Issue)
{
AppliesTo = new EndpointReference("http://azureservices/TenantSite"),
TokenType = "urn:ietf:params:oauth:token-type:jwt",
KeyType = KeyTypes.Bearer,
};
RequestSecurityTokenResponse rstr = null;
SecurityToken token = null;
token = channel.Issue(rst, out rstr);
var tokenString = (token as GenericXmlSecurityToken).TokenXml.InnerText;
var jwtString = Encoding.UTF8.GetString(Convert.FromBase64String(tokenString));
return jwtString;
}
Parameter "authSiteEndPoint" is your Tenant Authentication site url.
default port is 30071.
You can find some resource here:
https://msdn.microsoft.com/en-us/library/dn479258.aspx
The sample program "SampleAuthApplication" can solve your question.

Apache Shiro login failed using JDBC Realm

I am trying to connect to oracle DB .
I want to retrieve list of passwords from data base using the authentication query. Here is my sample shiro.ini file:
# password matcher
passwordMatcher = org.apache.shiro.authc.credential.PasswordMatcher
passwordService = org.apache.shiro.authc.credential.DefaultPasswordService
passwordMatcher.passwordService = $passwordService
# datasource
ds = oracle.jdbc.pool.OracleDataSource
ds.URL = jdbc:oracle:thin:#matrix-oracle11g:1521:dev11g
ds.user = cit1am
ds.password = cit1
jdbcRealm = org.apache.shiro.realm.jdbc.JdbcRealm
jdbcRealm.permissionsLookupEnabled = true
jdbcRealm.authenticationQuery = SELECT USR_PSWD FROM USR
jdbcRealm.credentialsMatcher = $passwordMatcher
jdbcRealm.dataSource = $ds
securityManager.realms = $jdbcRealm
[users]
[roles]
[urls]
Sample code snippet of login:
public class Quickstart {
private static final transient Logger log = LoggerFactory.getLogger(Quickstart.class);
public static void main(String[] args) {
Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
SecurityManager securityManager = factory.getInstance();
SecurityUtils.setSecurityManager(securityManager);
Subject currentUser = SecurityUtils.getSubject();
// Do some stuff with a Session (no need for a web or EJB container!!!)
Session session = currentUser.getSession();
session.setAttribute("someKey", "aValue");
String value = (String) session.getAttribute("someKey");
if (value.equals("aValue")) {
log.info("Retrieved the correct value! [" + value + "]");
}
try{
// let's login the current user so we can check against roles and permissions:
if (!currentUser.isAuthenticated()) {
UsernamePasswordToken token = new UsernamePasswordToken("cit1am", "cit1") ;
token.setRememberMe(true);
try {
currentUser.login(token); //problem occurs here
log.info("inside try block ==========>>" );
}
catch (UnknownAccountException uae) {
log.info("There is no user with username of " + token.getPrincipal());
}
I am getting following error:
[main] ERROR org.apache.shiro.realm.jdbc.JdbcRealm - There was a SQL error while authenticating user [cit1am]
java.sql.SQLException: Invalid column index
at oracle.jdbc.driver.SQLStateMapping.newSQLException(SQLStateMapping.java:70)
at oracle.jdbc.driver.DatabaseError.newSQLException(DatabaseError.java:133)
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:199)
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:263)
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:271)
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:445)
Please suggest what i am doing wrong?
After debugging more i found issue with my code and sql query in .ini file.
I changed following in .INI file
jdbcRealm.authenticationQuery = SELECT USR_PSWD FROM USR where USR_NM = ?
Also commented
#cm = org.apache.shiro.authc.credential.Sha256CredentialsMatcher
#jdbcRealm.credentialsMatcher = $cm and removedconfiguration related to password matcher
I also removed role and permission check from java code.
As i have just started with shrio it's bit difficult to understand flow at start.
Though it can help some one in future.
Thanks

Web Deploy API and Web Management Service (WMSVC)

I'm trying to translate the following WORKING command line into web deploy api (Microsoft.Web.Deployment) code:
"C:\Program Files (x86)\IIS\Microsoft Web Deploy V3\msdeploy.exe" -verb:sync -source:contentPath="\\myserver\code_to_deploy" -dest:contentPath="Default Web Site",wmsvc="mysandbox",userName="MyWebDeployUser",password="MyPassword" -allowUntrusted
My looks like this:
string srcPath = "\\myserver\code_to_deploy";
string destPath = "Default Web Site";
DeploymentBaseOptions sourceOptions = new DeploymentBaseOptions();
sourceOptions.TraceLevel = TraceLevel.Verbose;
sourceOptions.Trace += new EventHandler<DeploymentTraceEventArgs>(Src_Trace);
DeploymentBaseOptions destOptions = new DeploymentBaseOptions();
destOptions.UserName = "MyWebDeployUser";
destOptions.Password = "MyPassword";
destOptions.AddDefaultProviderSetting("contentPath", "wmsvc", "mysandbox");
destOptions.AuthenticationType = "basic";
destOptions.TraceLevel = TraceLevel.Verbose;
destOptions.Trace += new EventHandler<DeploymentTraceEventArgs>(Dest_Trace);
ServicePointManager.ServerCertificateValidationCallback = (s, c, chain, err) =>
{
return true;
};
DeploymentSyncOptions syncOptions = new DeploymentSyncOptions();
syncOptions.DeleteDestination = true;
using (DeploymentObject depObj = DeploymentManager.CreateObject(DeploymentWellKnownProvider.ContentPath, srcPath, sourceOptions))
{
var summary = depObj.SyncTo(DeploymentWellKnownProvider.IisApp, destPath, destOptions, syncOptions);
}
When the code makes the call to 'AddDefaultProviderSetting' it fails saying that wmsvc is not supported by the provider. If I remove the line I receive a 401 from the server. Any examples of doing this or other help is much appreciated.
I don't know whether you have found a solution but here is a code snippet that allows to use wmsvc for those who need it:
DeploymentBaseOptions destinationOptions = new DeploymentBaseOptions()
{
UserName = "<user_name>",
Password = "<password>",
IncludeAcls = false,
AuthenticationType = "Basic",
UseDelegation = true,
ComputerName = "https://<server>:8172/msdeploy.axd?Site=<website>"
};
// Use -allowUntrusted option
ServicePointManager.ServerCertificateValidationCallback +=
new RemoteCertificateValidationCallback(
(object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) => { return true; });
string package = <zip_package_fullPath>;
string parameters = <project_SetParameters_xml_fullPath>;
using (var deploymentObject = DeploymentManager.CreateObject(DeploymentWellKnownProvider.Package, package))
{
deploymentObject.SyncParameters.Load(parameters);
DeploymentSyncOptions syncOptions = new DeploymentSyncOptions();
DeploymentChangeSummary results = deploymentObject.SyncTo(destinationOptions, syncOptions);
}
It's quite hard to find documentation on these topics. Btw, I've not succeeded in using AddDefaultProviderSetting, even by creating a .exe.configSettings file and I'm not sure it's the right method to achieve what you want to.
To create a virtual application instead of a website, only .SetParameters.xml has to be changed from
<setParameter name="IIS Web Application Name" value="<WebSite>" />
to
<setParameter name="IIS Web Application Name" value="<WebSite>/<VirtualApp>" />
Hope this helps.