Compiling error Nullreference - c#

I'm compiling a program which was originally build in Visual C# 2005. I'am using visual C# 2010. And I keep getting "NullReference Execption was unhandled" errors when running the program on the following functions:
The error occurs on the line with DataBuffer. DataBuffer is an private string set to null on initialisation.
if (DataBuffer.Contains(ok))
{
okFound = true;
}
and
string temp = getLine(DataBuffer.Substring(mylocation));
if (!checkTypeFound())
{
if (temp != null)
{
parseDeviceType(temp);
}
checkTypeFound();
}
When I check what the value of DataBuffer is in the code above (when I get the error) this is not null. It actually contains the data I expect.
DataBuffer information is loaded in this function:
private void ser1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
while (ser1.BytesToRead > 0)
{
string data = ser1.ReadExisting();
DataBuffer += data;
}
}
The serial port is opened somewhere else in the code. There have been no changes to the code only the compiler is different. What line should I add, and where to solve this error? Note, I can prevent this error from happening using an if and try-catch statement. But this is not what I'm looking for, I need this code to work.
This application has not been changed in any way other than the compiler.

You should check if DataBuffer is null before you call its methods.
if (DataBuffer != null && DataBuffer.Contains(ok))
{
okFound = true;
}
// or simpler:
okFound = (DataBuffer != null && DataBuffer.Contains(ok));
and your second code snipped should check for null as well.
string temp = String.Empty;
if (DataBuffer != null)
temp = getLine(DataBuffer.Substring(mylocation));
if (!checkTypeFound())
{
if (!String.IsNullOrEmpty(temp))
parseDeviceType(temp);
checkTypeFound();
}

Try using the following:
if (DataBuffer != null && DataBuffer.Contains(ok))
{
okFound = true;
}

You should set the value of DataBuffer to something other than null in your constructor. If you can't do that then you may set it to string.Empty instead of null to avoid null exception. But it always better to check for null before initiating an instance method on object.

Related

c# Console Application referenced DLL variable remains null

I have read through many posts on this type of situation and I can't figure out the solution or what I am doing wrong.
I have a code that references a DLL. It is added as a reference in Visual Studio and it is copied locally along with the target exe file. It runs for me, but when I deploy it to another computer it causes a NullReference exception at the below line of code (see comment):
Unhandled Exception: System.NullReferenceException: Object reference
not set to an instance of an object.
at CheckUpdate.Program.checkUpdate() in Program.cs:line 28
at CheckUpdate.Program.Main(String[] args) in Program.cs:line 22
Here is my code, see comments where the error is reported on the stack trace:
using System;
using System.Collections.Generic;
using System.Text;
using Com.Idiominc.Webservices.Client;
using System.Diagnostics;
using System.IO;
using System.Net;
namespace CheckUpdate
{
class Program
{
private static WSContext _UpdateWScontext { get; set; }
private static string wsUrl = "https://www.myWorldServer.com/ws";
private static string[] myArgs;
static int Main(string[] args)
{
myArgs=args;
if (myArgs.GetUpperBound(0) != 1) return 9;
return checkUpdate();
}
public static int checkUpdate()
{
string testStr = "password1";
while (_UpdateWScontext == null && testStr != "")
{
try
{
_UpdateWScontext = new WSContext("user", testStr, wsUrl + "/services");
}
catch
{
if (_UpdateWScontext == null)
{
if (testStr == "password1") testStr = "password2";
else if (testStr == "password2") testStr = "password3";
else testStr = "";
}
}
}
if (_UpdateWScontext.token == string.Empty) return 0;
string currentversion = myArgs[0];
string latestver = getLatestVersion();
if (latestver == null)
{
return 0;
}
else if (!currentversion.Equals(latestver))
{
if (getLatestDownload()) return 1;
else return 0;
}
else
{
_UpdateWScontext.logout(_UpdateWScontext.token);
return 2;
}
}
}
}
The DLL (WSWebServices.dll) is copied locally along with the executable. It runs on my own station, but when I port it to another station, it causes the exception.
Any advice or clue would be appreciated, thanks.
Edit:
Based on comments the NullReference exception was on the line
if (_UpdateWScontext.token == string.Empty) return 0;
I have now modified this to
if (_UpdateWScontext == null || _UpdateWScontext.token == string.Empty) return 0;
With this no more NullReference Exception, however the exit code now is always 0, meaning the variable is still null.
Any suggestion as to why the connection is not working to the URL? It does work from the browser on the same computer.
Update - solved
I traced the error by outputting the Exception stack trace to the console on the station where the app was not working, and it turned out that the WSWebServices.dll is referencing the Microsoft.Web.Services2.dll (part of the WSE package) and for some reason this was missing from the installation on the misbehaving station.
I added it as a reference and made sure that the dll is copied to the application folder and it now works as intended. Documented here for others in the same mystery why the WorldServer web services would not work.
Within while loop, firstly you try with Password1, you get exception on creating WSContext, then in catch block you set testStr to Password2. With Password2 you again get an exception, and this time in catch block you set testStr to an empty string, and you leave out of while loop without creation of _UpdateWScontext.
I think you null ref exception exactly at this point of code if (_UpdateWScontext.token == string.Empty) return 0;.
You should log exception details in the catch block within the while loop, it can give clue about the error.

.net SqlDataReader VB C#

I have this statement:
if (sqlClass.Reader != null && sqlClass.Reader.HasRows)
{
do
{
data = sqlClass.Reader.GetString(0); //error line System.InvalidOperationException {"Invalid attempt to read when no data is present."}
} while (sqlClass.Reader.Read());
}
the object sqlClass.Reader is of type System.Data.SqlClient.SqlDataReader
In C# it gives me an InvalidOperationException but in VB it worked fine, what would the reason be and how do I solve this?
Something like this:
if (null != sqlClass.Reader)
{
while (sqlClass.Reader.Read())
{
data = sqlClass.Reader.GetString(0);
}
}

Why do I get "Object reference not set to an instance of an object" [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What is a NullReferenceException in .NET?
Object reference not set to an instance of an object.
protected void Page_Load(object sender, EventArgs e)
{
int Role = Convert.ToInt32(Request.QueryString["Role"].ToString());
try
{
if (Role != 3)
{
gv_ViewApplicants.Visible = true;
gv_ViewApplicants_SelectedIndexChanged(this, new EventArgs());
}
else
{
gv_ViewApplicants.Visible = false;
}
}
catch (NullReferenceException e1)
{
}
}
Try
int Role = Convert.ToInt32(Request.QueryString["Role"] != null ?
Request.QueryString["Role"].ToString() :
"0");
instead of
int Role = Convert.ToInt32(Request.QueryString["Role"].ToString());
You need to check for null if not passed query string.
first thing
int Role = Convert.ToInt32(Request.QueryString["Role"].ToString());
This statement is outside try so if it crashes on QueryString being null or even if Convert.ToInt32 method throw exception, catch block will not be executed.
You can try this code
int number;
bool result = Int32.TryParse(Request.QueryString["Role"], out number);
if (result)
{
// your implemntation
}
else
{
// your implemntation
}
You can even use Convert.ToString(Request.QueryString["Role"]) if still u are getting this error.
The code is trying to access a member of a reference type variable that is set to null.
Please make source Request.QueryString["Role"] is not null.
You should Never catch NullReferenceException.
However, the problem seems to be in very first line: (the only line outside try block)
int Role = Convert.ToInt32(Request.QueryString["Role"].ToString());
either Request is null OR QueryString["Role"] is returning null.
Share the stack trace for more clear answer.

NullRefrenceException was unhandled by user code

Code below is placed in page_Load. How I should handle this to bypass UrlReferrer when you enter page directly first time and there is no referrer?
What I am missing here?
if (HttpContext.Current.Request.UrlReferrer.AbsoluteUri != null)
{
urlReferer = HttpContext.Current.Request.UrlReferrer.AbsoluteUri.ToString();
}
else
{
urlReferer = "";
}
Just check UrlReferrerfor null:
if (HttpContext.Current.Request.UrlReferrer != null
&& HttpContext.Current.Request.UrlReferrer.AbsoluteUri != null)
{
urlReferer = HttpContext.Current.Request.UrlReferrer.AbsoluteUri.ToString();
}
else
{
urlReferer = "";
}
Who says the client passed by the referrer in the HTTP request?
Check if UrlReferrer is null first
if (HttpContext.Current.Request.UrlReferrer != null)
{
urlReferer = HttpContext.Current.Request.UrlReferrer.AbsoluteUri.ToString();
}
else
{
urlReferer = "";
}
Why not this way much cleaner than checking nulls
private void Page_Load()
{
if (!IsPostBack)
{
if (HttpContext.Current.Request.UrlReferrer != null)
{
urlReferer = HttpContext.Current.Request.UrlReferrer.AbsoluteUri.ToString();
}
else
{
urlReferer = "";
}
}
}
I believe you need to check if HttpContext.Current.Request.UrlReferrer != null.
If UrlReferrer is null, then the test to AbsolutUri will fail.
Try initially testing UrlReferrer for null, this will probably correct the issue.
Use your debugger. If you're running this out of visual studio, than you might be brought to a debugger window when the exception is thrown. There are multiple tabs at the bottom of the debugger including "Locals" and "Watch" you can use those to see what variables are being stored.
If the above code is indeed what's causing the problem than
HttpContext.Current.Request.UrlReferrer.AbsoluteUri
or
HttpContext.Current.Request.UrlReferrer
or
HttpContext.Current.Request
or
HttpContext.Current
or
HttpContext
is set to null

Object reference not set to an instance of an object

Hai,
In my code while executing a function i got regularly the exception error as "Object reference not set to an instance of an object"
The function exceuting is as follows
private void PageHeaderSetting(Graphics g)
{
try
{
DataTable dtPageHeader=new DataTable() ;
dtPageHeader = ds.Tables["Page Header"];
if (dtPageHeader.Rows.Count != 0)
{
foreach (DataRow dr in dtPageHeader.Rows)
{
if (dr.ItemArray[0].ToString() != "")
PageHeaderText = dr.ItemArray[0].ToString();
else
PageHeaderText = "";
if (dr.ItemArray[1].ToString() != "")
PageHeaderFont = (Font)dr.ItemArray[1];
else
PageHeaderFont = new Font("Tahoma", 18, FontStyle.Bold, GraphicsUnit.Point);
if (dr.ItemArray[2].ToString() != "")
PageHeaderFormat = AlignmentSetting(dr.ItemArray[2].ToString());
else
PageHeaderFormat = AlignmentSetting(Convert.ToString(Alignment.Left));
if (dr.ItemArray[3].ToString() != "")
PageHeaderColor = (System.Drawing.Color)dr.ItemArray[3];
else
PageHeaderColor = Color.Black;
PageFooterText = Word_Wrap(PageHeaderText, PageHeaderFont, g, 0);
PageHeader(g);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
How can i solve this.Can anybody help me?
From the second line i got the exception error
means after declaring the datatable and putting the ds.Tables in it from there erroe occurs
This exception means you're trying to call a method on a null object. The exception should have given you a stack trace with the line number it was thrown at; this'll help you pin it down a bit. You could also try debugging it in visual studio and see where the exception is thrown & see what is null.
Instead of using ToString() to check if you have a value in the ItemArray you should check the actual value. Check for ItemArray[0] == null and ItemArray[0] == DBNull.Value.
Edit:
From your comment it seems that there may not be any data table named "Page Header" in your data set.
Try to add a null check to your DataTable object after the line dtPageHeader = ds.Tables["Page Header"];
Something like this:
if (dtPageHeader == null)
{
// There is no table named Page Header
}
Look at the line number in the exception.
Your code has numerous chained calls, which is a common source of this exception. If either of these chained properties returns null, the "next" call in the chain will fail with a NullReferenceException.
One of this could be true:
ds is null
A Value on a columun in dtPageHeader is null

Categories