I found the solution of getting a list of installed programs from here. Get installed applications in a system
but not getting all installed programs, missing some programs in the list. How can I get all program list without skip
here is my code..
try
{
object line;
string softwareinstallpath = string.Empty;
string registry_key = #"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall";
using (var baseKey =RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64))
{
using (var key = baseKey.OpenSubKey(registry_key))
{
foreach (string subkey_name in key.GetSubKeyNames())
{
using (var subKey = key.OpenSubKey(subkey_name))
{
line = subKey.GetValue("DisplayName");
if (line != null)
{
listBox1.Items.Add(line);
if (line != null && (line.ToString().ToUpper().Contains("SKYPE")))
{
MessageBox.Show("SKYPE");
}
if (line != null && (line.ToString().ToUpper().Contains("QBFC")))
{
softwareinstallpath = subKey.GetValue("InstallLocation").ToString();
listBox1.Items.Add(subKey.GetValue("InstallLocation"));
break;
}
}
}
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message + Environment.NewLine + ex.StackTrace);
}
Related
Operating system patch
i want to get list of install patch of my operation system with version details in dot net,
i am trying using wmi
string Software = null;
string SoftwareKey = #"SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall";
Software += "\r\nWINDOWS X64 Software\r\n\r\n\r\n ";
using (RegistryKey rk = Registry.LocalMachine.OpenSubKey(SoftwareKey))
{
if (rk == null)
{
return Software;
}
foreach (string skName in rk.GetSubKeyNames())
{
using (RegistryKey sk = rk.OpenSubKey(skName))
{
try
{
if (!(sk.GetValue("DisplayName") == null))
{
if (sk.GetValue("InstallLocation") == null)
Software += sk.GetValue("DisplayName") + " - Install path not known \r\n ";
else
Software += sk.GetValue("DisplayName") + " - " + sk.GetValue("InstallLocation") + "\r\n ";
}
}
catch (Exception ex)
{
}
}
}
}
return Software;
I have a small Console app where I search for keywords in a large group of .cs files. I now want to follow the inheritance of a subfile to its parent root file. So far I have completed this by using a very noobish method that I don't like.
I think Reflection will be perfect but then I struggle to figure out how to use Reflection on an external file.
Can someone advise me on how I can achieve this?
EDIT:
static string GetParent(string location, string word)
{
string[] file = location.Split(new[] { "\\" }, StringSplitOptions.None);
try
{
using (StreamReader test = new StreamReader(location))
{
while ((line = test.ReadLine()) != null)
{
if (word == "ControlEventStates" && line.Contains(file.Last().ToString().Replace(".cs", "")))
{
string[] a = line.Split(new[] { " ", "(", ")", ";", ".", ",", "<", ">" }, StringSplitOptions.None);
for (int p = 0; p < a.Length; p++)
{
if (a[p] == ":" && a[p + 1] != "FunctionBase")
{
recValue = a[p + 1] + ".cs";
foreach (var item in Frontendfiles)
{
//newlocation = item;
string loc = Path.GetFileName(item);
if (loc == recValue)
{
GetParent(item, word);
}
else if (loc != recValue)
{
FindLine(item, a[p + 1] + " : ");
}
}
}
}
if (location != "" && location != null)
{
//LinesList = FindLine(newlocation, word);
return line;
}
}
}
}
return "";
}
catch (Exception ex)
{
throw ex;
}
}
So as I said this is terrible coding for what I want to accomplish. Basically I search for the line containing the current class name then filtering out the strings to find where the parent file is. Then I use the parent file name to search for its directory and then start the process over again.
I need to generate UUID for my Machine Mac address. Also i want extract the mac address from UUID.
I know we can use below two methods for encoding and decoding. But it will generate the encrypted string only not UUID.
Encode:
System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(plainTextBytes));
Decode:
System.Text.Encoding.UTF8.GetString(System.Convert.FromBase64String(base64EncodedData));
But for my requirement i want to generate(encode) the UUID and extract(decode) the mac address . How to do this in C# code?
You can get the MAC address using the following code.
From our tests it will return null on about 1.3% of machines (probably some form of virtual machine or something very locked down).
MAC Address of first IP enabled device
public static string GetMACAddress()
{
try
{
using (ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration"))
{
using (ManagementObjectCollection moc = mc.GetInstances())
{
if (moc != null)
{
foreach (ManagementObject mo in moc)
{
try
{
Trace.WriteLine(mo["Index"] + " Mac " + mo["Caption"] + " : " + mo["MacAddress"] + " Enabled " + (bool)mo["IPEnabled"]);
if (mo["MacAddress"] != null && mo["IPEnabled"] != null && (bool)mo["IPEnabled"] == true)
{
return mo["MacAddress"].ToString();
}
}
finally
{
mo.Dispose();
}
}
}
}
}
}
catch (Exception ex)
{
Trace.TraceWarning("Failed to read DiskID\r\n" + ex.Message);
}
return null;
}
This question already has answers here:
How to uniquely identify computer using C#?
(5 answers)
Closed 6 years ago.
I am working on a software lock using C#. I need to generate a unique number for every computer.
I have researched and decided to use the CPU number and hard drive number as a unique number for every computer.
My Code :
private string UniqID()
{
////////////////CpuID
string cpuInfo = string.Empty;
ManagementClass mc = new ManagementClass("win32_processor");
ManagementObjectCollection moc = mc.GetInstances();
foreach (ManagementObject mo in moc)
{
cpuInfo = mo.Properties["processorID"].Value.ToString();
break;
}
////////////////HDD ID
string drive = "C";
ManagementObject dsk = new ManagementObject(
#"win32_logicaldisk.deviceid=""" + drive + #":""");
dsk.Get();
string volumeSerial = dsk["VolumeSerialNumber"].ToString();
return volumeSerial + cpuInfo;
}
That works, but there is a problem!
When a user re-installs Windows (OS) and wants to run my software, the unique number has been changed.
Why does the unique number change when Windows is installed again? Do the CPU number and HDD number depend on the current windows installation?
You realistically have MotherboardID, CPUID, Disk Serial and MAC address, from experience none of them are 100%.
Our stats show
Disk serial Is missing 0.1 %
MAC Is missing 1.3 %
Motherboard ID Is missing 30 %
CPUID Is missing 99 %
0.04% of machines tested they yielded no information, we couldn't even read the computer name. It maybe that these were some kind over virtual PC, HyperV or VMWare instance?
Disk serial is the most reliable, but easy to change, mac can be changed and depending on the filtering applied can change if device drivers are added (hyperv, wireshark etc).
Motherboard and CPUID sometimes return values that are placeholders "NONE" etc.
You should also note that these functions can be very slow to call (they may take a few seconds even on a fast PC), so it may be worth kicking them off on a background thread as early as possible, you ideally don't want to be blocking on them.
Motherboard ID
private static void FetchMotherboardIdInternal()
{
try
{
ManagementScope scope = new ManagementScope("\\\\" + Environment.MachineName + "\\root\\cimv2");
scope.Connect();
using (ManagementObject wmiClass = new ManagementObject(scope, new ManagementPath("Win32_BaseBoard.Tag=\"Base Board\""), new ObjectGetOptions()))
{
object motherboardIDObj = wmiClass["SerialNumber"];
if (motherboardIDObj != null)
{
string motherboardID = motherboardIDObj.ToString().Trim();
Trace.WriteLine("MotherboardID = " + motherboardID);
if (IsValidMotherBoardID(motherboardID))
{
_motherboardID = motherboardID;
}
}
}
}
catch (System.Threading.ThreadAbortException)
{
throw;
}
catch (Exception ex)
{
Trace.TraceWarning("Failed to read MotherbaordID\r\n" + ex.Message);
}
}
public static bool IsValidMotherBoardID(string value)
{
if (value == null)
return false;
string motherboardID = value.Trim();
return !( motherboardID.Replace(".", "").Replace(" ", "").Replace("\t", "").Trim().Length < 5 ||
motherboardID.ToUpper().Contains("BASE") ||
motherboardID.Contains("2345") ||
motherboardID.ToUpper().StartsWith("TO BE") ||
motherboardID.ToUpper().StartsWith("NONE") ||
motherboardID.ToUpper().StartsWith("N/A") ||
motherboardID.ToUpper().Contains("SERIAL") ||
motherboardID.ToUpper().Contains("OEM") ||
motherboardID.ToUpper().Contains("AAAAA") ||
motherboardID.ToUpper().Contains("ABCDE") ||
motherboardID.ToUpper().Contains("XXXXX") ||
motherboardID.ToUpper().Contains("NOT") ||
motherboardID.ToUpper().StartsWith("00000")
);
}
CPU ID
private static void FetchCpuIdInternal()
{
try
{
using (ManagementClass mc = new ManagementClass("Win32_Processor"))
{
using (ManagementObjectCollection moc = mc.GetInstances())
{
foreach (ManagementObject mo in moc)
{
if (mo.Properties["UniqueId"] != null && mo.Properties["UniqueId"].Value != null)
{
// only return cpuInfo from first CPU
Trace.WriteLine("CPU ID = " + mo.Properties["UniqueId"].Value.ToString());
_cpuID = mo.Properties["UniqueId"].Value.ToString();
}
mo.Dispose();
}
}
}
}
catch (System.Threading.ThreadAbortException)
{
throw;
}
catch (Exception ex)
{
Trace.TraceWarning("Failed to read CPUID\r\n" + ex.Message);
}
}
MAC Adress of first card
private static void FecthMACAddressInternal()
{
try
{
using (ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration"))
{
using (ManagementObjectCollection moc = mc.GetInstances())
{
if (moc != null)
{
foreach (ManagementObject mo in moc)
{
Trace.WriteLine(mo["Index"] + " Mac " + mo["Caption"] + " : " + mo["MacAddress"] + " Enabled " + (bool)mo["IPEnabled"]);
if (string.IsNullOrEmpty(_macAdderss)) // only return MAC Address from first card
{
if ( mo["MacAddress"] != null && mo["IPEnabled"] != null && (bool)mo["IPEnabled"] == true)
{
_macAdderss = mo["MacAddress"].ToString();
}
}
mo.Dispose();
}
}
}
}
}
catch (System.Threading.ThreadAbortException)
{
throw;
}
catch (Exception ex)
{
Trace.TraceWarning("Failed to read DiskID\r\n" + ex.Message);
}
if (_macAdderss != null)
_macAdderss = _macAdderss.Replace(":", "");
}
Drive Serial Number
/// <summary>
/// return Volume Serial Number from hard drive
/// </summary>
/// <param name="strDriveLetter">[optional] Drive letter</param>
/// <returns>[string] VolumeSerialNumber</returns>
public static string GetVolumeSerial(char driveLetter)
{
try
{
using (ManagementObject disk = new ManagementObject("win32_logicaldisk.deviceid=\"" + driveLetter + ":\""))
{
if (disk == null)
return null;
disk.Get();
object diskObj = disk["VolumeSerialNumber"];
if (diskObj != null)
return diskObj.ToString();
}
}
catch (System.Threading.ThreadAbortException)
{
throw;
}
catch (Exception ex)
{
Trace.TraceWarning("Failed to read DiskID\r\n" + ex.Message);
}
try
{
uint serialNum, serialNumLength, flags;
StringBuilder volumename = new StringBuilder(256);
StringBuilder fstype = new StringBuilder(256);
bool ok = GetVolumeInformation(driveLetter.ToString() + ":\\", volumename, (uint)volumename.Capacity - 1, out serialNum, out serialNumLength, out flags, fstype, (uint)fstype.Capacity - 1);
if (ok)
{
return string.Format("{0:X4}{1:X4}", serialNum >> 16, serialNum & 0xFFFF);
}
}
catch (System.Threading.ThreadAbortException)
{
throw;
}
catch (Exception ex2)
{
Trace.TraceWarning("Failed to read DiskID\r\n" + ex2.Message);
}
return null;
}
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
static extern bool GetVolumeInformation(string Volume, StringBuilder VolumeName, uint VolumeNameSize, out uint SerialNumber, out uint SerialNumberLength, out uint flags, StringBuilder fs, uint fs_size);
Using System.Management you can extract all Hardware information. with this you can create an ID from this values, meaby a crypted id and save it.
Here is a reference: Link
I use MAC Address, Motherboard id and works fine to me.
I hope this help!
I have written some code which deals with C# reflections and selenium to automate the build process of a URL.
But I am unable to catch the exception. What I did is , I exported into .html format from selenium IDE. and parsed and it automatically calls the function related to it from c# code.
but I am unable to catch it. I need help in this regard? Any guesses why it is unable to catch the exception..
I am using Visual Studio Microsoft Visual C# 2010 Express.
And the code is as follows.
using System;
using System.Text;
using System.Text.RegularExpressions;
using NUnit.Framework;
using Selenium;
using System.Reflection;
using System.IO;
namespace SeleniumTests
{
public class Program
{
public ISelenium selenium;
public void SetupTest()
{
selenium = new DefaultSelenium("localhost", 4444, "*chrome", "URL");
selenium.Start();
}
//[TearDown]
public void TeardownTest()
{
try
{
selenium.Stop();
}
catch (Exception)
{
}
}
public void myFun(string file)
{
bool flag = false;
string targetString = "", valueString = "", commandString = "";
string subString1, subString2;
HtmlAgilityPack.HtmlNode commandNode=null;
HtmlAgilityPack.HtmlNode targetNode=null;
HtmlAgilityPack.HtmlNode valueNode=null;
HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
doc.Load(file);
doc.OptionCheckSyntax = true;
doc.OptionFixNestedTags = true;
doc.OptionAutoCloseOnEnd = true;
doc.OptionOutputAsXml = true;
doc.OptionDefaultStreamEncoding = Encoding.Default;
HtmlAgilityPack.HtmlNode table = doc.DocumentNode.SelectSingleNode("//table");
foreach (var row in table.SelectNodes("//tr"))
{
commandNode = row.SelectSingleNode("td[1]");
commandString = commandNode.InnerHtml.ToString();
subString1 = commandString.Substring(0, 1);
subString1 = subString1.ToUpper();
subString2 = commandString.Substring(1, commandString.Length - 1);
commandString = subString1 + subString2;
targetNode = row.SelectSingleNode("td[2]");
if (targetNode != null)
{
targetString = targetNode.InnerHtml.ToString();
if (targetString.Length == 0)
{
targetNode = null;
}
}
valueNode = row.SelectSingleNode("td[3]");
if (valueNode != null)
{
valueString = valueNode.InnerHtml.ToString();
if (valueString.Length == 0)
{
valueNode = null;
}
}
MethodInfo SeleniumMethod = typeof(ISelenium).GetMethod(commandString);
if (SeleniumMethod == null)
{
// Console.WriteLine(" \n NULL " + commandString);
continue;
}
if (targetNode == null && valueNode == null)
continue;
if (targetNode != null && valueNode != null)
{
String[] SeleniumArgs = new String[2];
SeleniumArgs[0] = targetNode.InnerHtml.ToString();
SeleniumArgs[1] = valueNode.InnerHtml.ToString();
try
{
SeleniumMethod.Invoke(selenium, SeleniumArgs);
}
catch (System.Reflection.TargetInvocationException)
{
}
catch (Selenium.SeleniumException se)
{
flag = true;
string lines = "\n Selenium Exception: Caught an exception while executing the script : " + file + " with the command : " + commandNode.InnerHtml.ToString() + " and the XPath is: " + targetNode.InnerHtml.ToString() + " and the value is : " + valueNode.InnerHtml.ToString() + " and the exception is as follows : ";
using (StreamWriter writer = new StreamWriter("Log.txt", true))
{
writer.WriteLine(lines);
writer.Flush();
writer.Close();
}
}
catch (Exception e)
{
flag = true;
string lines = "\n Exception: Caught an exception while executing the script : " + file + " with the command : " + commandNode.InnerHtml.ToString() + " and the XPath is: " + targetNode.InnerHtml.ToString() + " and the value is : " + valueNode.InnerHtml.ToString() + " and the exception is as follows : ";
using (StreamWriter writer = new StreamWriter("Log.txt", true))
{
writer.WriteLine(lines);
writer.Flush();
writer.Close();
}
}
}
else if (targetNode != null && valueNode == null)
{
String[] SeleniumArgs = new String[1];
SeleniumArgs[0] = targetNode.InnerHtml.ToString();
SeleniumMethod.Invoke(selenium, SeleniumArgs);
}
else if (valueNode != null)
{
String[] SeleniumArgs = new String[1];
SeleniumArgs[0] = valueNode.InnerHtml.ToString();
SeleniumMethod.Invoke(selenium, SeleniumArgs);
}
}// end of for
string line = "\n Script executed successfully ";
if (flag == false)
{
using (StreamWriter writer = new StreamWriter("Log.txt", true))
{
writer.WriteLine(line);
writer.Flush();
writer.Close();
}
}
}
}
public class TestProgram
{
static void Main(string[] args)
{
try
{
Program p = new Program();
p.SetupTest();
string file = #"1.html";
p.myFun(file);
p.TeardownTest();
}
catch { }
}
}
}
If you are trying to catch the exception in your Main() method, you need to bubble your exceptions up in your myFun method. At the moment you are drowning any exceptions in your myFun method.
e.g.
try
{
SeleniumMethod.Invoke(selenium, SeleniumArgs);
}
catch (System.Reflection.TargetInvocationException)
{
throw; //make this bubble up to the calling method.
}
catch (Selenium.SeleniumException se)
{
flag = true;
string lines = "\n Selenium Exception: Caught an exception while executing the script : " + file + " with the command : " + commandNode.InnerHtml.ToString() + " and the XPath is: " + targetNode.InnerHtml.ToString() + " and the value is : " + valueNode.InnerHtml.ToString() + " and the exception is as follows : ";
using (StreamWriter writer = new StreamWriter("Log.txt", true))
{
writer.WriteLine(lines);
writer.Flush();
writer.Close();
}
throw se; //bubble up to calling method
}
//etc...