Asynchronous task using Task.Factory.StartNew() - c#

At some point of execution of our project we are using Task.Factory.StartNew() for creating asynchronous tasks. which are required to delete some temporary files. following is the code i am using for this :
Task.Factory.StartNew(Function() deleteTempDocs(path))
The problem is that some folders may have privilege restrictions. so i need to run this tasks with Administrator Rights. even if my project is not running in admin Rights. is it possible to set rights like this?

It isn't possible to run a task with Administrator rights, as rights are assigned on a process level. You would have to start a new process, for example a batch file, and get it to run as administrator.
var process = new Process();
var processStartInfo = new ProcessStartInfo();
processStartInfo.Verb = "runas"; // runs as Administrator
processStartInfo.FileName = "myFileDeleter.exe";
process.StartInfo = processStartInfo;
process.Start();
process.WaitForExit();

Related

Being prompted for uac using c# process

I am trying to run an exe inside a console application. I am being prompted for UAC to enter admin credentials. The thing is i only have read and execute permissions. I cannot give full permissions as it is on a server.
using (Process process = new Process())
{
process.StartInfo.Verb = "runas";
process.StartInfo.FileName = ImgToDjvuPath;
process.StartInfo.Arguments = string.Format("\"{0}\" -profile \"{1}\" \"{2}\" \"{3}\"", ImgToDjvuPath, "fine200up", localNewDjvuFile, localNewDjvuFile);
process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
process.StartInfo.CreateNoWindow = true;
process.Start();
process.WaitForExit(10 * 60 * 1000);
}
I want to be able to run this code and have it work without being prompted for uac.
This is why i do not like stack overflow, you ask a specific question and rarely get a specific answer. Then get marked down for asking a valid question. I figured it out about 2 minutes after i posted. Thanks to those to actually tried to help for being constructive and helping.
If you want to start a new process and if you want process to run as administrator, you need RunAs verb.
UAC prompt will be shown ONLY IF the process invoker does not have administrative rights.
For your case, if you do not want process to be executed as Admin, then you should remove below line from the code:
process.StartInfo.Verb = "runas";

Start Azure Storage Emulator for non-Admin users on Startup

At work we use Azure functions for simple tasks.
To debug or run the function you need a running Azure Storage Emulator.
The problem is that our developer accounts don't have admin privileges so we can't start the emulator ourselves.
For now we solve this by asking an admin to start it for us, but that works only until you restart/turn off the machine.
We tried many things for the emulator to start for each user( as if it was run by the admin) but nothing worked.
Here is one of the methods we tried. A simple program that runs at startup and starts the emulator. If you start it manually as admin it does the job and the emulator starts without problems.
But when scheduled to start(with the admin account) at startup or at logon it starts it but only for the admin account and not the current user.
Code for the program we run at startup:
internal class Program
{
private static void Main(string[] args)
{
System.Diagnostics.Process process = new System.Diagnostics.Process();
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal;
startInfo.FileName = #"C:\Program Files (x86)\Microsoft SDKs\Azure\Storage Emulator\AzureStorageEmulator.exe";
startInfo.Arguments = "start";
process.StartInfo = startInfo;
process.Start();
}
}
Do you have any idea or suggestions how to solve the above problem ?
P.S:I have searched the related topics posted on StackOverflow for issues of the same kind but they ware not much help or the use-case was different.
:)
As per this link: the first time you run your emulator, the emulator environment will need to configure itself: it will create a database in LocalDB and it will register some HTTP ports. In order for the configuration process to succeed, you need administrator privilege.
The next time you'll run the storage emulator, you will no longer need administrator privilege.
So there is a tricky way, just for your reference.
you can use administrator to start the emulator, then wait for a few seconds(it finishes the inialization), stop emulator.
Then you can use normal user account to start it, it would be run for you.
Code like below:
with admin account:
private static void Main(string[] args)
{
System.Diagnostics.Process process = new System.Diagnostics.Process();
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal;
startInfo.FileName = #"C:\Program Files (x86)\Microsoft SDKs\Azure\Storage Emulator\AzureStorageEmulator.exe";
startInfo.Arguments = "start";
process.StartInfo = startInfo;
process.Start();
//Wait for finished initialization
System.Threading.Thread.Sleep(TimeSpan.FromSeconds(10));
//After initialization, close the Emulator
Process[] processes = Process.GetProcessesByName("AzureStorageEmulator");
foreach (var p in processes)
{
p.Kill();
}
}
Then you can start Emulator again using your developer account, the code is similar to the above.
It maybe a not good choice, you can also submit an question on here.

Scheduling tasks with 'schtasks' without admin privileges C#

I am trying to schedule the tasks from my application using schtasks instead of using the Windows Task Scheduler COM/managed API.
Creating a task here is easier by using this on command line schtasks /Create /tn "MyApp" /tr c:\myapp.exe /sc onlogon but I opened the command line as an administrator to get the task created (otherwise I get access denied)
From my application, to create the task I use
string args = #"/Create /tn MyApp /tr c:\myapp.exe /sc onlogon";
Process.Start("schtasks", args);
However, the task gets created only if I run my application as an administrator. I need to avoid this, so that any user can create the task without the hassle of running the app as admin. Any suggestions on how ca this be done?
You can try with a sort of RunAs that allow to run a process with a specified user :
ProcessStartInfo psi = new ProcessStartInfo("schtasks");
psi.UseShellExecute = false;
psi.UserName = "Username";
psi.Password = "password";
Process.Start(psi);
The Process class through ProcessStartInfo provides a mechanism which allows you to specify the user context that the new process should run under, so you can specify the user in which you want to run the command even if the user that start the program is different. In your case you can specify Administrator credentials to the ProcessStartInfo without having to run the program with an Administrator user ...
Why should that require user interruption each time in an exhibition
booth PC which is mounted just for exposition purpose?
If you want a hidden program that will run on a PC whenever it is booted, and your task is not harmful, you can add it to the following registry key:
HKCU\Software\Windows\CurrentVersion\Run
programmatically. I can provide code if needed.
Contents of TextBox: "SCHTASKS.exe /Create /ST 06:30 /SC DAILY /TN report /TR notepad.exe"
I was able to use Process.Start(ProcessStartInfo);
ProcessStartInfo psinfo = new ProcessStartInfo();
psinfo.Filename = "powershell.exe";
psinfo.Args = textbox1.text;
Process.Start(psinfo);
**Of course, this will only work on machines that have powershell installed, using cmd.exe failed to create the scheduled task...

Run process under current user

There is "Setup project" in VS. During installation I launch another process:
System.Diagnostics.Process process = new System.Diagnostics.Process();
//fill StartInfo and run call Start()
process.Start();
If I run installer under Windows 7 and install for "Everyone", process start under the SYSTEM. If I install "Just for me", process start under Current user. How do I always start process under Current user?
I have found very simple solution. All that you need it just create a new class and copy text from this link.
To launch the process call ProcessAsUser.Launch("program name");
I had a similar problem: My setup extension (custom action) needed Admin privileges which brought up an elevation box. After I start my application at the end of "Just for Me" the process had settings that were made for the admin context. For example my user account likes to see all extensions of files in Windows Explorer but the admin account was configured to hide them. So in every file open box I couldn't see the extensions. To cure this this piece of code worked:
ProcessStartInfo startInfo = new ProcessStartInfo(ShortcutTarget);
startInfo.LoadUserProfile = true;
startInfo.UseShellExecute = false;
Process.Start(startInfo);
It works only in "Just for Me" mode, in "Everyone" the admin's settings are used. But this is ok for me.
Use ProcessStartInfo class and its property UserName, then use it as argument for Process.Start static method.
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.UserName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
Process.Start(startInfo);

Admin rights for a single method

Is it possible to require administrator rights for one single method?
Something like this:
[RequireAdminRightsForThisMethod()]
private void TheMethod(){
// Do something
}
You can add a PrincipalPermission attribute to your method to demand administrative privileges for its execution:
[PrincipalPermission(SecurityAction.Demand, Role = #"BUILTIN\Administrators")]
public void MyMethod()
{
}
This is described in more detail in the following article:
Security Principles and Local Admin Rights in C# .Net
If you are looking for a way to elevate an already existing process I doubt that this is possible as administrator privileges are given on process-level to a process upon startup (see this related question). You would have to run your application "as administrator" to get the desired behavior.
However, there are some tricks that might allow you to do what you want, but be warned that this might open up severe security risks. See the following thread in the MSDN forums:
Launching MyElevatedCom Server without prompting Administrator credentialls from Standard User
Update (from comment)
It seems that if an update requires elevation your application update is best done by a separate process (either another executable, or your application called with a command line switch). For that separate process you can request elevation as follows:
var psi = new ProcessStartInfo();
psi.FileName = "path to update.exe";
psi.Arguments = "arguments for update.exe";
psi.Verb = "runas";
var process = new Process();
process.StartInfo = psi;
process.Start();
process.WaitForExit();
A method can require administrative privileges to run, but it's not possible to automatically elevate to Admin when executing a method.

Categories

Resources