I'm trying to create an application in C#.Net, and I need it to scan the processes that the user start and stop, but I'm getting an "Access Denied" on the .Start()
Here is what I've got so far
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
using System.Management;
using Security;
using MySQLConnectivity;
namespace MyApp
{
public partial class Login : Form
{
MySQLClass sql = new MySQLClass();
ManagementEventWatcher processStartEvent = new ManagementEventWatcher("SELECT * FROM Win32_ProcessStartTrace");
ManagementEventWatcher processStopEvent = new ManagementEventWatcher("SELECT * FROM Win32_ProcessStopTrace");
public Login()
{
InitializeComponent();
processStartEvent.EventArrived += new EventArrivedEventHandler(processStartEvent_EventArrived);
processStartEvent.Start();
processStopEvent.EventArrived += new EventArrivedEventHandler(processStopEvent_EventArrived);
processStopEvent.Start();
}
void processStartEvent_EventArrived(object sender, EventArrivedEventArgs e)
{
string processName = e.NewEvent.Properties["ProcessName"].Value.ToString();
string processID = Convert.ToInt32(e.NewEvent.Properties["ProcessID"].Value).ToString();
MessageBox.Show("Process started. Name: " + processName + " | ID: " + processID);
}
void processStopEvent_EventArrived(object sender, EventArrivedEventArgs e)
{
string processName = e.NewEvent.Properties["ProcessName"].Value.ToString();
string processID = Convert.ToInt32(e.NewEvent.Properties["ProcessID"].Value).ToString();
MessageBox.Show("Process stopped. Name: " + processName + " | ID: " + processID);
}
}
}
I've searched online hours, but couldn't find anything. People that had this problem, had it remotelly, and not locally. I am using Windows Pro 8.1 + Microsoft Visual Studio Ultimate 2013, just in case that versions of VS or OS may be important in this case.
The problem triggers on processStartEvent.Start() saying "Access denied".
I also tried to switch from .Start() to .WaitForNextEvent() with the same result
Anything that I'm missing here?
ClickOnce was activated. Disabling it solved my problem. Thanks tho.
Related
I am trying to create a Configuration Tool for new devices, which has to be set up.
That's why I am trying to set the local hostname with a Button.
I want to use the name which I wrote in a textbox
public void SetMachineName(string newName)
{
// Create a new process
ProcessStartInfo process = new ProcessStartInfo();
// set name of process to "WMIC.exe"
process.FileName = "WMIC.exe";
// pass rename PC command as argument
process.Arguments = "computersystem where caption='" + System.Environment.MachineName + "' rename " + newName;
// Run the external process & wait for it to finish
using (Process proc = Process.Start(process))
{
proc.WaitForExit();
// print the status of command
Console.WriteLine("Exit code = " + proc.ExitCode);
}
}
public void Click_sethostname(object sender, RoutedEventArgs e)
{
SetMachineName(Textbox_sethostname.Text);
}
WPF setup
I have following namespaces:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Threading;
using Microsoft.Win32;
using System.Management;
using System.Diagnostics;
Hey Members i am new to C# Language and Visual Studio Platform recently i am learning how to connect access Database with visual Studio and first time with same code i have connected with database but after some time when i compiled again then there is error given in Title.
why this is happening ?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.OleDb;
namespace Clinic_Management_System
{
public partial class Login : Form
{
public Login()
{
InitializeComponent();
}
private void Login_Load(object sender, EventArgs e)
{
try
{
OleDbConnection connection = new OleDbConnection();
connection.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users
\Hassan Gillani\Documents\Clinic Management System.accdb; Persist Security Info = False; ";
connection.Open();
label1.Text = "Connected to Clinic Management System Database";
connection.Close();
}
catch (Exception exp)
{
MessageBox.Show("Error " + exp);
}
}
}
}
please visit given like to view screen short
http://s33.postimg.org/5ltm4dtnj/Error.png
Using the verbatim character (#) and splitting your path in the middle in not a good idea.
Spaces counts in paths so the filename used for your connection is
C:\Users \Hassan Gillani\Documents\Clinic Management System.accdb;
If you try to use File.Exists on this string you get false as result.
Do not split your connection string in the middle of the path
connection.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;
Data Source=C:\Users\Hassan Gillani\Documents\Clinic Management System.accdb;
Persist Security Info = False; ";
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Diagnostics;
namespace WindowsFormsApplication
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
var newProcessInfo = new System.Diagnostics.ProcessStartInfo();
newProcessInfo.FileName = #"C:\Windows\SysWOW64\WindowsPowerShell\v1.0\powershell.exe";
newProcessInfo.Verb = "runas";
System.Diagnostics.Process.Start(newProcessInfo);
newProcessInfo.Arguments = #"sfc /scannow";
}
}
}
So my code works up to a point. you click the windows form application button and it will run windows Powershell in 64bit as an administrator but won't run a .ps1 script "c:\path\script.ps1" or the command directly written out like the "sfc /scannow" above.
I was reading that the powershell commands won't work sometimes if the "Set-ExecutionPolicy Unrestricted" isn't loaded somewhere in the beginning of the code.
Please help! I have been looking everywhere for an answer.
First of all, you need to specify the Arguments property before you start the process:
var newProcessInfo = new System.Diagnostics.ProcessStartInfo();
newProcessInfo.FileName = #"C:\Windows\SysWOW64\WindowsPowerShell\v1.0\powershell.exe";
newProcessInfo.Verb = "runas";
newProcessInfo.Arguments = #"sfc /scannow";
System.Diagnostics.Process.Start(newProcessInfo);
Second, you'll need to tell PowerShell that sfc /scannow is a command, and not command line switches.
On the command line you would do powershell.exe -Command "sfc /scannow", so the correct Arguments value in your case would be
newProcessInfo.Arguments = #"-Command ""sfc /scannow""";
("" is the escape sequence for " in verbatim string literals)
For .ps1 files, use the -File switch:
newProcessInfo.Arguments = #"-File ""C:\my\script.ps1""";
If you don't know the execution policy on the target system, you can bypass it without affecting the machine-wide policy with -ExecutionPolicy Bypass:
newProcessInfo.Arguments = #"–ExecutionPolicy Bypass -File ""C:\my\script.ps1""";
I am testing a C# WPF program that requires elevated privileges, that loads without any delay if I am logged on as an admin, but if I am logged on as a standard user (99% of time) then there is a delay of about 30 seconds before the UI appears.
Using the same elevation code in a C# console app and in a c# Winforms app, there is no delay in loading, so I know that the code works.
So, can anyone explain to me why is there a delay associated with WPF; and is there a workaround?
Here is the code from app.xaml.cs ( the remainder of the project is as genereated by VS2010)
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Windows;
using System.Security.Principal;
using System.Diagnostics;
using System.Reflection;
using System.ComponentModel;
using MyNewServiceLib;
using System.Runtime.InteropServices;
namespace WhySoSlow
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
if (!IsAdmin())
{
StartAsAdmin(e);
Application.Current.Shutdown();
}
else
{
MainWindow = new MainWindow();
MainWindow.SizeToContent = SizeToContent.WidthAndHeight;
MainWindow.WindowStartupLocation = WindowStartupLocation.CenterScreen;
MainWindow.Show();
}
}
bool IsAdmin()
{
WindowsIdentity id = WindowsIdentity.GetCurrent();
WindowsPrincipal p = new WindowsPrincipal(id);
return p.IsInRole(WindowsBuiltInRole.Administrator);
}
private void StartAsAdmin(StartupEventArgs e)
{
string[] args = e.Args;
try
{
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.UseShellExecute = true;
startInfo.WorkingDirectory = Environment.CurrentDirectory;
Uri uri = new Uri(Assembly.GetExecutingAssembly().GetName().CodeBase);
startInfo.FileName = uri.LocalPath;
startInfo.Arguments = String.Join(" ", args);
startInfo.Verb = "runas";
Process p = Process.Start(startInfo);
}
catch (Win32Exception exception)
{
MessageBox.Show(exception.Message);
}
}
}
}
Further info
Weirdly, if I start the program from a cmd prompt running under NT Authority\System, there is no delay starting up the UI. After that one successful start, every further start, from whatever prompt, be it standard user prompt, run as administrator, the program starts without delay; UNTIL that is, I log off from the session.
After logging on again to a new (standard user) session, all attempts to start the program result in the 30 second delay before showing the UI.
I can only think that this is some kind of UAC bodge by Microsoft, that is hindering the startup of wpf.
Instead of using this code, have you tried utilizing a manifest file? Running an application as admin is one of the things you can do with it.
this might help https://msdn.microsoft.com/en-us/library/ms742884.aspx
I have ran a debug stepping through the program and it crashes at the following line
Runspace runspace = RunspaceFactory.CreateRunspace();
It gives the following error
An unhandled exception of type 'System.InvalidProgramException' occurred in PrimarySMTP_Fix.exe
Additional information: Common Language Runtime detected an invalid program.
This is my first time working with Power Shell through C# and I'm having trouble getting some simple code execution. The point of the project is to automate a simple fix for a common issue with our company's exchange server.
The complete code is below.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Management.Automation;
using System.Collections.ObjectModel;
using System.Management.Automation.Runspaces;
namespace PrimarySMTP_Fix
{
public partial class MainWindow : Window
{
//Variable Declarations
string userName = "";
string confirmUser = "";
string primarySMTP = "";
string confirmSMTP = "";
public MainWindow()
{
InitializeComponent();
}
private string RunScript(string scriptText)
{
Runspace runspace = RunspaceFactory.CreateRunspace();
runspace.Open();
Pipeline pipeline = runspace.CreatePipeline();
pipeline.Commands.AddScript(scriptText);
pipeline.Commands.Add("Out-String");
Collection<PSObject> results = pipeline.Invoke();
runspace.Close();
StringBuilder stringBuilder = new StringBuilder();
foreach (PSObject obj in results)
{
stringBuilder.AppendLine(obj.ToString());
}
return stringBuilder.ToString();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
userName = adUser.Text;
confirmUser = confirmAD.Text;
primarySMTP = mail.Text;
confirmSMTP = confirmMail.Text;
outPut.Text = RunScript(userName);
}
}
}
The above is just setup to test. For now it's taking just the username information and running it directly as a command. If I can get that to work and output information then I can re-write it to do what I want it to do.
After playing around for a while I found that I needed to reinstall the Windows Management Framework to get it to work. Figured that out when I put the debug build on the server and ran the test there and it worked.