I have the following piece of code.
It is returning different results when running on the same machine in case of web and desktop applications.
Here is my code. Please guide me on what to do regarding this???
var searcher = new ManagementObjectSearcher("SELECT * FROM Win32_PhysicalMedia");
return (from ManagementObject wmiHD in searcher.Get()
select wmiHD["SerialNumber"] == null ? "VM HD" : wmiHD["SerialNumber"].ToString()).ToList();
Here is a LINQ-free version of the same code
var hdCollection = new List<string>();
var searcher = new ManagementObjectSearcher("SELECT * FROM Win32_PhysicalMedia");
foreach (ManagementObject wmiHD in searcher.Get())
{
// get the hardware serial no.
if (wmiHD["SerialNumber"] == null)
{
hdCollection.Add("VM HD");
}
else
{
hdCollection.Add(wmiHD["SerialNumber"].ToString());
}
}
return hdCollection;
That could possibly be caused by two things:
web server runs with different user account (probably NetworkService)
http://www.bluevisionsoftware.com/WebSite/TipsAndTricksDetails.aspx?Name=AspNetAccount
web server runs code without Fulltrust permissions (probably medium trust)
http://discussion.accuwebhosting.com/iis-web-server/993-how-grant-full-trust-mode-domain-asp-net-2-0-iis-6-0-a.html
Both actions can compromise security, but the first one gives more choices to fix this by setting ACLs.
Related
I want to get all a list of all installed drivers on my machine. For this purpose I use WMI. But for unknown reason all properties returned have empty values (except for deviceID, DriverVersion and Signer) .
What I tried and considered so far:
running with and without admin rights makes no difference
no methods found like fetch, load, reload on any of involved objects found
no option found like lazyload
pnputil.exe and driversearch.exe do return data of all drivers, but the outputs of those a very hard to interpret
This is the C#-code:
using (var searcher = new ManagementObjectSearcher("SELECT * FROM Win32_PnPSignedDriver"))
{
foreach (ManagementBaseObject u in searcher.Get())
{
foreach(PropertyData prop in u.Properties)
{
System.Console.WriteLine($"{prop.Name}={prop.Value}");
}
System.Console.WriteLine("===");
}
}
Output for first driver found:
Caption=
ClassGuid=
CompatID=
CreationClassName=
Description=
DeviceClass=
DeviceID=\\SVWPSW46\P3115 X WC 7120-D C S U A3
DeviceName=
DevLoader=
DriverDate=
DriverName=
DriverProviderName=
DriverVersion=2:6.0,2:5.2,2:5.1,2:5.0
FriendlyName=
HardWareID=
InfName=
InstallDate=
IsSigned=True
Location=
Manufacturer=
Name=
PDO=
Signer=Microsoft Windows
Started=
StartMode=
Status=
SystemCreationClassName=
SystemName=
===
...
I am trying to read two setting values in Local Group policy (gpedit.msc). The path is :
Local Computer Policy\Windows Settings\Security Settings\Local Policies\User Rights Assignment
The Policy that I want to read are :
1. Perform volume maintainace tasks (Users assigned to it)
2. Lock Pages in memory (Users assigned to it).
I have searched the web (including all stackoverflow threads) and could not find a solution to this but could not get a solution to this. Below is the code I am using currently but it only returns me 7 values.
I am not sure if this is possible. Please suggest. I am using C# .NET as language and would prefer if possible be able to read these setting from a remote machine (so I am preferring WMI approach).
Also I only want to read values. Now editing or writing...
Please suggest..
Girija
Code
private void Test()
{
ManagementScope scope =
new ManagementScope(
"\\\\localhost\\root\\rsop\\Computer");
scope.Connect();
ObjectQuery query = new ObjectQuery(
"SELECT * FROM RSOP_UserPrivilegeRight");
ManagementObjectSearcher searcher =
new ManagementObjectSearcher(scope, query);
ManagementObjectCollection queryCollection = searcher.Get();
List<string> val = new List<string>();
foreach (ManagementObject mgo in queryCollection)
{
var d = mgo["Name"];
val.Add(Convert.ToString(d));
}
}
Is there a .NET (C#) method or API call that I can use to query if a Windows Service is disabled? The relevant MSDN article is here.
I want to avoid querying the registry directly. Below is some of the code that I am using right now (and it works). However I am looking for something more elegant and less invasive.
const String basepathStr = #"System\CurrentControlSet\services\";
String subKeyStr = basepathStr + servicenameStr;
using (RegistryKey key = Registry.LocalMachine.OpenSubKey(subKeyStr))
{
return (int) key.GetValue("Start");
}
I did find a simliar question but I was hoping for a better answer since the answers are presumably outdated (3 years have passed).
This the most relevant section of the code I decided to use...thanks for the help all!
StartupState state = StartupState.Unknown;
try
{
PermissionSet fullTrust = new PermissionSet(System.Security.Permissions.PermissionState.Unrestricted);
fullTrust.Demand();
string wmiQuery = #"SELECT * FROM Win32_Service WHERE Name='" + servicenameStr + #"'";
ManagementObjectSearcher searcher = new ManagementObjectSearcher(wmiQuery);
ManagementObjectCollection results = searcher.Get();
foreach (ManagementObject service in results)
{
if (service["StartMode"].ToString() == "Disabled")
state = StartupState.Disabled;
else
state = StartupState.Enabled;
}
return state;
}
catch (SecurityException se)
{
return StartupState.Refused;
}
catch (Exception e)
{
return StartupState.Error;
}
Use the ServiceController class to get information about services.
EDIT
Seems one of the things you can't do with the ServiceController is get the startup type. Googling showed the following blog post that has code that uses P/Invoke to get the service startup type: http://peterkellyonline.blogspot.de/2011/04/configuring-windows-service.html
Add a ref to System.Management and the following code will get you the StartMode
string wmiQuery = "SELECT * FROM Win32_Service WHERE Name='YourServiceName'";
var searcher = new ManagementObjectSearcher(wmiQuery);
var results = searcher.Get();
foreach (ManagementObject service in results)
{
Console.WriteLine(service["StartMode"]);
}
ServiceController class doesn't provide this information. You should use WMI. See here for detailed solution
WMI can be another way for querying the status of the windows services
You can use:
using System.ServiceProcess;
And then link the service you want to view the satus by:
// Link by service name
ServiceController TheServiceName = new ServiceController();
TheServiceName.ServiceName = "Spooler";
// Link by display name
ServiceController TheDisplayName = new ServiceController();
TheDisplayName.ServiceName = "Print Spooler";
To check for example the isRunning Status :
if (TheServiceName.Status == ServiceControllerStatus.Running)
MessageBox.Show("The service is running.");
presently I am writing a small piece of code to get the list of web services hosted on IIS in a remote system,
the working code right now is :
string q2 = "select * from Win32_PerfFormattedData_W3SVC_WebService";
ManagementScope scope2 = new ManagementScope(string.Format(#"\\dtp-robaro2\{1}", host, ns), options);
// ns here is string ns = #"root\cimv2";
scope2.Connect();
ManagementObjectSearcher search2 = new ManagementObjectSearcher(scope, new ObjectQuery(q2));
foreach (ManagementObject mo in search2.Get())
{
Console.WriteLine(mo.ClassPath);
Console.WriteLine(mo.GetText(TextFormat.Mof));
}
now I was wondering if WMI is turned off on the remote system that i am querying then is there any alternative way to access the information i get with the above code?
Use tool Service Control - SC.EXE
I have converted this from VB.Net to C# so it may not be exactly correct, but this will do what you need:
public List<string> GetSites(string MachineName)
{
List<string> siteList = new List<string>();
DirectoryEntry iis = new DirectoryEntry(string.Format("IIS://{0}/w3svc/1/root", MachineName));
foreach (DirectoryEntry site in iis.Children) {
if (site.SchemaClassName == "IIsWebServer") {
siteList.Add(site.Properties("ServerComment").Value.ToString());
}
}
return siteList;
}
I'm attempting to get the current domain controller name via c#. This code will NOT be running during a logon session. It runs during machine startup so, I can't use the %logonserver% variable because there is no such thing at machine startup. Searching here I thought the following code would work but it returns the primary domain controller, not the current logon server. (at startup the 'logon server' might be best referred to as the 'authentication server')
this doesn't work for me (doesn't return machines' current DC, returns Domain's PDC)
using (PrincipalContext context = new PrincipalContext(ContextType.Domain))
{
string controller = context.ConnectedServer;
Console.WriteLine("Domain Controller: " + controller);
}
I have found that the following WMI query gets positive results but, it's slow:
ManagementObjectSearcher searcher =
new ManagementObjectSearcher("root\CIMV2",
"SELECT * FROM Win32_NTDomain");
foreach (ManagementObject queryObj in searcher.Get())
{
if (queryObj["DomainControllerName"] != "")
Console.WriteLine("DomainControllerName: {0}", queryObj["DomainControllerName"]);
}
Anyone know a better way?
Granted you'll need to include a user and password, but this should do the trick:
DirectoryContext domainContext = new DirectoryContext(DirectoryContextType.Domain, "targetDomainName", "validUserInDomain", "validUserPassword");
var domain = System.DirectoryServices.ActiveDirectory.Domain.GetDomain(domainContext);
var controller = domain.FindDomainController();