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();
}
Related
Tell me please, how can I do so that would only give the last meaning of this search.
At the moment, about 15 MessageBox.Show is opened.
How to make it so that only the latter would show?
For the fifth hour I am suffering with different variations. Nothing happens.
TextReader tr = null;
try
{
File.Copy(SteamLogFilePath, tmpFile, true);
}
catch { }
try
{
tr = new StreamReader(tmpFile);
try
{
string line = null;
while (true)
{
line = tr.ReadLine();
if (line.Contains("RecvMsgClientLogOnResponse") && line.Contains("OK"))
{
tmpSplit1 = line.Split(')');
string SteamIdbrut = tmpSplit1[1];
tmpSplit1 = SteamIdbrut.Split(']');
string SteamIdnet = tmpSplit1[0].Replace(" : [", "");
long steam32 = Convert.ToInt64((GetFriendID(SteamIdnet)));
MessageBox.Show((FromSteam32ToSteam64(steam32)).ToString());
}
}
}
catch { }
}
catch { }
if (tr != null)
tr.Close();
You could use this instead:
string lastLine = File.ReadLines(tmpFile)
.Where(line => line.Contains("RecvMsgClientLogOnResponse") && line.Contains("OK"))
.LastOrDefault();
// rest of code to create the MessageBox
This code replaces all of your code from 2nd try to tr.Close();.
I'm trying a booking system, I want to put controls on the booking aspect. I want to use If and then cases. I want to control in such a way that if number of booking is 4, then it will throw an exception and stop inserting in the database.
public ApiResult<TimeModelExtended> SaveBooking(Booking booking)
{
AchimotaGCDb repo = new AchimotaGCDb();
var result = new ApiResult<TimeModelExtended>();
try
{
booking.PlayDate = getPlayDate(booking.RefCode);
Int16 nb = getNbBooked(booking.RefCode);
if (nb == 4)
{
Exception ex = new Exception();
result.Successfull = 0;
result.InternalError = ex.Message;
result.Error = "Booking slot is full";
}
else if (nb == 0)
{
booking.BookingStatus = 1;//Booked already
}
else
{
booking.BookingStatus = 0;//Reservation already
}
repo.Insert(booking);
result.Successfull = 1;
result = GetOneteeTime(booking.RefCode);
}
catch (Exception ex)
{
result.Successfull = 0;
result.InternalError = ex.Message;
result.Error = "Error from server";
}
finally
{
repo.Dispose();
}
return result;
}
help to solve that.
If you want to throw an exception, you need to really throw it:
if (nb == 4)
{
throw new Exception("Booking slot is full.");
}
But I don't think throwing an exception is a good idea. Throwing an exception and validation is a different thing.
Here is my suggestion:
if (nb == 4)
{
return result = new ApiResult<TimeModelExtended>()
{
Successfull = 0,
InternalError = "Other messages",
Error = ""Booking slot is full."
};
}
This will return as result message that nothing will continue unless you satisfy that nb != 4
I'm trying to return a value from a function. The function WcfProvider.MetalsPrices may throw an exception. I want to avoid it.
public IEnumerable<PriceOfMetal> GetPrice(int id, DateTime time)
{
bool condition = false;
DateTime timenew = time.AddDays(-1);
var allPrice = from c in db.PriceOfMetal
select c;
foreach (var i in allPrice)
{
if (i.Date.Date == timenew.Date && i.ListOfMetaL_Id==id)
{
condition = true;
}
}
try
{
if (condition == false)
{
var price = WcfProvider.MetalsPrices(id, time, time).Tables[0].AsEnumerable()
.Select(
a =>
new PriceOfMetal()
{
Date = a.Field<DateTime>("Date"),
ListOfMetaL_Id = a.Field<int>("MetalId"),
Value = a.Field<System.Double>("Price")
})
.ToList().Single();
db.PriceOfMetal.Add(price);
db.SaveChanges();
}
}
finally
{
var all = from c in db.PriceOfMetal select c;
return all;
}
I want to return the value of the block finally. Is it possible? I get an error.
You have to decide whether your function should return normally or abnormally if an exception occurs inside.
If abnormally (your caller will see the exception):
try {
// do stuff
return answer;
}
finally {
// cleanup stuff
}
If normally, you need to handle the exception:
try {
// do stuff
}
catch {
// recover stuff
}
// cleanup stuff
return answer;
You can never put a return statement in a finally block, because finally runs when there is an uncaught exception, and when your function ends (abnormally) due to uncaught exception, there is no return value.
you may need a pattern like this
try
{
return here
}
catch(Exception ex)
{
// Catch any error
// re throw if you choose,
// or you can return if you choose
return here
}
finally
{
// allways do whats here
}
You might want to read a couple of the pages around here : try-catch-finally (C# Reference)
Just to build on this a bit more, Imagine if we could return within a finally block
You could have a nasty piece of code like below, which would be confusing at best
try
{
return 10;
}
catch (Exception e)
{
return 20;
}
finally
{
return 30;
}
What would the compiler return?
I'm sorry to say this but your question is vague and hard to answer. Your code looks over complicated. Anyway it's holiday time. Maybe below will help you along. No guarantees though.
public IEnumerable<PriceOfMetal> GetPrice(int id, DateTime time)
{
DateTime timenew = time.AddDays(-1);
var allPrice = from c in db.PriceOfMetal
select c;
where c.Date.Date == timenew.Date
and c.ListOfMetal_Id == id
if (!allPrice.Any())
{
try
{
var price = WcfProvider.MetalsPrices(id, time, time).Tables[0].AsEnumerable()
.Select(a =>new PriceOfMetal
{
Date = a.Field<DateTime>("Date"),
ListOfMetaL_Id = a.Field<int>("MetalId"),
Value = a.Field<System.Double>("Price")
})
.ToList().Single();
db.PriceOfMetal.Add(price);
db.SaveChanges();
}
catch
{
// Eating exceptions like this is really poor. You should improve the design.
}
}
return db.PriceOfMetal;
}
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.
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;
}
}
}