I have a winform that allows me to enable and disable all my 8 year old's network adapters using this code:
protected override void OnStart(string[] args)
{
//start timer
SelectQuery query = new SelectQuery("Win32_NetworkAdapter","NetConnectionStatus=2");
ManagementObjectSearcher search = new ManagementObjectSearcher(query);
foreach (ManagementObject result in search.Get())
{
NetworkAdapter adapter = new NetworkAdapter(result);
adapter.Disable();
enabled = false;
}
InternetCheckTimer.Start();
}
This code works fine on a win form assuming I am running with admin. I have never written a win service before so the problem might be else where, I am able to install using installutill and attach the debugger to the process, however no break points are hit. I have tried starting and stopping the process and cannot get the debugger to attach so I might be doing that wrong as well... Right now I am assuming that the code is running and I am too stupid to get the debugger working. That said, I think my code requires the service to have admin like the form did in order to work.
Sorry if this is unclear, I will do my best to clear it up if you need more information.
Use user and password for the service, and assure that the user that start the service has all rights needed for the application to run.
An other possibility if you can control the service is to use impersonation, see: http://www.codeproject.com/Articles/4051/Windows-Impersonation-using-C.
You can try couple of options.
Add app.manifest
After installing window service set the service permission to run at Highest Privilege and also you can set the user name and password for the logged in user.
How to Get Full Administrator Rights in Windows 7:
Click Start
Click Computer (you might also find this icon on the desktop).
Right click on the Hard Disk icon where your OS is installed on and click Properties.
Click the Security tab.
Click the Advanced tab.
Click the Change Permissions button located after the Permission Entries list.
A new window will appear on your screen; which contains a list of all the User Accounts
Select the user account you want to give total control over your Windows 7) and click the Edit button.
Now, tick the checkbox labeled "Total Control" and press OK.
You're all done!
Related
I need to start a windows forms application with admin rights whenever a domain user logs in.
I am trying to start the application with service and task scheduler but the application UI does not show up. However I can see it running in the task manager. and if I add a timer and terminate the app. it terminates after correct interval as well.
Can someone help me on how to develop/deploy an application so that it shows "the UI" when whenever any user logs in to the machine. should I add some registry entry that will start me application or is there any other way to achieve this..
It seems to me that when the user logs in, the task does not really work because there are not enough rights. Try it like this:
you need to create a new task that simply launches the program you want to use without UAC dialogs. When creating this task, in the General tab, enter the name of the task (remember this name, you will need it later) and check the box that says “Run with highest privileges - Run with highest privileges”. This puts the task to run with administrator rights.
To make sure there are no compatibility issues, go to the “Configure for” drop-down list at the bottom of the Create Task window and select Windows ® 7, Windows Server ™ 2008 R2.
On the Actions tab - Actions, you need to create an action that launches the program. Everything is very simple here: select the action “Start a program”, specify the path to the program that will be executed, and click OK.
Your last stop is on the Settings tab. Here you need to make sure that the checkbox “Allow task to be run on demand” is checked. Also, make sure that when the task is already running, another instance will not be started by choosing the option “Do not start a new instance”
The second step in this procedure is to create a shortcut that launches the task you just created, which in turn launches the program of your choice without the UAC line appearing.
An important difference when creating a shortcut to a task compared to a normal shortcut on the desktop is to enter schtasks / run / tn Task Name - Schtasks / run / tn “Task Name” (Task Name must be replaced with the actual task name) in the Item Location field. In this command, the / Run parameter simply performs a specific task, and / tn allows you to enter the name of the task you want to run.
Once the shortcut is created, if you click on it, it will work like the task you created, and this in turn launches the program specified with administrator rights, but without UAC.
Thus, you can create a task to run the created shortcut.
To check if user has logged in into a domain, you can use
System.Security.Principal.WindowsIdentity.GetCurrent.Name which gives you "domain\username".
and for starting your application once user logged in, you have to run your program at start up, try this link.
And to run your app at startup using group policy (recommended) try this.
I'm using Windows 10. Here is my code to map the network drive.
System.Diagnostics.Process p = new System.Diagnostics.Process();
p.StartInfo.UseShellExecute = true;
p.StartInfo.Verb = "runas";
p.StartInfo.FileName = "net.exe";
p.StartInfo.Arguments = "use Z: " + dPath; //dPath has escaped characters
p.Start();
What I was trying to do was trying to run the command net.exe use Z: DPATH as administrator but the Z drive does not appear in File Explorer but when I run the exact same command using cmd with Admin rights, the Z drive appears correctly.
Proof of mapped drive
My Network drive is mapped as evidenced below (Encountered this error when trying to re-map it manually) just that it wasn't appearing under Network Locations in File Explorer > This PC.
This behaviour is caused by UAC (User Account Control). When logging on to Windows as an admin, there are two sessions created. One with admin rights and one without. When you map the drives programmatically, you are doing it with the session with admin rights.
However, when you use File Explorer to view the Network Locations, you are using standard rights. For mapped drives, the admin and standard rights are not shared. Hence, the admin is not able to view the mapped drive eventhough it was created with admin rights.
Solution 1
Click Start, type regedit in the Start programs and files box, and
then press ENTER.
Locate and then right-click the registry subkey
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System.
Point to New, and then click DWORD Value.
Type EnableLinkedConnections, and then press ENTER.
Right-click EnableLinkedConnections, and then click Modify.
In the Value data box, type 1, and then click OK.
Exit Registry Editor, and then restart the computer.
Solution 2
Run File Explorer as administrator
When making a right click on the Explorer and select "Run as
administrator" it doesn't start the Windows Explorer with admin
rights. The Windows Vista/7/8/10 Explorer includes a special function to
block such requests.
To disable it, start regedit.exe and go to the following key:
HKEY_CLASSES_ROOT\AppID{CDCBCFCA-3CDC-436f-A4E2-0E02075250C2}
make a right click on Permissions and set your user as owner of the key and
give your current user writing permissions.
Next, delete or rename the value RunAs. Now the Elevated-Unelevated
Explorer Factory is disabled and you can start the Explorer with admin
rights.
Solution 3
If the above can't work, disable your UAC (User Account Control) by going into User Account Control Settings and moving the slider to Never notify
Also, if you have Professional, Enterprise, or Ultimate version of windows installed, you need to look into a program in Administrative tools called Local Security Policy and disable all the policies related to UAC in Security Settings > Local Policies > Security Options (Located in the bottom 15 policies of the list)
It helped me restarting explorer.exe with admin rights via Task Manager.
I have created a simple weather application and I added the code below to let the user let it run on Startup:
RegistryKey rk = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
if (startupCheck.Checked) {
rk.SetValue("WeTile", "\"" + Application.ExecutablePath.ToString() + "\"");
} else {
rk.DeleteValue("WeTile", false);
}
Now this runs fine on both my computers. But when I gave the app to my girlfriend. She said the app does not run on windows start up. I read it online that it could be because of the user permission or the location so I told her to move the app to c:/ and try checking the box again and then restarting. Now it works but on every startup she has the default windows message saying you want to run this app?
How do I get rid of this? What is the best way to add to windows startup that works with both windows 32/64 bit without any user permission disruptions?
It sounds like you may have run afoul of Windows' file blocking security function. Applications created on another computer are automatically blocked from executing unless the user specifically "unblocks" the file. Have your girlfriend right-click on the executable, select "Properties" and see if there is a button at the bottom of the dialog to unblock the file.
Once unblocked, you should no longer see the confirmation prompt at startup.
You could add it to the Windows startup folder, check if it's not there already and if not, add it (assuming this is what the user wants).
See How do I set a program to launch at startup
I need to give my application administrator rights, knowing that it will be run from a user session and not admin account.
I've looked on other sites, but can't find anything that helps.
I tried editing the manifest among other things and there have inserted the line:
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
This gave me an error when trying to publish using ClickOnce, but not when I debug.
Can you help me?
first of all - indeed, it's not allowed by design, to install and ClickOnce app as admin: http://msdn.microsoft.com/en-us/library/142dbbz4(v=vs.90).aspx
take a look at this post: http://antscode.blogspot.ca/2011/02/running-clickonce-application-as.html -
it explains how to run ClickOnce app as admin. BUT - it have to say that I have walked this path - and I did not have much luck with it. I had numerous troubles with this approach (trying to run ClickOnce app with admin privileges). As far as I recall, the biggest problem was auto-update was not working properly. Not to mention that non-admin users might need to enter admin credentials all the time.
So my advise would be to rethink your logic, and encapsulate the piece you need to be done as admin in a separate EXE file - and make it very clear for a user that when he clicks THAT button, UAC prompt will show up (probably by addin "shield" icon to the button). And in that button_click event do something like this:
// 2. Run Photoshop action on this image (and wait for the task to complete)
if (string.IsNullOrWhiteSpace(this.PhotoshopEnhanceActionAbsPath) == false)
{
var pi = new ProcessStartInfo(this.PhotoshopEnhanceActionAbsPath, "\"" + imgPhotoshopActionAbsPath + "\"");
pi.UseShellExecute = true;
pi.Verb = "runas";
var photoshopAction = Process.Start(pi);
var success = photoshopAction.WaitForExit();
if (success == false)
{
// do something here
}
}
this approach worked very well for me. The key here is this:
pi.UseShellExecute = true;
pi.Verb = "runas";
it runs your EXE with admin right - so UAC prompt will be displayed at that moment. Another nice consequence here is that users might not run this particular piece of logic each time they are using the app - and therefore they won't be annoyed by the prompt when they do not need it.
I'm pretty sure that this behaviour is by design.
ClickOnce apps are designed to be installable without Administrator privileges. It's not possible to elevate them at runtime as this means that effectively a user with no admin rights could install then run the app as admin; this would be a security risk.
I've been tasked with writing a simple command line utility in C# that will monitor a directory on a server that several users will be accessing to copy/cut/paste/view data. I used FileSystemWatcher to do this but it's lacking a couple features.
Is it possible to determine the user or at least the computer name from where the file is being accessed/modified?
(Note: This doesn't have to be with FileSystemWatcher, I'm looking for ANY way to do this.)
I don't think you'll be able to monitor this from C# directly. Not without the help of the host operating system anyway. Windows and NTFS allow you to audit a particular directory and log the accesses in the Security event log for the host machine (so the server hosting the share would have to audit, not the client).
From KB310399 - How to audit user access of files, folders, and printers in Windows XP
Auditing User Access of Files, Folders, and Printers
The audit log appears in the Security log in Event Viewer. To enable this feature:
Click Start, click Control Panel, click Performance and Maintenance, and then click Administrative Tools.
Double-click Local Security Policy.
In the left pane, double-click Local Policies to expand it.
In the left pane, click Audit Policy to display the individual policy settings in the right pane.
Double-click Audit object access.
To audit successful access of specified files, folders and printers, select the Success check box.
To audit unsuccessful access to these objects, select the Failure check box.
To enable auditing of both, select both check boxes.
Click OK.
Specifying Files, Folders, and Printers to Audit
After you enable auditing, you can specify the files, folders, and printers that you want audited. To do so:
In Windows Explorer, locate the file or folder you want to audit. To audit a printer, locate it by clicking Start, and then clicking Printers and Faxes.
Right-click the file, folder, or printer that you want to audit, and then click Properties.
Click the Security tab, and then click Advanced.
Click the Auditing tab, and then click Add.
In the Enter the object name to select box, type the name of the user or group whose access you want to audit. You can browse the computer for names by clicking Advanced, and then clicking Find Now in the Select User or Group dialog box.
Click OK.
Select the Successful or Failed check boxes for the actions you want to audit, and then click OK.
Click OK, and then click OK.
The process is similar for the server operating systems and Windows Vista/Windows 7. If you go this route, you can have the C# program read the event log (See EventLog class) to look for the data you want.
Note: Starting with vista you must be and (UAC elevated if needed) administrator to read them from code.
Make sure to have WMI installed or enabled on your PC, also make sure to add a reference to System.Management and System.Management.Instrumentation as well. There is also a C# and VB WMI scripting application GUI that you can download to run and test WMI Queries against as well Google that one. Since I work for Dept of Defense there are certain things that I can get to from here in regards to the web other things are blocked out so please forgive me if I don't post certain web links.
Here is something to get you started
ManagementScope mgtScope = new ManagementScope("\\\\ComputerName\\root\\cimv2");
// you could also replace the username in the select with * to query all objects
ObjectQuery objQuery = new ObjectQuery("SELECT username FROM Win32_ComputerSystem");
ManagementObjectSearcher srcSearcher = new ManagementObjectSearcher(mgtScope, objQuery);
ManagementObjectCollection colCollection = srcSearcher.Get();
foreach (ManagementObject curObjCurObject in colCollection)
{
Console.WriteLine(curObjCurObject["username"].ToString());
}
//if you want ot get the name of the machine that changed it once it gets into that Event change the query to look like this. I just tested this locally and it does work
ManagementObjectSearcher mosQuery = new ManagementObjectSearcher("SELECT * FROM Win32_Process WHERE ProcessId = " + Process.GetCurrentProcess().Id.ToString());
ManagementObjectCollection queryCollection1 = mosQuery.Get();
foreach (ManagementObject manObject in queryCollection1)
{
Console.WriteLine("Name : " + manObject["name"].ToString());
Console.WriteLine("Version : " + manObject["version"].ToString());
Console.WriteLine("Manufacturer : " + manObject["Manufacturer"].ToString());
Console.WriteLine("Computer Name : " + manObject["csname"].ToString());
Console.WriteLine("Windows Directory : " + manObject["WindowsDirectory"].ToString());
}