WMI Instance update fails - c#

I'm trying to update a WMI instance using C# following one example in MSDN but I cannot get it to work. It is firing me a 'System.Management.ManagementException' which does not give me any answer. Can you please tell me if I'm doing something wrong?
public void UpdateInstance(string parametersJSON)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
object result = serializer.Deserialize(parametersJSON, typeof(object));
Dictionary<string, object> dic = (Dictionary<string, object>)result;
PutOptions options = new PutOptions();
options.Type = PutType.UpdateOnly;
ManagementObject objHostSetting = new ManagementObject();
objHostSetting.Scope = new ManagementScope("root\\onguard");
objHostSetting.Path = new ManagementPath("Lnl_Cardholder.SSNO = '33263085'"); // This is the line that fires the exception
foreach (KeyValuePair<string, object> value in dic)
{
objHostSetting[value.Key] = value.Value.ToString();
}
//update the ManagementObject
objHostSetting.Put(options);
}

I changed my code to this and now works:
public void UpdateInstance(string scope, string query, string parametersJSON)
{
WindowsImpersonationContext impersonatedUser = WindowsIdentity.GetCurrent().Impersonate();
JavaScriptSerializer serializer = new JavaScriptSerializer();
object result = serializer.Deserialize(parametersJSON, typeof(object));
Dictionary<string, object> dic = (Dictionary<string, object>)result;
ManagementObjectSearcher searcher;
searcher = new ManagementObjectSearcher(scope, query);
EnumerationOptions options = new EnumerationOptions();
options.ReturnImmediately = true;
foreach (ManagementObject m in searcher.Get())
{
foreach (KeyValuePair<string, object> k in dic)
{
m.Properties[k.Key].Value = k.Value;
}
m.Put();
}
}

Related

How to get value of a specific value of a list in C#

var ctsDB = mooe.Files66.ToList();
Dictionary<string, string> mappedfields = new Dictionary<string, string>();
Dictionary<string, string> ctsfieldsValue = new Dictionary<string, string>();
for (int i = 0; i < ctsDB.Count; i++)
{
foreach(var item in mappedfields) {
// this line returns the item.key string not the value of it.
// item.key is the column name
var rowValue = mooe.Files66.Select(k = >item.Key).ToList();
// ctsfieldsValue.Add(item.Value, rowValue);
ctsfieldsValue.ToList();
}
}
I want to iterate through ctsDB List and get the row value of a specific
column like this:
if ctsDB [i] = fileID Field612 Fiel613
and I have these column names in the value field of ctsfieldsValue.
I want to iterate on ctsDB[i] to get the value of column Field612 only.
Can anyone provide a thought?
var ctsDB = mooe.Files66.ToList();
var mappedfields = new Dictionary<string, string>(); // I assume this is not empty in your real code.
var ctsfieldsValue = new List<Dictionary<string, string>>();
foreach (var row in ctsDB)
{
var d = new Dictionary<string, string>();
foreach (var mapping in mappedfields)
{
var v = row[mapping.Key]; //throws if not found
d[mapping.Value] = v;
}
ctsfieldsValue.Add(d);
}

Adding dynamic object to json

first of all, thanks for reading. Furthermore, i need your help!
By the way, im using Newtonsoft.Json;
How can i add a string to this:
obj.namedTypes.Menu.fields.< string > = new ExpandoObject();
So i have this code at the moment:
internal class Program
{
private static void Main(string[] args)
{
Regex reg = new Regex(":addSubMenu\\((?<Description>.+),[a-z A-Z](\'|\")(?<Identifier>[a-zA-Z]+)(\'|\")\\)"); //Regular expression for finding the id and description i want.
dynamic obj = new ExpandoObject();
obj.global = new ExpandoObject();
obj.global.type = "table";
obj.global.fields = new ExpandoObject();
obj.global.fields.scriptConfig = new ExpandoObject();
obj.global.fields.scriptConfig.type = "function";
obj.global.fields.scriptConfig.args = new string[] {};
obj.global.fields.scriptConfig.description = "a simple description";
obj.global.fields.scriptConfig.returnTypes = new List<ExpandoObject>();
dynamic arguments = new ExpandoObject();
arguments.type = "ref";
arguments.name = "Menu";
obj.global.fields.scriptConfig.returnTypes.Add(arguments);
obj.namedTypes = new ExpandoObject();
obj.namedTypes.Menu = new ExpandoObject();
obj.namedTypes.Menu.type = "table";
obj.namedTypes.Menu.fields = new ExpandoObject();
Console.WriteLine(JsonConvert.SerializeObject(obj, Formatting.Indented));
MatchCollection matches = reg.Matches(File.ReadAllText("test.txt"));
string description;
string value;
foreach (Match m in matches)
{
description = m.Groups["Description"].ToString();
value = m.Groups["Identifier"].ToString();
/* I want to add the value as a object like this: ->
* obj.namedTypes.Menu.fields.<value> = new ExpandoObject();
* obj.namedTypes.Menu.fields.<value>.description = description;
*/
Console.WriteLine($"Description: {description}\nValue: {value}");
}
Console.ReadLine();
}
I want to add the value as a object like this: ->
obj.namedTypes.Menu.fields.<value> = new ExpandoObject();
obj.namedTypes.Menu.fields.<value>.description = description;
Try using Dictionary.
Your modified code would be -
//Initialization of Dictonary
obj.namedTypes.Menu.fields = new Dictionary<string,string>();
//Reading from File and iteration on matches
MatchCollection matches = reg.Matches(File.ReadAllText("test.txt"));
string description;
string value;
foreach (Match m in matches)
{
description = m.Groups["Description"].ToString();
value = m.Groups["Identifier"].ToString();
obj.namedTypes.Menu.fields.Add(description , value);
}
//End: Serialize the Whole stuff
Console.WriteLine(JsonConvert.SerializeObject(obj, Formatting.Indented));

How to search in a List by first item

Here is my list:
public static List<Tuple<string, string>> hardDiskInfo(string hostname)
{
var hardDiskInfo = new List<Tuple<string, string>>();
ManagementScope Scope;
if (!hostname.Equals("localhost", StringComparison.OrdinalIgnoreCase))
{
ConnectionOptions Conn = new ConnectionOptions();
Conn.Username = Properties.Settings.Default.uName;
Conn.Password = Properties.Settings.Default.pWord;
Conn.Authority = "ntlmdomain:" + Properties.Settings.Default.doMain;
Scope = new ManagementScope(String.Format("\\\\{0}\\root\\CIMV2", hostname), Conn);
}
else
Scope = new ManagementScope(String.Format("\\\\{0}\\root\\CIMV2", hostname), null);
Scope.Connect();
ObjectQuery query = new ObjectQuery("SELECT * FROM Win32_LogicalDisk WHERE DriveType = 3 OR DriveType = 4");
ManagementObjectSearcher searcher = new ManagementObjectSearcher(Scope, query);
ManagementObjectCollection queryCollection = searcher.Get();
foreach (ManagementObject mo in queryCollection)
{
foreach (PropertyData p in mo.Properties)
{
if (p.Value != null)
{
hardDiskInfo.Add(new Tuple<string, string>(p.Name.ToString(), p.Value.ToString()));
}
}
}
return hardDiskInfo;
}
I'd like to know how to get the second p.Value of the p.Name after calling it:
hardDiskInfo(inputText.Text);
For example the value of the "FreeSpace" which is defined in Win32_LogicalDisk.
I'm having more Win32_ queries so knowing this will help me handling all of them and I'll be a happy panda.
Thank you.
Are the Names unique?
You might try:
var values = hardDiskInfo(inputText.Text);
// Get the first or default which matches "FreeSpace".
var freeSpaceInfo = values.FirstOrDefault(item => item.Item1 == "FreeSpace");
// If it was found,
if(freeSpaceInfo != null)
{
MessageBox.Show($"FreeSpace: {freeSpaceInfo.Item2}");
}
Next step: Use a Dictionary<string, string> which is much better.

autocomplete linq on dictionary of Active Directory Users in .Net MVC5 C#

I'm trying to get my auto complete repository method (linq) to use the active directory dictionary I've just recently created, but I can't seem to get my head around it..
// My ADUsers Dictionary
public Dictionary<string, string> ADUsers()
{
List<KeyValuePair<string, string>> ADUsersList = new List<KeyValuePair<string, string>>();
using (var context = new PrincipalContext(ContextType.Domain, "creaghconcrete.com"))
{
using (var searcher = new PrincipalSearcher(new UserPrincipal(context)))
{
foreach (var result in searcher.FindAll())
{
DirectoryEntry de = result.GetUnderlyingObject() as DirectoryEntry;
string samAccName = de.Properties["samAccountName"].Value.ToString();
string realName = string.Format("{0} {1}", de.Properties["givenName"].Value, de.Properties["sn"].Value);
ADUsersList.Insert(0, new KeyValuePair<string, string>(samAccName, realName));
}
}
}
var dictionary = ADUsersList.ToDictionary((keyItem) => keyItem.Key, (valueItem) => valueItem.Value);
return dictionary;
}
// My GetAutoADUsers method
public List<Schema.Models.ADUser> GetAutoADUsers(string query)
{
IQueryable<Schema.Models.ADUser> result = ADUsers().Where(x => x.Key != null && x.Value != null);
if (string.IsNullOrEmpty(query)) return result.OrderBy(u => u.RealName).ToList();
string q = query.ToLower();
return result.Where(u => u.RealName.ToLower().Contains(q)
|| u.ADName.ToLower().Contains(q)
).OrderBy(u => u.RealName).ToList();
}

Confused about how get value from DictionaryList at specific index

I am using a DictionaryList to keep some values coming from an xml file
this is the my xml file
<DnsServers>
<Dns>
<Name>Google</Name>
<Value>8.8.8.8,8.8.4.4</Value>
</Dns>
<Dns>
<Name>Telekom</Name>
<Value>195.175.39.39,195.175.39.40</Value>
</Dns>
</DnsServers>
and then populating a combobax just key values like this way .
void ReadFromDnsServerList()
{
_nameValueDictionary = new Dictionary<string, string>();
//var list = new List<string>();
XDocument doc = XDocument.Load("DnsServerList.xml");
if (doc.Root != null)
{
var keyValueXml = from c in doc.Root.Descendants("Dns")
select new
{
name = c.Element("Name").Value,
value = c.Element("Value").Value
};
foreach (var info in keyValueXml)
{
_nameValueDictionary.Add(info.name,info.value);
}
foreach (KeyValuePair<string, string> item in _nameValueDictionary)
{
cmbDns.Items.Add(item.Key);
}
}
}
I am wondering that How can I get corresponding dns value inside cmbDns_SelectedIndexChanged
change event somethinglike this
name=Google value =8.8.8.8,8.8.4.4
Try this:
void ReadFromDnsServerList()
{
_nameValueDictionary = new Dictionary<string, string>();
XDocument doc = XDocument.Load("DnsServerList.xml");
if (doc.Root != null)
{
var keyValueXml = from c in doc.Root.Descendants("Dns")
select new
{
name = c.Element("Name").Value,
value = c.Element("Value").Value
};
foreach (var info in keyValueXml)
{
_nameValueDictionary.Add(info.name, info.value);
}
cmbDns.DisplayMember = "Key";
cmbDns.ValueMember = "Value";
cmbDns.DataSource = _nameValueDictionary.ToArray();
}
}
I hope it helps.

Categories

Resources