Keynotfound exception - c#

Keynotfound exception
public int getLastUniqueID()
{
int lastID = 0;
IsolatedStorageSettings uc = IsolatedStorageSettings.ApplicationSettings;
List<sMedication> medicationList = (List<sMedication>)uc["medicationList"];
foreach (sMedication temp in medicationList) {
lastID = temp.UniqueID;
}
return lastID;
}
It is happening on the following line:
List<sMedication> medicationList = (List<sMedication>)uc["medicationList"];

As the error indicate that key was not found in the dictionary before accessing the value check if the key exists or not
if(uc.Contains("medicationList"))
{
// your code here
}

You're going to run into problems with that approach because, if the key "medicationList" isn't there in the retrieved Application Settings, then it'll throw an exception like you have witnessed.
Try the following:
uc.TryGetValue<List<sMedication>>("medicationList", out medicationList)
if (medicationList != null)
{
foreach(sMedication temp in medicationList)
{
lastID = temp.UniqueID;
return lastID;
}
}
else
{
// handle the key not being there
}

Related

Issue with checking if ID in class has changed

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.

How to fix a boolean method that returns true everytime asp.net

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.

handle system.Format Exception C#

In my app, I don't understand how do handle system.format Exception. See below code
public Harvest_Project(XmlNode node)
{
this._node = node;
this._name = node.SelectSingleNode("name").InnerText;
this._created_at = storeTime(node.SelectSingleNode("created-at").InnerText);
this._updated_at = storeTime(node.SelectSingleNode("updated-at").InnerText);
this._over_budget_notified_at = storeTime(node.SelectSingleNode("over-budget-notified-at").InnerText);
this._latest_record_at = storeTime(node.SelectSingleNode("hint-latest-record-at").InnerText);
this._earliest_record_at = storeTime(node.SelectSingleNode("hint-earliest-record-at").InnerText);
this._billable = bool.Parse(node.SelectSingleNode("billable").InnerText);
try
{
this._id = Convert.ToInt32(node.SelectSingleNode("id").InnerText);
this._client_id = Convert.ToInt32(node.SelectSingleNode("client-id").InnerText);
this._budget = float.Parse(node.SelectSingleNode("budget").InnerText);
this._fees = Convert.ToInt32(getXmlNode("fees", node));
}
catch (FormatException e)
{
Console.WriteLine();
}
catch (OverflowException e)
{
Console.WriteLine("The number cannot fit in an Int32.");
}
this._code = node.SelectSingleNode("code").InnerText;
this._notes = node.SelectSingleNode("notes").InnerText;
}
Here in, try and catch blocks, all the nodes takes int values but, as _fees takes "0" value. It's showing me format exception. I just want my nodes doesn't show empty string. I want to handle this exception. That means, it should not throw exception at line "this._fees = Convert.ToInt32(getXmlNode("fees", node));" because it's returning int value which I want.
How could I achieve that?
You can avoid control-flow programming with try/catch mechanisms generally by using TryX methods; in your case, int.TryParse, such that:
int output;
if (int.TryParse(input, out output)) {
// success
} else {
// failure
}
you haven't posted the xml, and I can't find the getXmlNode function
but I beleive that it returns XmlNode that have a content other then just int (else, you would use the InnerText property.
do try this:
XmlNode fees = getXmlNode(...)
var curr = fees.FirstChild;
int _fees = 0;
while (curr != null) {
_fees += (Convert.ToInt32(curr.InnerText);
curr = curr.NextSibling();
}

C#: Selecting a row in DataGridView with parameters

I am having a DataGridView and an Add New Entry button. Each time I add a new entry to the database, I want the program to select the row of the new entry in the DataGridView. After clicking on the Add New Entry button, the below function will be called, with parameters of studentName and date passed to the function. The name of the DataGridView is dvgPontengHistory.
But there is an exception thrown:
Object reference not set to an instance of an object.
on this line:
if(r.Cells["student_name"].Value.ToString().Contains(studentName))
Below is the code:
private void selectRow(string studentName, string date)
{
int i = 0;
foreach (DataGridViewRow r in dgvPontengHistory.Rows)
{
if(r.Cells["student_name"].Value.ToString().Contains(studentName)) // error in this line
{
if (r.Cells["date"].Value.ToString().Contains(date))
{
dgvPontengHistory.Rows[i].Selected = true;
return;
}
}
i++;
}
}
Any tips on resolving this problem? Thanks.
Probably the case that student_name was null in on of the rows in the result set. That would cause ToString() to fail.
My guess is your update statement is putting null into your table.
Here is how you test:
(set breakpoints on the throw lines).
private void selectRow(string studentName, string date)
{
int i = 0;
foreach (DataGridViewRow r in dgvPontengHistory.Rows)
{
if (r.Cells["student_name"] == null) { throw("can't find cell"); }
if(r.Cells["student_name"].Value == null) { throw("cell has no value"); }
if(r.Cells["student_name"].Value.ToString().Contains(studentName)) // error in this line
{
if (r.Cells["date"].Value.ToString().Contains(date))
{
dgvPontengHistory.Rows[i].Selected = true;
return;
}
}
i++;
}
}
private void selectRow(string studentName, string date)
{
int i = 0;
foreach (DataGridViewRow r in dgvPontengHistory.Rows)
{
if(r.Cells["student_name"].Value == null) return;
if(r.Cells["student_name"].Value.ToString().Contains(studentName)) // error in this line
{
if (r.Cells["date"].Value.ToString().Contains(date))
{
dgvPontengHistory.Rows[i].Selected = true;
return;
}
}
i++;
}
}

Clean way to catch errors from Azure Table (other than string match?)

I'd like to get a list of all the Azure Table errors and figure out a clean way to handle them in a try...catch block.
For example, I'd like to not have to directly code and compare the InnerException message to String.Contains("The specified entity already exists"). What is the right way to trap these errors?
You could try looking at the values in the Response, rather that the inner exception. This is an example of one of my try catch blocks:
try {
return query.FirstOrDefault();
}
catch (System.Data.Services.Client.DataServiceQueryException ex)
{
if (ex.Response.StatusCode == (int)System.Net.HttpStatusCode.NotFound) {
return null;
}
throw;
}
Obviously this is just for the item doesn't exist error, but I'm sure you can expand on this concept by looking at the list of Azure error codes.
To handle errors while adding objects to a table you can use the following code:
try {
_context.AddObject(TableName, entityObject);
_context.SaveCangesWithRetries();
}
catch(DataServiceRequestException ex) {
ex.Response.Any(r => r.StatusCode == (int)System.Net.HttpStatusCode.Conflict)
throw;
}
As said in other answer you can find a list of TableStorage errors at: http://msdn.microsoft.com/en-us/library/dd179438.aspx
See my code here: http://blog.smarx.com/posts/testing-existence-of-a-windows-azure-blob. The pattern is to catch a StorageClientException, and then use the .ErrorCode property to match against the constants in StorageErrorCode.
Here is code that is provided in the Azure Table Whitepaper, but I'm not sure if this gives any value over smark's reply.
/*
From Azure table whitepaper
When an exception occurs, you can extract the sequence number (highlighted above) of the command that caused the transaction to fail as follows:
try
{
// ... save changes
}
catch (InvalidOperationException e)
{
DataServiceClientException dsce = e.InnerException as DataServiceClientException;
int? commandIndex;
string errorMessage;
ParseErrorDetails(dsce, out commandIndex, out errorMessage);
}
*/
-
void ParseErrorDetails( DataServiceClientException e, out string errorCode, out int? commandIndex, out string errorMessage)
{
GetErrorInformation(e.Message, out errorCode, out errorMessage);
commandIndex = null;
int indexOfSeparator = errorMessage.IndexOf(':');
if (indexOfSeparator > 0)
{
int temp;
if (Int32.TryParse(errorMessage.Substring(0, indexOfSeparator), out temp))
{
commandIndex = temp;
errorMessage = errorMessage.Substring(indexOfSeparator + 1);
}
}
}
void GetErrorInformation( string xmlErrorMessage, out string errorCode, out string message)
{
message = null;
errorCode = null;
XName xnErrorCode = XName.Get("code", "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata");
XName xnMessage = XName.Get ( "message", "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata");
using (StringReader reader = new StringReader(xmlErrorMessage))
{
XDocument xDocument = null;
try
{
xDocument = XDocument.Load(reader);
}
catch (XmlException)
{
// The XML could not be parsed. This could happen either because the connection
// could not be made to the server, or if the response did not contain the
// error details (for example, if the response status code was neither a failure
// nor a success, but a 3XX code such as NotModified.
return;
}
XElement errorCodeElement = xDocument.Descendants(xnErrorCode).FirstOrDefault();
if (errorCodeElement == null)
{
return;
}
errorCode = errorCodeElement.Value;
XElement messageElement = xDocument.Descendants(xnMessage).FirstOrDefault();
if (messageElement != null)
{
message = messageElement.Value;
}
}
}

Categories

Resources