How to pass command to termux using dotnet? [duplicate] - c#

I am working on automating the process of launching the dependencies for an android project.
One of the dependencies is launching Termux (Installed through F-Droid not Play store as recommended).
I am trying to launch the installed Termux application through another application and add some commands to its ~./bashrc file for the sake of automation.
I know that an installed app can be launched trough another android app (more details are here).
I wonder to know if this is possible for Termux as well? I wonder to know if we can use intent concept to launch Termux from an android app as well? If yes what is the Termux package name?
I tried using "com.termux" as its packagename in my sample code, but it did not work.
In other words, the following line returns null:
Intent launchIntent = getPackageManager().getLaunchIntentForPackage("com.termux");
Updated:
I can open another installed app (the app that I developed and installed its apk file on tablet) using Intent concept as shown above (by replacing the appropriate package name instead of termux package name).
Note:
I have installed the Termux through F-Drioid not google play store.
New observation:
I confirmed through Package names application the Termux package name is "com.termux" and its activity class name is also "com.termux.app.termuxActivity"
But seems like the "com.termux" is not accessible through package manager. When i try to pass "com.termux" to the following function it returns false.
Any idea or suggestion?
public boolean isPackageExisted(String targetPackage){
enter code here
PackageManager pm=getPackageManager();
try {
PackageInfo info=pm.getPackageInfo(targetPackage,PackageManager.GET_META_DATA);
} catch (PackageManager.NameNotFoundException e) {
return false;
}
return true;
}

Add com.termux to queries element or declare QUERY_ALL_PACKAGES permission in AndroidManifest.xml if targetSdkVersion is 30+. Check Package Visibility or this article for more info. Otherwise, you will will get PackageSetting{...... com.termux/......} BLOCKED errors in logcat.
<manifest
<queries>
<package android:name="com.termux" />
</queries>
</manifest>
Moreover, you can run commands in termux via RUN_COMMAND intent. The termux-shared lib is published on jitpack since v0.116, check Termux Libraries for import instructions.
Moreover, activity name is com.termux.app.TermuxActivity.

Related

Add environment variables in UWP with FullTrustProcessLauncher

I am trying to create environment variables in Windows through a UWP application using the SetEnvironmentVariable method, but it seems that UWP as it runs in a sandbox prevents the application from being able to create environment variables.
So I have created a console app to call it from UWP:
var value = Environment.GetEnvironmentVariable("Test1", EnvironmentVariableTarget.User);
if (value == null)
{
var path = "pathTest";
Environment.SetEnvironmentVariable("Test1", path, EnvironmentVariableTarget.User);
Console.WriteLine("The environment variable has been created successfully");
}
else
{
Console.WriteLine("Environment variable already exists");
}
UWP code to run the console application that I have added in the application package:
public class TestService : ITestService
{
public async Task ExecuteSampleApp()
{
await FullTrustProcessLauncher.LaunchFullTrustProcessForCurrentAppAsync();
}
}
and I have added the .exe in the same UWP application package, and I have added the necessary permissions (runFullTrust) in the Package.appxmanifest to be able to run external applications (that are in the application package), up to this point everything is fine , I can run the console app from my UWP app but it seems that the console app when run from the UWP app can't create the environment variable it's like access is taken away (I think somehow the app sandbox UWP adds the same security restrictions even to the .exe added in the application package), however if I run the same console application in the bin folder that is created when compiling the UWP app it works, the problem occurs only when the UWP app calls the .exe. Anyone have any other ideas on how I could create environment variables in UWP either with this approach I was following or with another?
And with this console app, would it be possible to run cmd commands bypassing the UWP sandbox security restrictions?
Answer to #RoyLi-MSFT:
No, there are no exceptions, the UWP application executes the console application and it shows the message "Environment variable already exists" detecting as if it already exists, however it has not created it at any time, it seems that the console application when it is executed by the UWP app it is not able to really obtain if the environment variable exists or not in the operating system and it returns an incorrect state (indicating that it exists when it does not). However, if the console application is run regardless, it does work, which suggests that it is a UWP problem that somehow isolates the console application to the same sandbox as the UWP app when it is executed by the UWP app. Regarding your other question with placing the exe file in the application package, I mean that I add in the Assets folder the console application in charge of registering the environment variables to be able to execute it with FullTrustProcessLauncher through UWP since it is the only way of running a win32 app from a sandbox environment.
2ยบ Answer to #RoyLi-MSFT:
I use EnvironmentVariableTarget.User in my code, the code I had put here was an example (I have updated the example to clarify it), but I tried to use the 3 available enumerations: Process, User and Machine, the User type is the one that works correctly and is the one that I use in my console application, but as I mentioned before, when the UWP application is the one running the console application it cannot create the environment variable and the console shows: "The environment variable already exists" despite using EnvironmentVariableTarget.User.
I clarify this point: when the console application is run manually if it works, it only shows the message "The environment variable already exists" when the UWP application is in charge of executing it with FullTrustProcessLauncher.
Based on the document-SetEnvironmentVariable(String, String), the Environment Variable you created is stored in the current process, which means the process environment block. I tested your code inside of a console app. Every time when I launched the console app, it shows The environment variable has been created successfully. If I tried to read the value after I write it, I could get the correct value. This behavior matches the document.
So the behavior you mentioned should be expected. You could try directly read the Environment Variable when you haven't closed the console app and you should be able to get the value you set. And #jerry's comment should make sense, you might need to try SetEnvironmentVariable(String, String, EnvironmentVariableTarget) with other options like EnvironmentVariableTarget.User.
Update:
Based on your previous comment, you mentioned that you put the .exe file in the Assets folder of your UWP app. I would suggest you using the Windows Application Package Project to package the console app together with the UWP app. In that way under my test, the console app will correctly add the Environment Variable to the current user block and you could get it as you want.
Here are the steps:
Create a new console app under the solution of your UWP app. Add the code you need.
Create a Windows Application Package Project, and add the console app and the UWP as application reference to the Package Project.
Declare the extension in the package manifest of the Package Project
launch it from the UWP app.
You could refer Stafen's blog for more details.
And the result:
In the end I managed to create the environment variables. Through the UWP application we have to execute the console application and through the console application execute the CMD setx command through the Process class, this is the code:
Process cmd = new Process();
cmd.StartInfo.FileName = "cmd.exe";
cmd.StartInfo.RedirectStandardInput = true;
cmd.StartInfo.RedirectStandardOutput = true;
cmd.StartInfo.CreateNoWindow = true;
cmd.StartInfo.UseShellExecute = false;
cmd.Start();
var testPath = "c:\...";
cmd.StandardInput.WriteLine(#"setx testName + " \"" + testPath + "\"");
And with this we manage to bypass the restrictions that UWP has in the sandbox in which the applications are executed:

Access is denied despite using broadFileSystemAccess

UWP is killing me.....
I had to reinstall VisualStudio2017 after a computer crash. And now, my app that was working perfectly well before the crash refuses to work.
I've been using the broadFileSystemAccess capability in the Package Manifest, as per the instructions in the MS documentation:
xmlns:rescap="http://schemas.microsoft.com/appx/manifest/foundation/windows10/restrictedcapabilities"
IgnorableNamespaces="rescap uap mp desktop4 iot2">
and
<Capabilities>
<rescap:Capability Name="broadFileSystemAccess" />
</Capabilities>
This worked no problem, but now I get an underlined rescap:Capability and the compile warning "The element 'Capabilities' in namespace 'http://schemas.microsoft.com/appx/manifest/foundation/windows10' has invalid child element 'Capability' in namespace .......
Since it's a warning, it compiles without a hickup. However, the application cannot access files (access denied) justa s if this manifest code wasn't there.
I'm holding back saying bad words.... anybody has any idea of what is causing this? It's a fresh VS2017 install.
Thanks!
Ok so heres some of my findings.
1. an app must not declare both broadFileSystemAccess and any of the other three file-system capabilities. (Pictures, documents, downloads)
source: https://social.msdn.microsoft.com/Forums/windowsapps/en-US/415d02da-eeb6-45b3-b6e2-946b124d14b0/broadfilesystemaccess-issue?forum=wpdevelop
2. This only works with the storageFile api NOT File.Exists etc api
source: https://learn.microsoft.com/en-gb/windows/uwp/packaging/app-capability-declarations
3. Make sure the fileAccess is enabled as with the other two answers:
source: https://stackoverflow.com/a/57703368/2987066
4. I also found that every time I started debugging (and the code had changed) I needed to turn that setting on and off again to get it to work
source: frustratingly debugging the application through trial and error
Thanks microsoft for your excellent development environment, it really shows how much developers love developing your apps as your store is really flourishing in comparison to your competitors... oh wait..
Thank you for reporting this issue. It's a known issue in 1809. The relevant team is working on it.
Clint Rutkas has replied on this thread: No user-consent prompt on first run of broadFileSystemAccess-capable UWP app.
He suggested that we could use try/catch to catch this scenario:
try
{
StorageFile storageFile = await StorageFile.GetFileFromPathAsync(#"E:\Foo");
}
catch (Exception)
{
// prompt user for what action they should do then launch below
// suggestion could be a message prompt
await Launcher.LaunchUriAsync(new Uri("ms-settings:appsfeatures-app"));
}
You also need to allow your app access to the file system in Settings. This a safety measure so the user of the machine acknowledges your app can have access outside the controlled access to files provided by the UWP app container it runs in.

How to get a C# azure service that uses ChromeDriver to work in an Azure Cloud Service

I've written a C# Azure cloud service that uses Selenium.WebDriver.ChromeDriver but it doesn't work when I deploy it to Azure (Locally it runs fine - probably because I have Chrome installed).
I deploy chromedriver.exe with my service but it fails because chrome.exe isn't found.
I've tried deploying a copy of chrome.exe but that didn't work. I also tried adding the GoogleChrome nuget package but this also didn't work.
Anyone know a way to get a C# azure service that uses Selenium/Chromedriver to work?
Three things you'll need to get this to run on an Azure cloudservice
ChromeSetup.exe file included in your CloudService/Roles/Role directory
A line in your service definition file to call a startup script that runs the above file
That startup script included in your worker role's project
To add ChromeSetup.exe, right click on the name of your role beneath the cloud service and just "Add Item" and find where you downloaded the chrome installer last.
The startup task is added by going into the ServiceDefinition.cdef file--example from a recent project below.
<WorkerRole name="WebReportDownloader" vmsize="Small">
<Startup>
<Task commandLine="Initialization\Startup.cmd" executionContext="elevated" taskType="simple">
<Environment>
<Variable name="MyVersionNumber" value="1.0.0.0" />
</Environment>
</Task>
</Startup>
The script the above task calls is pretty simple and logging anything to a text file is optional from my reading:
ECHO The current version is %MyVersionNumber% >> "%TEMP%\StartupLog.txt" 2>&1
START ChromeSetup.exe
EXIT /B 0
Hopefully this saves you some of the grief I ran into while piecing together several resources...
I found another way of doing this without having to install Chrome - instead of using Chrome I ended up using Chromium.
For this I just downloaded the Chromium archive from https://chromium.woolyss.com/download/ then have it extract to my binaries directory - this still has Chrome.exe binary but doesn't need installing

How do I mimic the build and deploy functionality in the AWS Toolkit for Visual Studio via a script?

I have a .NET solution with several different projects. Each of them I have now set up via the AWS Toolkit so I can just right click and hit "Redeploy to AWS..." but what I would like to do create a script (PowerShell maybe?) that builds and deploys all of my projects automatically.
I know there is a CLI version of the AWS Toolkit called awsdeploy.exe but it doesn't seem like that will perform the compilation and archiving of a project like the AWS Toolkit plugin does.
How do I mimic this behavior?
So I'm currently tackling this question at work, with partial success. What I have found is that you can do the packaging with msbuild, and then deploy with awsdeploy.
For example, if I have a visual studio solution call bas, with two projects, foo and bar, and I want to deploy bar, then I first package bar with msbuild.
msbuild bar/bar.csproj /t:Package /p:PackageLocation=barPackage.zip
This should create a package call barPackage.zip under the bar directory. If you don't find it, look at the msbuild output as it should let you know where it was created.
Now that we have the package, we can deploy. Awsdeploy needs a configuration file. It's just a file that contains key value pairs of the form "key = value". There is an example file in a directory called Samples\, in the same directory where the awsdeploy.exe is located.
If you are using visual studio there is an option for creating the config file while deploying to aws.
More info: http://docs.aws.amazon.com/AWSToolkitVS/latest/UserGuide/tkv-deployment-tool.html#deployment-tool-configuration-file-format
Let's assume we have a configuration file called deployConfig.txt then we can call awsdeploy like so
awsdeploy /r deployConfig.txt
Note that the /r is for redeploy. This assumes that you already have an environment running.
If you don't want to put credential inside the file, you can also do.
awsdeploy /r /DAWSAccessKey=stuff /DAWSSecretKey=stuff deployCon
In general anything we don't want on the file we can specify on the command like by adding /Dsomething=stuff. As you can see above to specify AWSSecretKey we do /DAWSSecretKey=stuff.
The visual studio generated file does not list the location of the package so what I've been doing is
awsdeploy /r /DAWSAccessKey=stuff /DAWSSecretKey=stuff /DDeploymentPackage=bar/bar.zip deployConfig.txt
This almost works for me. But sadly it doesn't quite do the trick. It deploys the package, and I can see the environment trying to load it but fails at some point. I don't know why it's failing to load it. It loads it fine when I deploy it from visual studio.
This is how we're handling it. All of this runs on our CI server:
Step 1 - build web deploy package with msbuild:
msbuild website.csproj /t:WebPublish /p:WebPublishMethod=Package
/p:DesktopBuildPackageLocation=website.zip /p:Configuration=Release
/p:DeployIisAppPath="Default Web Site"
Step 2 - deploy with awsdeploy:
awsdeploy.exe /DAWSAccessKey=**** /DAWSSecretKey=**** /r config.txt
config.txt:
DeploymentPackage = .\website.zip
AWSProfileName = ******
Region = us-east-1
Template = ElasticBeanstalk
UploadBucket = ***********
Application.Name = ***********
Environment.Name = ***********

Installed Win Service not displaying in Service Manager

I have a Windows Service created in c#.
It's relatively simple compared to some of the other ones that I've worked on.
I built a setup project to install it for some testing.
I added the primary output from the service project and all the dependencies were added correctly.
I went to View > Custom Actions and added my Primary output to Install, Commit, Rollback, and Uninstall.
The project built and I right clicked the project and clicked Install.
The installation came back successful, I can view the service on the control panel under Add/Remove programs, but when I go into the Service Manager... nothing...
Can anyone provide some insite or anything else that may cause a successfuly installed service to NOT display on the Service Manager.
Forgive me if this goes without saying, but you haven't mentioned what code you are executing in your custom actions. Your service assembly must have a class which derives from System.Configuration.Install.Installer, and that class must have the [RunInstaller(true)] attribute on it. Within that class, you will need to create an instance of System.ServiceProcess.ServiceInstaller and System.ServiceProcess.ServiceProcessInstaller, set the appropriate parameters on those instances, and add them to the Installers collection. The ServiceInstaller and ServiceProcessInstaller MSDN pages have a very basic example, but it should be enough to get you there if this is what is needed.
Make sure you had provided some value in "Display name" property.
Use the following command "sc query <service_name>" from command prompt to see whether your windows service got properly installed. If you are not sure on the service name use the following command "sc query state= all >c:\ServicesList.txt" after executing this command search the ServicesList.txt in your C:\ drive.
If that too doesn't work try looking for the service name in registry under HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services
You said you added your primary output to Install, etc. But did you create an Installer derived class to do the actual installing of the windows service? I'm not talking the setup project itself, but in your project there should be an installer class that actually does the service install for you.
I had a post on my blog about creating a framework for easy installable services, it has examples on creating the isntaler class.
http://blackrabbitcoder.net/archive/2010/10/07/c-windows-services-2-of-2-self-installing-windows-service-template.aspx
In my case, solution of the problem was simple, i forgot to add access modifier 'Public' to the class. After adding access modifier, service is visible now in services list.

Categories

Resources