So I'm trying to store fields from a text file into an array. But when I reach the line
data = record.Trim().Split('*');
I get an error saying "Object reference not set to an instance of an object."
public bool matchCustomer(string accountID, string record)
{
String[] data = new String[5];
data = null;
data = record.Trim().Split('*');
this.accountNumber = data[0];
if (accountID == this.accountNumber)
{
return true;
}
else
{
return false;
}
}
Here is where the method is called:
public bool findCustomer(string accountNumber)
{
string record = Global.currentFile.getNextRecord(ref endOfFile);
bool okay = Global.customer.matchCustomer(accountNumber, record);
return okay;
}
Here is getNextRecord:
public string getNextRecord(ref Boolean endOfFileFlag)
{
string nextRecord;
endOfFileFlag = false;
nextRecord = reader.ReadLine();
if (nextRecord == null)
{
endOfFileFlag = true;
}
else
{
recordReadCount += 1;
} // end if
return (nextRecord);
} // end getNextRecord
First, you can simplify your code by replacing:
String[] data = new String[5];
data = null;
data = record.Trim().Split('*');
with just a single line:
string[] data = record.Trim().Split('*');
This is a correct statement, because you don't know the max index (elements) of the string[] array returning by Split() function.
Second, make sure that record!=null, and also it has a string containing "*" characters used as delimiter in Split() function.
Let's look at this line of code
data = record.Trim().Split('*');
If a NullReferenceException occurred here, that means you must be calling a method on a null object. In this case, the only possible object is record.
Now we know what is null, but why is it null? Let's look at this method:
public bool findCustomer(string accountNumber)
{
string record = Global.currentFile.getNextRecord(ref endOfFile);
bool okay = Global.customer.matchCustomer(accountNumber, record);
return okay;
}
Apparently you are using the return value of getNextRecord to call matchCustomer. This means that getNextRecord must return be returning null! So let's find out why getNextRecord returns null:
public string getNextRecord(ref Boolean endOfFileFlag)
{
string nextRecord;
endOfFileFlag = false;
nextRecord = reader.ReadLine();
if (nextRecord == null)
{
endOfFileFlag = true;
}
else
{
recordReadCount += 1;
} // end if
return (nextRecord);
} // end getNextRecord
If the method return nextRecord, that means nextRecord is null. And how did you get nextRecord? reader.ReadLine!
So the ultimate reason why record is null is that reader.ReadLine is null.
To avoid this exception, you need to first check whether record is null, then call the method on it:
if (record != null) {
data = record.Trim().Split('*');
} else {
// do other stuff
}
In C# 6, this can be simplified to
data = record?.Trim().Split('*');
If record is null, data will be null too!
Also, note that this code is redundant:
String[] data = new String[5];
data = null;
You are creating a bunch of strings and then setting the array to null. What's the point? So you can just remove that, and change the next line to:
string[] data = record?.Trim().Split('*');
Related
I want to download a file via Results.File(). It works when executing it in the main method (app.MapGet), however returning it in a different method does do nothing. The line where it should send the file is executed in the Debugger, however it does not return, but jumps back to the main method to execute the last return (The one that never should be executed). This last return does indeed return a result.
I have also used several methods like Result.BadRequest(), however nothing is executed when it is not in the main method.
I saw people using IResult as return method but I am not sure whether this is even right.
My guess is maybe the wrong return type or executing a Task or so.
Whole methods:
app.MapGet("/", (HttpContext context) =>
{
if (context.Request.Query.ContainsKey("amount"))
{
if (context.Request.Query["amount"].Count > 1)
{
return Results.BadRequest(new { Error = "The query parameter 'amount' may only be used once." });
}
if (int.TryParse(context.Request.Query["amount"], out int amount))
{
if (amount <= 0)
{
return Results.BadRequest(new { Error = "The specified amount must be greater or equal to 1." });
}
var list = new List<string>();
for (int i = 0; i < amount; i++)
{
list.Add(Ulid.NewUlid().ToString());
}
CheckIfDownload(context, (list, null));
return Results.Json(new { Ulids = list });
}
else
{
return Results.BadRequest(new { Error = "The specified amount is not a valid number." });
}
}
string ulid = Ulid.NewUlid().ToString();
CheckIfDownload(context, (null, ulid));
return Results.Json(new { Ulid = ulid });
});
static IResult? CheckIfDownload(HttpContext context, (List<string>? list, string? single) ulidListOrSingle)
{
if (context.Request.Query.ContainsKey("download"))
{
if (context.Request.Query["download"].Count > 1)
{
return Results.BadRequest(new { Error = "The query parameter 'download' may only be used once." });
}
if (context.Request.Query["download"] == "" || (bool.TryParse(context.Request.Query["download"], out bool download) && download))
{
if (ulidListOrSingle.list != null)
{
return SendJsonFile(JsonSerializer.Serialize(ulidListOrSingle.list));
}
if (ulidListOrSingle.single != null)
{
return SendJsonFile(JsonSerializer.Serialize(ulidListOrSingle.single));
}
return Results.BadRequest(new { Error = "An unknown error occurred." });
}
}
return null;
}
static IResult SendJsonFile(string data)
{
byte[] buffer = Encoding.UTF8.GetBytes(data);
var stream = new MemoryStream(buffer);
return Results.File(stream, "application/json", $"UlidGenerator_{DateTime.Now:MM-dd-yyyy_HH-mm-ss}.json");
}
when you inline an entire method block (not just a single expression), you must return what you want to be the output of the block. In your case you are not capturing the result of SendJsonFile to return it:
app.MapGet("/download", () =>
{
string data = "json data";
var result = SendJsonFile(data);
return result;
});
I am building a AWS lambda function .net core.
The issue I am encountering is, when there is no data in the row / column of the datatable I still get a count of one, in turn getData != null && getData.Count() > 0 defaults true and then throws a NullRefrenceError since the value is null when it goes to the loop, I have tried checking for multiple null types in datatable with them still defaulting to true.
Is there another way to check for nullable values, to avoid the assignment causing the error in a datatable column / row.
public object emailGets ( AType invoiceNum, ILambdaContext context )
{
Connection conn = new Connection();
try
{
string query = "SELECT QUERY";
conn.getData(query);
DataRow[] getData = conn.Dt.Select();
if(getData != null && getData.Count() > 0)
{
foreach (var item in getData)
{
string yourItem = item.Field<String>("email").ToString();
}
return new userData { email = yourItem};
}
else
{
return new userEmailAddress { email = null};
}
} catch ( Exception e )
{
throw e;
}
}
}
public class userEmailAddress
{
public string email { get; set; }
}
ToString() will throw a NullReferenceException when the source is null. So when you do
string yourItem = item.Field<String>("email").ToString();
and the item.Field<String>("email") part returns null, you'll get that exception.
Luckily, that ToString() call is redundant, so you can simply remove it and just have:
string yourItem = item.Field<String>("email");
Keep in mind that yourItem can now be null here.
I have a class called Line that stores bunch of information including the ID of the Line(I have a list of lines). I am writing this information in a CSV file and I want to check if the first character of my ID has changed (hopefully to a greater number). This change signifies a new folder.
Here is what I have tried:
public bool IsNewFile (Line ln)
{
int newID = ln.getID()[0];
int oldID = 0;
if (newID != oldID)
{
oldID = newID;
return true;
}
else
{
oldID = newID;
return false;
}
}
Here is my store to csv method:
public void csvWriter (Line ln, StreamWriter stream)//Writes List to CSV
{
//some code here
if (IsNewFile(ln))
{
//MAGICAL LINE
}
else
{
//NOT MAGICAL LINE
}
stream.WriteLine(printLine);
}
here is getID()
public string getID()
{
return id;
}
With the current code I print MAGICAL LINE every time! What am I doing wrong?
You're always checking if the newID is != 0 because you always initialize oldID to 0. You should store the oldID in your Line class because as of now, setting oldID = newID will do nothing as those variables will get destroyed when the function returns its boolean.
public bool IsNewFile (Line ln)
{
int newID = ln.getID()[0];
int oldID = ln.getOldID()[0];
if (newID != oldID)
{
ln.oldID = newID;
return true;
}
else
{
ln.oldID = newID;
return false;
}
}
I'm not sure you are giving us enough information but oldID is always 0. You need to store oldID and compare it to newID somewhere.
I designed my webpage to read a data string then display the results on labels in an html table. I am attempting to highlight the row that my database reads as a current order. My only problem is only one record is set to be active but they all highlight as if they were active. I use an array to set my data and I also use the label to get the ID I need (all is in code below). I have posted my method and where I use it in the asp page load. How can I fix my method to return correctly?
The implementing of the method in page load
if (lineData.IsCurrentOrderFind(L68.Text))
{
myTable.Rows[1].Cells[0].BgColor = "#FE2E2E";
myTable.Rows[1].Cells[1].BgColor = "#FE2E2E";
myTable.Rows[1].Cells[2].BgColor = "#FE2E2E";
myTable.Rows[1].Cells[3].BgColor = "#FE2E2E";
myTable.Rows[1].Cells[4].BgColor = "#FE2E2E";
}
Here is method that label above gets passed to
public bool IsCurrentOrderFind(string itemNumber)
{
StringBuilder sqlString = new StringBuilder();
sqlString.Append("SELECT * ");
sqlString.Append("FROM WorkOrder ");
sqlString.Append("WHERE LineNumber = " + ConfigurationManager.AppSettings["Line"] + " AND LineCompleted = 0 AND (ScaleGroup LIKE '%1' OR ScaleGroup LIKE '%3') ");
sqlString.Append(" AND CaseGenNum6 = #CaseGenNum6");
SqlDataReader reader = null;
SqlConnection dbConn = App_Code.DBHelper.getConnection();
SqlParameter[] parameters = new SqlParameter[] { new SqlParameter("#CaseGenNum6", itemNumber) };
try
{
reader = App_Code.DBHelper.executeQuery(dbConn, sqlString.ToString(), parameters);
while (reader.Read())
{
IsCurrentOrder = (reader["IsCurrentOrder"] != DBNull.Value && !string.IsNullOrEmpty(reader["IsCurrentOrder"].ToString())) ? true : false;
}
reader.Close();
reader.Dispose();
dbConn.Close();
dbConn.Dispose();
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (dbConn != null)
{
try { dbConn.Close(); dbConn.Dispose(); }
catch { }
}
if (reader != null)
{
try { reader.Close(); reader.Dispose(); }
catch { }
}
}
if (IsCurrentOrder == true) I realize this is not necessary
{
return true;
}
else
{
return false;
}
}
The problem could be with this expression:
!string.IsNullOrEmpty(reader["IsCurrentOrder"].ToString())
Instead of calling ToString(), try simply casting it to a string:
!string.IsNullOrEmpty((string)reader["IsCurrentOrder"])
Possibly even better (the previous line might throw an exception if it's not really a string):
!string.IsNullOrEmpty(reader["IsCurrentOrder"] as string)
The reason being is that if the string is really null, calling ToString() will return a non-null string "null".
IsCurrentOrder is not declared locally. It seems to be declared at a higher scope. When you enter this function, nothing is initializing the variable (back to false). So, it is remaining at its last setting. Try this code instead:
public bool IsCurrentOrderFind(string itemNumber)
{
bool IsCurrentOrder = false;
//and the rest of your source code
the line
IsCurrentOrder = (reader["IsCurrentOrder"] != DBNull.Value && !string.IsNullOrEmpty(reader["IsCurrentOrder"].ToString())) ? true : false;
}
It's not actually checking the value of the field, only that it's not null or empty.
Try
if(
(reader["IsCurrentOrder"] != DBNull.Value
&&
!string.IsNullOrEmpty(reader["IsCurrentOrder"].ToString()))
)
{
IsCurrentOrder = reader["IsCurrentOrder"];
}
else
IsCurrentOrder = false;
I think there is a lot of refactoring you could do to this method though that will simplify the logic.
Am running asp.net application with c#.Am using gridview to update and delete the columns.deleting is working fine.if am clicking the update button i got
System.NullReferenceException: Object reference not set to an instance of an object.
My code is;
protected bool IsRowModified(GridViewRow row)
{
int currentID;
string currentName;
string currentLocation;
currentID = Convert.ToInt32(GridView1.DataKeys
[row.RowIndex].Value);
currentName = ((TextBox)row.FindControl
("txtName")).Text;
currentLocation = ((TextBox)row.FindControl
("txtLocation")).Text;
**System.Data.DataRow newRow = originalTable.Select
(String.Format("ID = {0}", currentID))[0];** //got error in this line
if (!currentName.Equals(newRow["Name"].ToString()))
{ return true; }
if (!currentLocation.Equals(newRow["Location"].ToString()))
{ return true; }
return false;
}
Either originalTable is null, or originalTable.Select(...) is returning null.
Could it be that you've deleted the underlying data from originalTable and not updated the UI?
An alternative method might be to use the DataItem property of the GridViewRow parameter:
protected bool IsRowModified(GridViewRow row)
{
string currentName = ((TextBox)row.FindControl("txtName")).Text;
string currentLocation = ((TextBox)row.FindControl("txtLocation")).Text;
DataRow newRow = (DataRow)row.DataItem;
if (!string.Equals(currentName, newRow["Name"].ToString()))
{
return true;
}
if (!string.Equals(currentLocation, newRow["Location"].ToString()))
{
return true;
}
return false;
}
My guess is that your currentID variable is null or empty. You should check your values for null or empty before you try to use them.
if(!String.IsNullOrEmpty(currentID))
{
// Continue processing
}