getting a registry key and value in C# - c#

Sorry if this is simple, I haven't coded since college. I'm trying to write a program to view registry entries in Windows 7. I want to check to see if the registry value exists first, then check to see what the value is. If it doesn't exist, I want one message, if it does exist, I want one message reflecting a value of 1, and another reflecting a value of 0. I got the code to work if the registry key doesn't exist, but if I add the key and value it crashes. Not sure what I'm doing wrong here. Any suggestions would be appreciated. Here is my code.
using (RegistryKey Key = Registry.LocalMachine.OpenSubKey(#"SYSTEM\CurrentControlSet\services\LanmanServer\Parameters"))
if (Key != null)
{
string val = (string)Key.GetValue("EnableOplocks");
if (val == null)
{
oplockTextBox.Text = "Not Present In Registry";
oplockTextBox.BackColor = Color.Yellow;
}
else if (val == "1")
{
opslockTextBox.Text = "NO";
opslockTextBox.BackColor = Color.Red;
}
else
{
oplockTextBox.Text = "YES";
oplockTextBox.BackColor = Color.Green;
}
}
else
{
MessageBox.Show("");
}

As far as I can tell, the EnableOplocks value for that registry key is a DWORD value, which will give you an int when you use GetValue() to retrieve it. Trying to cast an int to a string will produce an InvalidCastException.
Instead, you should try this:
int? val = Key.GetValue("EnableOplocks") as int?;
if (val == null)
{
// ..
}
else if (val == 1)
{
// ...
}
Or this:
object val = Key.GetValue("EnableOplocks");
if (val == null)
{
// ...
}
else
{
string strVal = val.ToString();
if (strVal == "1")
{
// ...
}
}
In general, please remember to provide all of the error information you have. Saying "it crashes" is not very informative.

The registry can hold data-types other than string. What is happening is you are likely getting a int returned and that is why you are crashing when you attempt to cast a int to a string
Get the value back and store it in a object and have your debugger break. You should then be able to see what datatype is stored in the object and change your code to make the correct cast.
The other option would be use .ToString() instead of casting, you would need to compare the string 1 (like you are now) instead of the value 1. However, I always prefer to just use the correct type instead of turning everything in to strings.

Use follow;
string val = Key.GetValue("EnableOplocks").ToString();
EDIT
using (RegistryKey Key = Registry.LocalMachine.OpenSubKey(#"SYSTEM\CurrentControlSet\services\LanmanServer\Parameters"))
if (Key != null)
{
var val = Key.GetValue("EnableOplocks");
if (val == null)
{
oplockTextBox.Text = "Not Present In Registry";
oplockTextBox.BackColor = Color.Yellow;
}
else if (val.ToString() == "1")
{
opslockTextBox.Text = "NO";
opslockTextBox.BackColor = Color.Red;
}
else
{
oplockTextBox.Text = "YES";
oplockTextBox.BackColor = Color.Green;
}
}
else
{
MessageBox.Show("");
}

Related

How do I accept a null line?

So I have a line of code that sometimes does not exist.
HtmlElement Pend = webBrowser1.Document.GetElementById("ctl00_cphRoblox_AlreadyRequestedInvite");
Here is the rest of my code
string PendT;
webBrowser1.Document.GetElementById("ctl00_cphRoblox_JoinGroup").InvokeMember("click");
HtmlElement Pend = webBrowser1.Document.GetElementById("ctl00_cphRoblox_AlreadyRequestedInvite");
PendT = Pend.InnerText;
Debug.WriteLine(PendT);
if (PendT == "Join Pending")
{
Debug.WriteLine("Join Pending");
Value = 1;
}
Now what I need help with is sometimes Pend is null and when I go to do PendT = Pend.InnerText; I get System.NullReferenceException. And that's probably because it cannot find Pend. Is there I way I can assign Pend a string value if it's null? I have tried
if (webBrowser1.Document.GetElementById("ctl00_cphRoblox_AlreadyRequestedInvite").InnerText != null)
{
Debug.WriteLine("Join Pending");
Value = 1;
}
Although that hasn't worked.
You could check if Pend is null after you retrieve it. Do what you want with taht if check.
string PendT;
webBrowser1.Document.GetElementById("ctl00_cphRoblox_JoinGroup").InvokeMember("click");
HtmlElement Pend = webBrowser1.Document.GetElementById("ctl00_cphRoblox_AlreadyRequestedInvite");
if(Pend != null)
{
PendT = Pend.InnerText;
Debug.WriteLine(PendT);
if (PendT == "Join Pending")
{
Debug.WriteLine("Join Pending");
Value = 1;
}
}
else
{
// do something here
}

C# Textbox textresult wouldn't show up

This is the code used to check whether the first number is greater than the second, but it is not working as expected. Can anyone please suggest the reason and correct me?
if (txtFirst.Text == "")
{
txtFirst.Text = "0";
if (txtSecond.Text == "")
{
txtSecond.Text = "0";
int first = Convert.ToInt32(txtFirst.Text);
int second = Convert.ToInt32(txtSecond.Text);
if (first < second)
{
txtResult.Text = "TRUE";
}
else
{
txtResult.Text = "FALSE";
}
}
}
Your scenario is working only if both the textboxes are blank(""). so it will be much better if you do like the following:
if (txtFirst.Text == "") {txtFirst.Text = "0";}
if (txtSecond.Text == ""){txtSecond.Text = "0";}
// it is good to check for null in this scenario since
// Convert.ToInt32() is not capable of handling null
int first = Convert.ToInt32(txtFirst.Text);
int second = Convert.ToInt32(txtSecond.Text);
if (first < second){txtResult.Text = "TRUE";}
else{txtResult.Text = "FALSE";}

Compare a registry key to find if it is greater than or less than?

I am currently working with the following code:
public static bool checkFF86version(string FF86_version)
{
RegistryKey key = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64)
.OpenSubKey(#"SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall");
//.OpenSubKey(#"SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall");
string displayFF86version;
if (key != null)
{
foreach (RegistryKey subkey in key.GetSubKeyNames().Select(keyName => key.OpenSubKey(keyName)))
{
displayFF86version = subkey.GetValue("DisplayVersion") as string;
if (displayFF86version != null && displayFF86version.Equals(FF86_version))
{
return true;
}
}
key.Close();
}
return false;
}
I would like to take the DisplayVersion from the registry key and check if it is greater than or less than the checked version (FF86_version)
I have tried converting the string to int, but seem to be stumped on the null reference. (shown below:)
public static bool checkFF86greater(string FF86_greater)
{
RegistryKey key = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64)
.OpenSubKey(#"SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall");
//.OpenSubKey(#"SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall");
string displayFF86greater;
if (key != null)
{
foreach (RegistryKey subkey in key.GetSubKeyNames().Select(keyName => key.OpenSubKey(keyName)))
{
displayFF86greater = subkey.GetValue("DisplayVersion") as string;
if (displayFF86greater != null && displayFF86greater.Equals(FF86_greater))
{
string A = displayFF86greater;
string B = FF86_greater;
int versionA = Convert.ToInt32(A.Replace(".", string.Empty));
int versionB = Convert.ToInt32(B.Replace(".", string.Empty));
if (versionA > versionB)
return true;
}
}
//key.Close();
return true;
}
return false;
}
I know this may be very simple for most of you, but for some reason this has beat me up for two days, and help would be greatly appreciated.
Looking for:
//Check FireFox version and compare it to a known good version
if (!(checkFF86name("Firefox")))
listView1.Items.Add(new ListViewItem { ImageIndex = 0, Text = "Firefox is NOT installed" });
else if (checkFF86name("Firefox") && (checkFF86version("33.0")))
listView1.Items.Add(new ListViewItem { ImageIndex = 0, Text = "Firefox is the latest version" });
else if (checkFF86name("Firefox") && (checkFF86greater("33.0.1")))
listView1.Items.Add(new ListViewItem { ImageIndex = 0, Text = "Firefox is NEWER than checked version" });
else
listView1.Items.Add(new ListViewItem { ImageIndex = 0, Text = "Re-installing...." });
I think I tried that already using the following:
var checkedversion = FF86_greater.Split('.');
var installed = displayFF86greater.Split('.');
for (int i = 0; i < installed.Length; i++)
{
var currinstalled = in.Parse(installed[i]);
var currcheckedversion = int.Parse(checkedversion[i]);
if (currinstalled == currcheckedversion)
continue;
if (currinstalled > currcheckedversion)
return true;
if (currinstalled < currcheckedversion)
return false;
Unless I am going about this the wrong way!
Tried it like this, and still returning "False"
public static bool checkFF86greater(string FF86_greater)
{
RegistryKey key = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64)
.OpenSubKey(#"SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall");
//.OpenSubKey(#"SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall");
string displayFF86greater;
if (key != null)
{
foreach (RegistryKey subkey in key.GetSubKeyNames().Select(keyName => key.OpenSubKey(keyName)))
{
displayFF86greater = subkey.GetValue("DisplayVersion") as string;
if (displayFF86greater != null && displayFF86greater.Equals(FF86_greater))
{
var version = displayFF86greater;
var parsedversion = Version.Parse(version);
var minimumversion = new Version(FF86_greater);
if (parsedversion >= minimumversion)
return true;
else
return false;
}
}
key.Close();
}
return false;
}
What you're looking for is Version.Parse. Then use two Version objects to compare.
Simple example:
// Get string from registry
// RegistryKey.OpenBaseKey(blahblahblah)
var version = "32.0.1"; //Assume this string came from registry
var parsedversion = Version.Parse(version);
var minimumversion = new Version("33.0.1");
if (parsedversion >= minimumversion)
Console.WriteLine("Your version is correct");
else
Console.WriteLine("You need a newer version!");
Note: The Parse method is a convenience method; it is equivalent to calling the Version(String) constructor, also shown in this example (for minimumversion).
Other than that (from your code):
if (!(checkFF86name("Firefox")))
...
else if (checkFF86name("Firefox") && (checkFF86version("33.0")))
...
else if (checkFF86name("Firefox") && (checkFF86greater("33.0.1")))
...
else
...
You do realize that you access (and iterate over) the registry (worst case) some 5 times here do you? It won't kill you but it also won't hurt you to simply get the value once and then use that value in your comparisons.
Example:
Version ff86version = GetFF86VersionFromRegistry(); //Implement this method so that it simply returns FF's version as a Version object (or null if the key is not found)
if (ff86version == null)
// FF not installed
else if (ff86version < new Version("33.0")
// FF version less than 33.0 installed
else
// Whatever
Also, it's not very DRY and prone to mistakes if you keep repeating things like "Firefox". Use a variable / constant if you insist on calling the method in each if/else/else.

Why am I getting a format exception in this C# code?

I am working on a Windows Form application. I am parsing an XML file and doing some queries. For example, in this case I am trying to find all users weighing between 55 and 100. For some reason, when I run this code, I get a format exception unhandled. Why am I getting a format exception. I have indicated the breakpoint where the exception occurs. I think the problem is a syntactical error.
Thanks for your help.
private bool UserWeighsBetween55and100(IEnumerable<XElement> paramsList) {
bool result = false;
foreach (XElement parameter in paramsList) {
if (parameter.Attribute("name").Value == "Weight") {
--->HERE if ((Int32.Parse(parameter.Attribute("value").Value) > 55) &&
(Int32.Parse(parameter.Attribute("value").Value) < 100)){
return true;
}
}
}
return result;
}
Convert your value once instead of converting same value two time.
Try to do like this.
int iValue = 0;
if (Int.TryParse(parameter.Attribute("value").Value, out iValue)) //If the value converted
{
if (iValue > 55 && iValue < 100)
{
return true;
}
}
else //Failed to convert value into int datatype
{
//Code here if conversion faild
}
if the parameter.Attribute("value").Value is containing non-numeric value then it wont convert in int datatype.
Instead of using the "Parse" method, use the tryParse.
In your case, it would look like :
foreach (XElement parameter in paramsList) {
if (parameter.Attribute("name").Value == "Weight") {
int value;
if(!Int32.TryParse(parameter.Attribute("value").Value, out value)){
//Not a number, handle this case
}
if ((value > 55) && (value < 100)){
return true;
}
return result;
}
I will be answering my question because I found out my mistake and I hope it would help everybody reading this post.
The problem with using Int32.Parse() was that while I was parsing the XML file, I didn't pay attention to the values of type double.
The fix for this code would be as follows:
private bool UserWeighsBetween55and100(IEnumerable<XElement> paramsList) {
bool result = false;
foreach (XElement parameter in paramsList) {
if (parameter.Attribute("name").Value == "Weight") {
if ((parameter.Attribute("value").Value)!=null) {
if ((Convert.ToDouble(parameter.Attribute("value").Value) > 55) && (Convert.ToDouble(parameter.Attribute("value").Value) < 100)) {
return true;
}
}
}
}
return result;
}

c# two nested if statements, one else

Please excuse the question that seems simple, but for some reason I cannot think of an elegant solution at the moment.
I have the following situation:
if (Request.QueryString["name"] != null)
{
if (Request.QueryString["name"].ToString() != "")
{
nameSpan.InnerHtml = Request.QueryString["name"].ToString();
}
}
The problem is, if I want to hide the nameSpan if querystring["name"] is either null or emtpy. The ugly solution would be:
if (Request.QueryString["name"] != null)
{
if (Request.QueryString["name"].ToString() != "")
{
nameSpan.InnerHtml = Request.QueryString["name"].ToString();
}
else
{
nameSpan.Visible = false;
}
}
else
{
nameSpan.Visible = false;
}
I would like to have a situation where both the nameSpan.Visible = false; sections could be merged into one area so I only have to write it once.
As far as I am aware, it is not possible to do the following:
if (Request.QueryString["name"] != null && Request.QueryString["name"].ToString() != "")
{
nameSpan.InnerHtml = Request.QueryString["name"].ToString();
}
else
{
nameSpan.Visible = false;
}
But please tell me if I am wrong! If you have a different solution which changes the logic then I am more than happy to have different views! Thank you!
Your && solution should be fine. If left side of && is false, right side it not evaluated so there will be no exception.
If you want, you could use String.IsNullOrEmpty static method:
if (!string.IsNullOrEmpty(Request.QueryString["name"]))
{
nameSpan.InnerHtml = Request.QueryString["name"].ToString();
}
else
{
nameSpan.Visible = false;
}
if you are after compact code, I'd use next (NameValueCollection returns null if key does not exist, and indexer returns string):
nameSpan.InnerHtml = Request.QueryString["name"];
nameSpan.Visible = !string.IsNullOrEmpty(nameSpan.InnerHtml);

Categories

Resources