Can't get names of running applications - c#

I am trying to get name of running applications (mozila, visual studio etc.) I try code bellow but my I get "Access Denied" exception. I don't know how to solve this?
StringBuilder sb = new StringBuilder();
foreach (Process p in Process.GetProcesses("."))
{
try
{
foreach (ProcessModule pm in p.Modules)
{
sb.Append("Image Name:\t" +
pm.ModuleName.ToString()
+ Environment.NewLine);
sb.Append("File Path:\t\t" +
pm.FileName.ToString() +
Environment.NewLine);
sb.Append("Memory Size:\t" +
pm.ModuleMemorySize.ToString() +
Environment.NewLine);
sb.Append("Version:\t\t" +
pm.FileVersionInfo.FileVersion.ToString() +
Environment.NewLine);
sb.Append(Environment.NewLine);
}
}
catch { }
}

Your code is ok, this is privilege problem.
Perhaps you are trying to get this under user account that has no privileges to access this API.
There are group called something like performance counter user, add your application account to admin or performance counter user group.
If you are using the ASP.NET, ASPNET account (configured by default) has no privileges to access this API.

Ah I solved. I changed account type from 'local service' to 'local system'.

Related

Unable to format a drive using ManagementObject from Non-Admin account

I have below code to format a USB drive. Code works fine with Admin account, but if I run the exe using Non Admin account, it returns 3 (Access Denied).
I want to format a drive in Non-Admin mode. Any help?
I visited this link https://social.msdn.microsoft.com/Forums/en-US/1e192745-9d58-4507-93f0-ceacbc0cde96/wmi-win32volume-format-method-returns-access-denied?forum=windowsgeneraldevelopmentissues , but no help
ManagementObjectSearcher searcher = new ManagementObjectSearcher(#"select * from Win32_Volume WHERE DriveLetter = '" + driveLetter + "'");
foreach (ManagementObject vi in searcher.Get())
{
var result = vi.InvokeMethod("Format", new object[] { fileSystem, quickFormat, clusterSize, label, enableCompression });
if (Convert.ToInt32(result) != 0)
{
throw new Exception("Error while formating drive");
}
}
Have you tried "Right Click> Compatibility> Change All User Settings> Run As Administrator"?
If this is the solution, you can do this with the code.
Probably, this question - answer, can answer your problem.
How do I force my .NET application to run as administrator?

Query User Sessions in Windows

There is a built-in tool: query.exe that allows you to view all active users and sessions in Windows.
It's output looks like:
PS C:\> query.exe user
USERNAME SESSIONNAME ID STATE IDLE TIME LOGON TIME
>testusr console 1 Active none 12/16/2014 9:29 AM
Right now I have code that just parses the query.exe output, but some of us are concerned that future OS upgrades might change query's output so we're looking for an API call that can be used instead.
Is there anyway .Net way to gather the same information?
For alternatives, we don't necessary need all the fields, but we do need: Username, State, and Logon Time. We also need to run this code from the System context so any code or WMI classes that requires the user context won't work for us.
Well what I found and I think could be useful for you is Cassia project.
There is almost ready for you example in main page:
ITerminalServicesManager manager = new TerminalServicesManager();
using (ITerminalServer server = manager.GetLocalServer())
{
server.Open();
foreach (ITerminalServicesSession session in server.GetSessions())
{
Console.WriteLine("Hi there, " + session.UserAccount + " on session " + session.SessionId);
Console.WriteLine("It looks like you logged on at " + session.LoginTime +
" and are now " + session.ConnectionState);
}
}
As you can see when you get a TerminalServicesSession you will find UserName, LoginTime and ConnectionState.
Hope this will help you.
You can simply get the last logon time using WMI:
using System;
using System.Management;
using System.Windows.Forms;
namespace WMISample
{
public class MyWMIQuery
{
public static void Main()
{
try
{
ManagementObjectSearcher searcher =
new ManagementObjectSearcher("root\\CIMV2",
"SELECT * FROM Win32_LogonSession");
foreach (ManagementObject queryObj in searcher.Get())
{
Console.WriteLine("-----------------------------------");
Console.WriteLine("Win32_LogonSession instance");
Console.WriteLine("-----------------------------------");
Console.WriteLine("Last Logon: {0}", queryObj["StartTime"]);
}
}
catch (ManagementException e)
{
MessageBox.Show("An error occurred while querying for WMI data: " + e.Message);
}
}
}
}
Sounds like you want NetWkstaUserEnum. I couldn't find a native .NET version of this but it seems like a fairly light interop call.

to retrieve windows login-password via asp.net

public Object IsAuthenticated()
{
String domainAndUsername = strDomain + "\\" + strUser;
***DirectoryEntry entry = new DirectoryEntry(_path, domainAndUsername, strPass);***
SearchResult result;
try
{
//Bind to the native AdsObject to force authentication.
DirectorySearcher search = new DirectorySearcher(entry) { Filter = ("(SAMAccountName=" + strUser + ")") };
search.PropertiesToLoad.Add("givenName"); // First Name
search.PropertiesToLoad.Add("sn"); // Last Name
search.PropertiesToLoad.Add("cn"); // Last Name
result = search.FindOne();
if (null == result)
{
return null;
}
//Update the new path to the user in the directory.
_path = result.Path;
_filterAttribute = (String)result.Properties["cn"][0];
}
catch (Exception ex)
{
return new Exception("Error authenticating user. " + ex.Message);
}
return user;
}
In the above code segment, is there a way to retrieve the user's Windows login password so that the LDAP authentication works without asking the user his password another time?
Can the value for "strPass",that is being passed when DirectoryEntry object is being created, be retrieved by any way?
The password does not exist anywhere. It would be a big security hole if it did.
Also, BTW, get rid of the try/catch block. It's doing nothing but hiding the reason for the exception.
Use the ActiveDirectoryMemebershipProvider - You can authenticate without writing code, thus eliminating the login scenario you currently have.
You could set up Windows Authentication in your ASP.NET app.
http://msdn.microsoft.com/en-us/library/ff647405.aspx
Once you set this up, only authenticated users have access to the protected parts of your site.
This gives you access some key bits of information.
For example:
System.Web.HttpContext.Current.User.Identity.Name - gives the name (domain\username) of an authenticated user.
System.Web.HttpContext.Current.User.IsInRole("role_name_here") - will tell you if the authenticated user is in a given role.
Authentication can be tricky to do for the first time - please do not ask a user for their windows password - this is a security risk - allow IIS and the .NET framework take care of this for you. The article above may be a bit long and seem a bit complicated but it has a lot of good information in it.

Reading EventLog C# Errors

I have this code in my ASP.NET application written in C# that is trying to read the eventlog, but it returns an error.
EventLog aLog = new EventLog();
aLog.Log = "Application";
aLog.MachineName = "."; // Local machine
foreach (EventLogEntry entry in aLog.Entries)
{
if (entry.Source.Equals("tvNZB"))
Label_log.Text += "<p>" + entry.Message;
}
One of the entries it returns is "The description for Event ID '0' in Source 'tvNZB' cannot be found. The local computer may not have the necessary registry information or message DLL files to display the message, or you may not have permission to access them. The following information is part of the event:'Service started successfully.'"
I only want the 'Service started successfully'. Any ideas?
Try this :)
EventLog aLog = new EventLog();
aLog.Log = "Application";
aLog.MachineName = "."; // Local machine
string message = "\'Service started\'";
foreach (EventLogEntry entry in aLog.Entries)
{
if (entry.Source.Equals("tvNZB")
&& entry.EntryType == EventLogEntryType.Information)
{
if (entry.Message.EndsWith(message))
{
Console.Out.WriteLine("> " + entry.Message);
//do stuff
}
}
}
It works on Win XP home. The message might be different on another OS.
Best way: dump entry.Message by System.Diagnostics.Trace.Write and see the exact message.
Hope it works smoothly :)

How do I get a real name stored in Active Directory from an username with C#?

I want to create a quick application for people to resolve the name of a user stored in Active Directory from a set of credentials. Some applications only provide the user id and it is too much to expect an end user to fire up the Active Directory Users and Groups MMC snap-in.
Input would be something like "MYCORP\a_user" and output would be "Dave Smith" if that is what is stored in AD.
I want this to be able to run in my test domain and also in a multi-forest environment.
Can someone provide a sample that does this? Does retrieval of other attributes from AD such as telephone number follow the same pattern?
Target platform: .NET 2.0 and above.
Here's the code I use, taken from my authentication class:
string[] strUserName = username.Split("\\".ToCharArray());
using (var entry = new DirectoryEntry("LDAP://" + ADServer, ADServiceDomain + "\\" + ADServiceAccount, ADServicePassword))
using (var ds = new DirectorySearcher(entry, "sAMAccountName=" + strUserName[1])) {
ds.SearchScope = SearchScope.Subtree;
SearchResult result = ds.FindOne();
string fullname = result.Properties["displayName"][0].ToString();
}
System.DirectoryServices sucks. As you can see, it takes a ridiculous amount of code to do even the most basic things. I'd like to see a user authentication method that didn't require using exceptions for flow control.
Working with Active Directory is a bit painfull in C#, sure 3.5 adds some new classes to help, but for pure productivity I like to use Powershell and Quest's free PowerShell Commands for Active Directory
in which case the code looks something like
get-qaduser userid | select PhoneNumber,DisplayName
if you need this to run as part of your C# program, you can do that too
public static IEnumerable<PSObject> Invoke(string script, params object[] input)
{
IList errors = null;
using (var run = new RunspaceInvoke())
{
var psResults = run.Invoke(script, input, out errors);
if (errors != null && errors.Count > 0)
Debug.WriteLine(errors.Count);
foreach (PSObject res in psResults)
yield return res;
}
}
PSObject psUser = POSHelp.Invoke(
#"add-pssnapin Quest.ActiveRoles.ADManagement
($userid) = $input | % { $_ }
get-qaduser $userid", "auserid").Single();
Debug.WriteLine(psUser.Properties["DisplayName"].Value);
add a ref to Program Files\Reference Assemblies\Microsoft\WindowsPowerShell\v1.0\System.Management.Automation.dll
See DirectorySearcher, loading the property "DisplayName".

Categories