Attempting to pull the automatic update settings from the registry of a remote server. For some reason, it's returning a 0 even though a manual check of the key is 1-4. What am I overlooking? Snippet below:
ManagementScope msAutoUpdateReg = new ManagementScope(#"\\" + remoteServer + #"\root\DEFAULT:StdRegProv", connection);
msAutoUpdateReg.Connect();
ManagementClass ci = new ManagementClass(msAutoUpdateReg, new ManagementPath(#"DEFAULT:StdRegProv"), new ObjectGetOptions());
ManagementBaseObject inParams = ci.GetMethodParameters("GetDWORDValue");
inParams["hDefKey"] = 0x80000002; //HKLM
inParams["sSubKeyName"] = #"Software\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update";
inParams["sValueName"] = "AUOptions";
ManagementBaseObject outParams = ci.InvokeMethod("GetDWORDValue", inParams, null);
UInt32 auValue = (UInt32)outParams["uValue"];
if (auValue.ToString() != "0")
{
if (auValue == 1)
{
string currentSetting = "Keep my computer up to date has been disabled in Automatic Updates.";
}
if (auValue == 2)
{
string currentSetting = "Notify of download and installation.";
}
if (auValue == 3)
{
string currentSetting = "Automatically download and notify of installation.";
}
if (auValue == 4)
{
string currentSetting = "Automatically download and scheduled installation.";
}
}
else
{
string currentSetting = "Unknown";
}
I guess a process of elimination might help here...
1) Is this happening on just one server or are you getting this on all servers? How about on your own local machine? Is it a Windows version thing? For example it seems my Windows 10 box doesn't show the SubKey name you are looking for.
2) Do you also get zero if you change the sValueName to "foo"? Is a value of 0 representing an error?
3) Can you put a watch on outParams and check to see what values have been returned?
4) Are you being blocked by UAC, firewall or other permission issues? Can you execute other WMI commands against this server without any problems? Do you need to Run As Administrator to get this to work?
5) Are you getting an other exceptions or return values? I'm guessing you've posted just a portion of the code here so is this code inside a try/catch block?
Sorry if this sounds either vague or simplistic but I think you may need to look at what does work and what doesn't to see if you can identify a pattern.
Related
I started using CodeFluentRuntimeClient to replace Interop.MSScriptControl.dll.
I succeed here by tweeking a bit the dll to make it work.
We started using the dll in production. On one of the machines that we installed on it (windows server 2012), we are having a Sytem.AccessViolationException.
Here's the stack trace of the event viewer:
Do CodeFluent requieres any other dlls?
EDIT
Here's the code:
public dynamic EvaluateVBScript(string token, string key, string script, IDictionary<string, object> parameterValuePair = null)
{
try
{
using (ScriptEngine engine = new ScriptEngine(ScriptEngine.VBScriptLanguage))
{
List<object> parameters = new List<object>() { string.IsNullOrEmpty(token) ? string.Empty : ServiceManager.GetService<IServiceInstance>().GetService<IContextManager>(token).UserName };
string extraParameters = string.Empty;
if (parameterValuePair != null && parameterValuePair.Count > 0)
{
extraParameters = "," + string.Join(",", parameterValuePair.Select(e => e.Key));
foreach (var para in parameterValuePair)
parameters.Add(para.Value);
}
string parsedScript = string.Format(#"Function {0}(NecUserProfile {2})
{1}
End Function", key, script, extraParameters);
ParsedScript parsed = engine.Parse(parsedScript);
dynamic value = parsed.CallMethod(key, parameters.ToArray());
return (value != null) ? value.ToString() : string.Empty;
}
}
catch
{
throw;
}
}
After some tests, we found out that the client had an antivirus (Kaspersky) installed on his server. Even after disabling the antivirus, the access violation error was still occurring.
After uninstalling the antivirus, we were finally able to execute the JavaScript. We still don't know what rule was set in the antivirus that was blocking the script to be parsed.
I didn't test in the suggested solution by Simon Mounier. I don't know if it would have solved the problem.
The solution was to drop out the CodeFluent.Runtime.Client.dll and use directly the source code provided here. Also add MarshalAs(UnmanagedType.LPWStr)] around the string parameters that are going to be used by the parse function, like in here.
I am detecting whether or not I'm attempting a connection against localhost, and creating (or not) the WMI connection options as follows:
if (NetworkUtils.IsLocalIpAddress(machineName))
{
_scope = new ManagementScope(string.Format(#"\\{0}\root\cimv2", machineName));
}
else
{
_connectionOptions = new ConnectionOptions
{
Username = username,
Password = password,
Impersonation = ImpersonationLevel.Impersonate
};
_scope = new ManagementScope(string.Format(#"\\{0}\root\cimv2", machineName), _connectionOptions);
}
When I call _scope.Connect() in either case, it works. That is, no exception and IsConnected is true.
However, when I attempt to invoke a method in the local case, such as Win32_Share.Create I get errors. The following code always works for remote connections for me:
var winSharePath = new ManagementPath("Win32_Share");
var winShareClass = new ManagementClass(_scope, winSharePath, null);
var shareParams = winShareClass.GetMethodParameters("Create");
shareParams["Path"] = pathName.TrimEnd('\\');
shareParams["Name"] = shareName;
shareParams["Type"] = 0;
shareParams["Description"] = "CMC Bootstrap Share";
var outParams = winShareClass.InvokeMethod("Create", shareParams, null);
if ((uint) (outParams.Properties["ReturnValue"].Value) != 0)
{
throw new Exception("Unable to share directory. Error code: " +
outParams.Properties["ReturnValue"].Value);
}
I create the pathName directory just prior to invoking this method, so I guarantee pathName exists in all cases.
When executing locally ONLY on Windows Server 2008 & 2012, the above code throws the exception with error code 24. Executing against localhost on Windows 8 works just fine.
What is the correct way to specify "blank credentials" when invoking WMI methods against localhost, as I believe this is the underlying issue?
I tried the code below on my local PC and this works (shares my temp folder). Could you try the same please? Also, which is the patch & share name you're using?
string pathName = #"c:\temp\";
string shareName = "tempFolder";
var scope = new ManagementScope(string.Format(#"\\{0}\root\cimv2", "localhost"));
// your code below
var winSharePath = new ManagementPath("Win32_Share");
var winShareClass = new ManagementClass(scope, winSharePath, null);
var shareParams = winShareClass.GetMethodParameters("Create");
shareParams["Path"] = pathName.TrimEnd('\\');
shareParams["Name"] = shareName;
shareParams["Type"] = 0;
shareParams["Description"] = "CMC Bootstrap Share";
var outParams = winShareClass.InvokeMethod("Create", shareParams, null);
if ((uint)(outParams.Properties["ReturnValue"].Value) != 0)
{
throw new Exception("Unable to share directory. Error code: " +
outParams.Properties["ReturnValue"].Value);
}
the above code throws the exception with error code 24
That doesn't have anything to do with the error you mention in the title of your question. Error codes for Win32_Share.Create method are documented in this MSDN article. Return value 24 means "Unknown Device or Directory".
In other words, your pathName variable is wrong.
I need to share a folder programmatically in VS2010 using C# on a machine running windows8. there were many solutions on the net out of which i used the one described used Managementclass. It didnt work on my machine. I think for windows 8 the process might be little bit different. I'm trying to figure out whats the problem in my code, till then if I cud get some help, much time will be saved. The code returns an access denied error. Please Help!!!
This is the code I'm using:
ManagementClass managementClass = new ManagementClass("Win32_Share");
ManagementBaseObject inParams = managementClass.GetMethodParameters("Create");
ManagementBaseObject outParams;
inParams["Description"] = "Dump";
inParams["Name"] = "Dump";
inParams["Path"] = "D:\\Dump";
inParams["Type"] = 0x0; // Disk Drive
DirectoryInfo d = new DirectoryInfo("D:\\Dump");
if (d.Exists)
{
}
outParams = managementClass.InvokeMethod("Create", inParams, null);
// Check to see if the method invocation was successful
if ((uint)(outParams.Properties["ReturnValue"].Value) != 0)
{
throw new Exception("Unable to share directory.");
}
}
I have an Outlook add-in that is working successfully for about 100 users. It interacts with our application and creates/updates Tasks and Appointment items. However, one client cannot get it to work for anyone who is not a network administrator. Through some logging, I can see that it works fine until it gets to the part where it should save the Task, and then it throws the infamous "The operation failed." error. I have tried in vain to get more error details by investigating inner exceptions and such, but "The operation failed." is all I can seem to get out of it.
To make it simpler to debug, I eliminated our application from the picture and wrote them a test add-in that just creates 9 tasks (hard-coded to "Task 1", "Task 2", etc.) and it fails in the same place with the same error. I have asked them to write a macro to see if a macro is able to create tasks for these users. I am awaiting their reply on that.
Anyway, I have been on MSDN for over a month trying to get help on the issue and nobody has been able to help. I am hoping someone here could shed some light. If you can provide any insight on what might be happening or suggestions to help me track down the problem, it would be greatly appreciated!
This is the function I am using to create the sample tasks in the test add-in:
private void CreateTasks()
{
int i = 1;
Outlook.TaskItem t = null;
Outlook.UserProperties ups = null;
Outlook.UserProperty up = null;
string name = string.Empty;
while (i < 10)
{
name = string.Format("Task {0}", i.ToString());
t = Application.CreateItem(Outlook.OlItemType.olTaskItem);
t.Subject = name;
t.Status = Outlook.OlTaskStatus.olTaskNotStarted;
t.Body = string.Format("Task {0} description", i.ToString());
t.Categories = "Test Task";
t.Importance = Outlook.OlImportance.olImportanceNormal;
t.ActualWork = 0;
t.TotalWork = 5 * 60;
//mimic dates that might come in main add-in
DateTime st = Convert.ToDateTime("12/10/2013");
st = st.AddDays(i);
t.StartDate = st;
DateTime end = Convert.ToDateTime("01/02/2014");
end = end.AddDays(i);
string EP = end.ToShortDateString() + " 5:00:00 PM";
end = Convert.ToDateTime(EP);
t.DueDate = end;
//mimic how we keep track of our items in the main add-in
ups = t.UserProperties;
up = ups.Find("ID");
if (up == null)
{
up = ups.Add("ID", Outlook.OlUserPropertyType.olText);
}
up.Value = string.Format("ID {0}", i.ToString());
//This is where the "The Operation Failed." error occurs on every single task.
try
{
((Outlook._TaskItem)t).Save();
}
catch (Exception ex)
{
//logs message to file
}
//Release objects
if (up != null) Marshal.ReleaseComObject(up);
if (t != null) Marshal.ReleaseComObject(t);
i++;
}
GC.Collect();
}
According to MSDN:
Saves the Microsoft Outlook item to the current folder or,
if this is a new item, to the Outlook default folder for the item type.
Does the "non administrator user" have access to this folder?
I'd hedge a bet it is something to do with Access permissions. This would be the first place to start.
Is this in an Exchange mailbox? I've seen this error before when connection to the server becomes spotty. If it is, see if the error occurs if you switch from cached mode to online mode. I don't think it's a code issue.
I have an application, that needs to get the last shutdown time. I have used EventLog class to get the shutdown time. I have separate class file that is designed to read/write event log. ReadPowerOffEvent function is intended to get the power off event.
public void ReadPowerOffEvent()
{
EventLog eventLog = new EventLog();
eventLog.Log = logName;
eventLog.MachineName = machineName;
if (eventLog.Entries.Count > 0)
{
for (int i = eventLog.Entries.Count - 1; i >= 0; i--)
{
EventLogEntry currentEntry = eventLog.Entries[i];
if (currentEntry.InstanceId == 1074 && currentEntry.Source=="USER32")
{
this.timeGenerated = currentEntry.TimeGenerated;
this.message = currentEntry.Message;
}
}
}
}
But whenever it tries to get the event entry count, it throws an IOException saying "The Network Path Not found". I tried to resolve, but I failed. Please help me out...
I think you sent wrong Log name, this worked for me
EventLog myLog = new EventLog();
myLog.Log = "System";
myLog.Source = "User32";
var lastEntry = myLog;
EventLogEntry sw;
for (var i = myLog.Entries.Count -1 ; i >=0; i--)
{
if (lastEntry.Entries[i].InstanceId == 1074)
sw = lastEntry.Entries[i];
break;
}
}
You have to have the "Remote Registry" service running on your machine (or the machine you want to run this app on). I suspect that this service in set to manual start on your machine. You may have to change the setting on this service to automatic.
If this app is going to be running on other machines, you may want to put some logic into your app to check to make sure this service is running first. If it isn't then you will need to start it up through your app.
Note:
The "Remote Registry" service enables remote users to modify registry setting on your computer. By default, the "Startup type" setting for the "Remote Registry" service may be set to "Automatic" or "Manual" which is a security risk for a single user (or) notebook PC user.
So, to make sure that only users on your computer can modify the system registry disable this "Remote Registry" service.