How do I accept a null line? - c#

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
}

Related

ASP.NET/Entity : Issue with my Array Index

I have managed to pull out the FirstorDefault() in the Query, however, some of these address types in the database actually have more than 1 address: therefore, I am trying to build an array of every address regarding each one.
The current code:
int counter = 0;
string queryID = "";
List<string> busAddr = new List<string>();
while (counter != busIDs.Count)
{
queryID = busIDs[counter];
var gathered = (from c in db.tblbus_address where c.BusinessID == queryID && c.AddressTypeID == addrnum select c).ToArray();
int gath = 0;
if ((gathered[gath] as tblbus_address) != null && !string.IsNullOrEmpty((gathered[gath] as tblbus_address).Address1))
{
var address = gathered[gath] as tblbus_address;
string test = "";
while (gath != address.Address1.Length)
{
var all = address.Address1;
test += address.Address1.ToString() + ",";
}
busAddr.Add(test);
}
else
{
busAddr.Add("No address for this type exists...");
}
counter++;
gath++;
}
I am receiving an error:
Index was outside the bounds of the array.
at this line:
if ((gathered[gath] as tblbus_address) != null && !string.IsNullOrEmpty((gathered[gath] as tblbus_address).Address1))
Can anyone point me in the right direction? I know this structure is the issue but I cannot think how to approach the situation.
You are trying to get the element gathered[gath] when there are no items in gathered. Adding a check for null and Any will help you
if(gathered!=null && gathered.Any()
&& (gathered[gath] as tblbus_address) != null
&& !string.IsNullOrEmpty((gathered[gath] as tblbus_address).Address1))
{
...
...
}

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";}

getting a registry key and value in 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("");
}

Nullable Property throwing NullReferenceException on .HasValue

This line of (C#) code
if (!currentLap.S1.HasValue)
is giving me
System.NullReferenceException: Object reference not set to an instance of an object.
provided I'm sure that currentLap variable is instantiated (because it's being used a few lines before and it is a local variable) and it has following property:
private double? _s1;
[DefaultValue(null)]
[JsonConverter(typeof(ShortDoubleConverter))]
public double? S1
{
get { return _s1; }
set { _s1 = value; }
}
how can it possibly throw NullReferenceException? Can it be something to do with optimization on Release mode?
Thanks,
Stevo
EDIT:
here is full method code.
public void Update(DriverData driverData)
{
LapInfo currentLap = this.CurrentLap;
if (currentLap != null &&
this.LastDriverData != null &&
driverData.TotalLaps != this.LastDriverData.TotalLaps &&
driverData.InPits &&
driverData.Speed < 10 &&
!this.LastDriverData.InPits)
{
currentLap.Escaped = true;
}
this.LastDriverData = driverData;
if ((currentLap == null || currentLap.Lap != driverData.LapNumber) &&
!this.Laps.TryGetValue(driverData.LapNumber, out currentLap))
{
currentLap = new LapInfo() { Lap = driverData.LapNumber, Parent = this, Class = driverData.Class };
this.Laps.Add(driverData.LapNumber, currentLap);
int lapsCount = 0, completedDriverLaps = 0, cleanLaps = 0;
this.TotalLaps = driverData.TotalLaps;
//if it's not the first lap
if (driverData.TotalLaps > 0)
{
//previous lap
if (this.CurrentLap == null || !this.CurrentLap.Escaped)
{
this.CompletedLaps++;
if (this.CurrentLap == null || !this.CurrentLap.MaxIncident.HasValue)
this.CleanLaps++;
}
}
foreach (DriverLapsInfo laps in this.Parent.LapsByVehicle.Values)
{
lapsCount += laps.TotalLaps;
completedDriverLaps += laps.CompletedLaps;
cleanLaps += laps.CleanLaps;
}
this.Parent.Parent.SetLapsCount(driverData, lapsCount, driverData.Class, completedDriverLaps, cleanLaps);
}
this.CurrentLap = currentLap;
//add incidents
if (driverData.Incidents != null)
{
foreach (IncidentScore incident in driverData.Incidents)
{
this.CurrentLap.MaxIncident = Math.Max(this.CurrentLap.MaxIncident ?? 0, incident.Strength);
this.CurrentLap.Incidents++;
this.Incidents++;
}
}
LapInfo previousLap = null;
if ((this.PreviousLap == null || this.PreviousLap.Lap != driverData.TotalLaps) &&
this.Laps.TryGetValue(driverData.TotalLaps, out previousLap))
{
this.PreviousLap = previousLap;
if (!this.PreviousLap.Date.HasValue)
{
this.PreviousLap.Date = DateTime.UtcNow;
}
}
if (currentLap.Position == 0)
currentLap.Position = driverData.Position;
if (driverData.CurrentS1 > 0)
{
**if (!currentLap.S1.HasValue)**
{
this.UpdateBestS1(driverData.BestS1);
this.Parent.Parent.UpdateBestS1(driverData.BestS1, driverData.UniqueName);
currentLap.UpdateS1(driverData.CurrentS1, driverData);
//reset the best split set at the finish line
if (this.PreviousLap != null && this.PreviousLap.SplitBest < 0)
this.PreviousLap.SplitBest = 0;
}
if (driverData.CurrentS2.HasValue && driverData.CurrentS1.HasValue && !currentLap.S2.HasValue)
{
double s2 = driverData.CurrentS2.Value - driverData.CurrentS1.Value;
this.UpdateBestS2(s2);
this.Parent.Parent.UpdateBestS2(s2, driverData.UniqueName);
currentLap.UpdateS2(s2, driverData);
}
}
if (this.PreviousLap != null)
{
if (driverData.LastLap > 0)
{
if (!this.PreviousLap.S3.HasValue && driverData.LastS2.HasValue)
{
double s3 = driverData.LastLap.Value - driverData.LastS2.Value;
this.UpdateBestS3(s3);
this.Parent.Parent.UpdateBestS3(s3, driverData.UniqueName);
this.PreviousLap.UpdateS3(s3, driverData);
}
if (!this.PreviousLap.LapTime.HasValue)
{
double? bestLap = this.Parent.Parent.BestLap;
this.PreviousLap.UpdateLapTime(driverData, 0);
this.Parent.Parent.UpdateBestLap(this.PreviousLap, driverData.BestLap, driverData);
this.UpdateBestLap(driverData.BestLap, this.PreviousLap);
this.PreviousLap.UpdateLapTime(driverData, bestLap);
}
}
else
{
if (this.PreviousLap.SplitBest.HasValue)
this.PreviousLap.UpdateBestSplit();
if (this.PreviousLap.SplitSelf.HasValue)
this.PreviousLap.UpdateSelfSplit();
}
}
if (driverData.InPits)
{
switch (driverData.Sector)
{
case Sectors.Sector1:
if (previousLap != null)
previousLap.InPits = true;
break;
case Sectors.Sector3:
currentLap.InPits = true;
break;
}
}
//lap to speed
if (currentLap.TopSpeed < driverData.Speed)
{
driverData.TopSpeedLap = driverData.Speed;
currentLap.UpdateTopSpeed(driverData.Speed);
}
else
driverData.TopSpeedLap = currentLap.TopSpeed;
//overall top speed
if (this.TopSpeed < driverData.Speed)
{
driverData.TopSpeed = driverData.Speed;
this.TopSpeed = driverData.Speed;
this.Parent.Parent.UpdateTopSpeed(this.TopSpeed, driverData);
}
else
driverData.TopSpeed = this.TopSpeed;
}
There is no way on earth the code can make it to that line and currentLap beeing null.
Or am I going crazy? :)
.HasValue will not throw if the nullable reference is null, but a.b.HasValue will if a is null.
I suspect that currentLap == null. I know you say you're sure that currentLap is not null, but I think that's the most likely explanation. Can you post more code?
Update:
Thanks for posting your code.
This doesn't throw:
void Main() {
var f = new Foo();
Console.WriteLine (f.S1);
Console.WriteLine (f.S1.HasValue);
}
class Foo {
private double? _s1 = null;
public double? S1 {
get { return _s1; }
set { _s1 = value; }
}
}
Could you try to create a minimal reproduction? (minimal code that exhibits the issue)
Maybe have a look at the previous line of code :) - debugger often highlights the next line after the one where the NullReferenceException was actually thrown.

How to skip to next item if current variable is null

I have a function that retrieves a list of device names and stores then in a variable. Then the next step is to get info using 1 device name per line and keep going till the loop is complete.
String text = "";
String errors = "";
for (int i = 0; i < collection.Result.Count; i++)
{
deviceNames += collection.Result[i].DeviceName + Environment.NewLine;
getvirtuals.Location = deviceNames;
var virtuals = client.GetKnownVirtuals(getvirtuals, LtmKeyType.VirtualAddressPort);
if (virtuals.Result == null)
{
i++;
getvirtuals.Location = deviceNames;
for (int v = 0; v < virtuals.Result.Count; v++)
{
try
{
LtmKey virtualKey = new LtmKey();
virtualKey.Location = virtuals.Result[v].Location;
virtualKey.LocationType = virtuals.Result[v].LocationType;
virtualKey.Key = virtuals.Result[v].Key;
virtualKey.KeyType = LtmKeyType.VirtualAddressPort;
virtualKey.AdminGroup = admingroupComboBox.Text;
var memberStatus = client.GetMemberStatus(virtualKey);
for (int j = 0; j < memberStatus.Result.Count; j++)
{
VirtualMemberStatus status = memberStatus.Result[j];
text += String.Format("{5},{4},{0},{1},{2},{3}" + Environment.NewLine, status.Member.Address, status.Member.Port, status.EffectiveStatus, status.DesiredStatus, virtualKey.Key.Replace(":", ","), DateTime.UtcNow);
toolStripProgressBar1.PerformStep();
}
}
catch
{
errors += String.Format("{0} Error Code: 2, Error occurred, check device name (case senstive) and admin group. This error may also occur due to connection loss, try again." + Environment.NewLine, DateTime.UtcNow);
}
}
this.allResultsBox.Text = text;
getallstatusButton.Enabled = true;
}
}
The problem that I am running into is that if virtuals is null the tool crashes, instead what I want to do is if virtuals = null I want to move onto the next item from the list. I have tried a if statement but it is not working the way planned, it still comes back as null.
Well this seems like a problem to start with:
if (virtuals.Result == null)
{
i++;
getvirtuals.Location = deviceNames;
for (int v = 0; v < virtuals.Result.Count; v++)
...
If virtuals.Result is null, how do you expect virtuals.Result.Count to work? I suspect you meant:
if (virtuals.Result != null)
However, I suspect you really just want:
// Keep going with the next iteration of the for loop
if (virtuals == null || virtuals.Results == null)
{
continue;
}
If all you want is to go to the next loop iteration if virtuals is null then you want
if (virtuals == null) continue;
How about just inserting:
if(virtuals == null)
continue;
right after the line
var virtuals = client.GetKnownVirtuals(getvirtuals, LtmKeyType.VirtualAddressPort);
Have you tried changing the line:
if (virtuals.Result == null)
to:
if ((virtuals != null) && (virtuals.Result != null))
If this doesn't solve your issue, then you need to indicate what the additional errors are.
if (virtuals.Result == null)
make this
if (virtuals == null)

Categories

Resources