WMI Access Denied Problem on 2003 Server - c#

I´m having a problem whenever i try to use WMI services on a virtual pc running a 2003 Server.
The error message that i get is 'Access Denied'. I have already checked the permissions of the user over the COM components. The curious thing is that i´m running both WMI service and my app as Administrator user, so i don´t think i have trouble with permissions.
Can Anyone help me??
Thanks you very much.
The problem is on this block:
ManagementEventWatcher watcher;
try
{
numeros = devolverRandomicos();
string nros = "";
foreach (int num in numeros)
{
nros = nros + " " + num.ToString();
}
MessageBox.Show(nros);
watcher = new ManagementEventWatcher("root\\OnGuard", dataQry);
watcher.EventArrived += WMIEventArrieved;
watcher.Start();
}
catch (Exception e)
{
MessageBox.Show("ERROR CREANDO EL WATCHER: \n" + e.Message,"CatchToyota",MessageBoxButtons.OK,MessageBoxIcon.Error);
}

The problem at last was in the Domain Users I was using to log in. After getting the machine out of the domain, all started to work just fine.
I guess it was a problem with permissions on domain users.

Related

WPF: unable to map network drive for all users

I'm trying to create a function for an application to automatically copy over specific files during the final stage of a job. The only issue here is that the copy location is a protected share drive and uses a separate login instead of being validated by the active directory so I've got to do a bit of a workaround to get File.Copy() working. My workaround has been to call the built in net.exe utility and passing a command line argument that points to the share drive to open up a connection to the drive then using File.Copy() to get the file where it needs to go then deleting the connection. The issue at hand is that this works great on my computer but when anyone else on the team runs the same program a "Logon failure: unknown user name or bad password" is thrown. I'm at a bit of loss as to why this would happen since the username and password are static and not being changed and everyone on the team has the same network permissions I do. Here is the WPF/C# code I'm using to do this:
try
{
string mrdfDropPath = #"dropPathHere";
string MRDFPath = #"storePath\test.xml";
string command = #"use " + mrdfDropPath + #" /user:CORP\Username Password";
Process.Start("net.exe", command);
File.Copy(MRDFPath, mrdfDropPath + "test.xml");
string command2 = #"use " + mrdfDropPath + #" /delete";
Process.Start("net.exe", command2);
StreamWriter writer = new StreamWriter(#"logPath\log.txt", true);
writer.WriteLine(mrdfDropPath + "test.xml" + "," + File.GetLastWriteTime(MRDFPath).ToString());
writer.Close();
}
catch (Exception e)
{
StreamWriter writer = new StreamWriter(#"logPath\log.txt", true);
writer.WriteLine(e.Message);
writer.Close();
}
Like I said this works as expected during debug and when I run the application, but for anyone else it is throwing the error.

is this the correct way to use WMI?

I am trying to build a tool on the server which will open the browser on the client. note that the server and the client are in the same domain in our company.
everything works good, but when i try this to open the browswer on the client machine
string theProcessToRun = popupURL + "?CallerID=" + callerID;
string remoteIdentifier = string.Format(#"\\{0}\root\cimv2:Win32_Process", ipAddress);
ManagementClass mc = new ManagementClass(remoteIdentifier);
mc.InvokeMethod("Create", new[] { theProcessToRun });
as you see, i am using #"\\{0}\root\cimv2:Win32_Process", ipAddress, which ** I don't** know if it is the correct way because i am using windows client so i don't know what is this root has to do here
i am having this exception
Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))
on this line
mc.InvokeMethod("Create", new[] { theProcessToRun });
may you help please

How to determine if the "Active Directory Domain Services" role has been installed on a server

I am trying to figure out if the Active Directory Domain Services are installed a windows server.
I know they show up in the Server Manager, but can I programmatically get if the role is installed on a server using C# code
If you know the name of the server you want to test and can run the program with domain admin privileges remotely, you can use WMI:
internal static bool IsDomainController(string ServerName)
{
StringBuilder Results = new StringBuilder();
try
{
ManagementObjectSearcher searcher =
new ManagementObjectSearcher("\\\\" + ServerName + "\\root\\CIMV2",
"SELECT * FROM Win32_ServerFeature WHERE ID = 10");
foreach (ManagementObject queryObj in searcher.Get())
{
Results.AppendLine(queryObj.GetPropertyValue("ID").ToString());
}
}
catch (ManagementException)
{
//handle exception
}
if (Results.Length > 0)
return true;
else
return false;
}
If you're running that locally on the server, the WMI path changes to:
ManagementObjectSearcher searcher =
new ManagementObjectSearcher("root\\CIMV2",
"SELECT * FROM Win32_ServerFeature WHERE ID = 10");
See the MSDN reference on Win32_ServerFeature for a full list of roles and their ID numbers.
If your question is to see if a server is a domain controller, you can enumerate the domain controllers in the domain and check the hostname of the server you are sitting on to see if it matches any of them. To get the list of domain controllers:
var domainControllers = new List<string>();
var domain = Domain.GetCurrentDomain();
foreach (var dc in domain.DomainControllers)
{
domainControllers.Add(dc.Name);
}
string whoami = Dns.GetHostname();
Make sure to add requisite error handling (like if you run this on a workgroup computer, it will die).
EDIT:
Alternate ways of detecting DCPROMO (because it's possible to install Domain Services without DCPROMO, and that is a bad thing):
1) Parse out (and check for the existence of) the debug log that is created when DCPROMO does its thing. Should be located at c:\windows\debug\dcpromo.log
2) This DSQUERY command is FAST and will give you all the servers where DCPROMO was ran:
dsquery * "cn=Sites,cn=Configuration,dc=MyDomain,dc=com" -Filter "(cn=NTDS Settings)" -attr distinguishedName whenCreated
Problem is getting that from command line output if you started it using Process. Working on a way to do this and will update once I have it tested, as I haven't done AD filtering in a query for a while.

Errors scheduling a C# console app that sends faxes via FAXCOMEXLib

I have a console app written in C# that uses MS Fax (FAXCOMEXLib) to send faxes. If I run the application manually or from a command prompt it works as expected. If I schedule the application with Task Scheduler or try to run from a service with a timer, it fails when calling the ConnectedSubmit2 on the FaxDocument object. The application runs as expected, gets the data, creates the pdf, connects to Fax Service, fills the FaxDocument properties, but bombs on ConnectedSubmit2. It feels like a security issue. The windows account the TaskScheduler runs under belongs to the administrator group.
This same application has worked on another Server 2008 (not R2) computer without issue with Task Scheduler.
The server in question is running Microsoft Server 2008 R2.
Recap: The application will work if run manually, fails if run from another process like Task Scheduler.
Any suggestions would be most appreciated. Thank you.
C# Code:
FAXCOMEXLib.FaxServer faxServer = new FAXCOMEXLib.FaxServer();
FAXCOMEXLib.FaxDocument faxDocument = new FAXCOMEXLib.FaxDocument();
ArrayList al = new ArrayList();
al.Add(orderPdfFilePath);
if (facesheetPdfFilePath != "")
al.Add(facesheetPdfFilePath);
if (write) Console.WriteLine("Preparing to Connect to Fax Server...");
sbLog.Append("Preparing to Connect to Fax Server...\r\n");
faxServer.Connect("");
if (write) Console.WriteLine("Connected.");
sbLog.Append("Connected.\r\n");
// Add Sender Information to outgoing fax
faxDocument.Sender.Name = dr2["FacilityName"].ToString();
faxDocument.Sender.Department = dr2["TSID"].ToString();
faxDocument.Sender.TSID = Truncate(dr2["TSID"].ToString(), 20);
faxDocument.Recipients.Add(dr2["FaxNumber"].ToString(), dr2["Pharmacy"].ToString());
faxDocument.Bodies = al.ToArray(typeof(string));
faxDocument.Subject = order;
if (write) Console.WriteLine("Attempting submit to fax server...");
sbLog.Append("Attempting submit to fax server...\r\n");
// attempt send...
try
{
object o;
faxDocument.ConnectedSubmit2(faxServer, out o);
if (write) Console.WriteLine("Fax sent successfully " + DateTime.Now.ToString());
sbLog.Append("Fax sent successfully " + DateTime.Now.ToString() + ".\r\n");
}
catch (Exception ex)
{
if (write) Console.WriteLine("SEND FAILED! " + order + " " + DateTime.Now.ToString() + " " + ex.Message);
sbLog.Append("SEND FAILED! " + order + " " + DateTime.Now.ToString() + ".\r\n" + ex.Message + "\r\n" + ex.InnerException + "\r\n");
error = true;
}
Errors in Event Log:
System.Runtime.InteropServices.COMException (0x80070102): Operation failed.
at FAXCOMEXLib.FaxDocumentClass.ConnectedSubmit2(IFaxServer pFaxServer, Object& pvFaxOutgoingJobIDs)
System.UnauthorizedAccessException: Access denied. at FAXCOMEXLib.FaxDocumentClass.ConnectedSubmit2(IFaxServer pFaxServer, Object& pvFaxOutgoingJobIDs) at ElementsTransmission.Program.Main(String[] args)
See
http://blogs.msdn.com/b/dougste/archive/2011/08/30/system-runtime-interopservices-comexception-0x80070102-operation-failed-trying-to-send-a-fax-from-and-asp-net-application.aspx
Bill

C# IIS 7.5 class not registered exception

We just started up a new webserver and i'm running into "class not registered" when creating a new application pool. I'm using the code below but I have no idea how to distinguish what is not registered. Any thoughts would be awesome.
Thanks.
string path = "IIS://" + server + "/W3SVC";
string app_pools_path = path + "/AppPools";
/error below.
var app_pools = new DirectoryEntry(app_pools_path);
foreach (DirectoryEntry app_pool in app_pools.Children)
{
//do work
}
Error "Class no registered" error code:2147221164
ON the server open the server manager
add new features ==> Web Server (IIS) ==> Management Tools ==> IIS 6 Management Compatibility then check IIS6 Metabase Compatibility. use your original connection string / path
string path = "IIS://" + server + "/W3SVC";
string app_pools_path = path + "/AppPools";
try this please :
private void StopAppPool(string app_Pool , string server)
{
try
{
ConnectionOptions co = new ConnectionOptions();
co.Username = "DomainName\\UserName";
co.Password = "UserPassword";
string appPool = "W3SVC/AppPools/" + app_Pool;
co.Impersonation = ImpersonationLevel.Impersonate;
co.Authentication = AuthenticationLevel.PacketPrivacy;
string objPath = "IISApplicationPool.Name='" + appPool + "'";
ManagementScope scope = new ManagementScope(#"\\" + server + #"\root\MicrosoftIISv2", co);
using (ManagementObject mc = new ManagementObject(objPath))
{
mc.Scope = scope;
mc.InvokeMethod("Stop", null, null);
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
Console.WriteLine(e.StackTrace);
Console.WriteLine(e.InnerException);
Console.WriteLine(e.Data);
}
//Console.ReadLine();
}
You should avoid using DirectoryEntry to manipulate IIS 7 and above. That's the old API based on IIS ADSI interfaces,
http://msdn.microsoft.com/en-us/library/ms524896(v=vs.90).aspx
IIS 6 Compatibilities might help you out though,
http://blogs.msdn.com/b/narahari/archive/2009/05/13/when-using-directoryservices-to-access-iis-schema-iis6-management-compatibility-pack-needs-to-be-installed-system-runtime-interopservices-comexception-0x80005000.aspx
The best solution (which is also strong typed and more convenient for C# developers) is Microsoft.Web.Administration,
http://www.iis.net/learn/manage/scripting/how-to-use-microsoftwebadministration

Categories

Resources