sistematically, but only on one PC, while executing this code:
using Microsoft.Ink;
...
Tablets allTablets = new Tablets();
int numTablet = allTablets.Count;
I get this exception.
System.ArgumentException: Valore non compreso nell'intervallo previsto. {In English --> Value not in the right range}
in Microsoft.Ink.InkTabletsClass.get_Count()
in Microsoft.Ink.Tablets.get_Count()
How could a COUNT throw this kind of exception?
Does it means that the Count method return a value that is not int?
Thanks.
How could a COUNT throw this kind of exception?
Because of some logic that is implemented in the getter of the Count property of the Tablets class. It is in the getter that the exception is thrown.
Does it means that the Count method return a value that is not int?
No. An int property can only return an int value or throw an exception. It can never return a value of any other type. The compiler enforces this.
I tried your code, and it works for me. That being said, I have encountered similar exceptions so many times before that I now make it a habit to check for null objects first. So, I would use:
Tablets allTablets = new Tablets();
int numTablet = 0;
if (allTablets != null)
numTablet = allTablets.Count;
To answer your question, for some reason new Tablets() returns null instead of an empty ICollection.
Related
Hi I have the following code:
log.Entry = (newEntry ?? "").Substring(0,Math.Min((newEntry ?? "").Length, 50));
log.Entry is a database field of nvarchar(50)
So I want to do is limit to max 50 chars but also have a null check so I don't try to run string-functions on null which might throw exceptions.(?)
My question is can the second (newEntry ?? "") be simplified by some sort of operator?
This is already evaluated once and might not need to be evaluated again.
I looking for a one-liner so it would be something like a lambda-style syntax. (but I guess not actual lambda).
log.Entry = newEntry?.Substring(0, Math.Min(newEntry.Length, 50)) ?? "";
Or drop ?? "" at the end if you want log.Entry to be null if newEntry is null:
log.Entry = newEntry?.Substring(0, Math.Min(newEntry.Length, 50));
You could always do the following:
var logEntry = new string(newEntry?.Take(50).ToArray());
To bear in mind:
new string(null) will creat an empty string "".
Enumerable.Take(n) will take the first n elements of the sequence. If there are less that n elements, then it will take the whole sequence.
Performance is significantly worse than other solutions, where it is not necessary to enumerate the string.
You can simply use
newEntry?.Substring(0, Math.Min(newEntry.Length, 50))
This way, as soon as newEntry is null, the call to SubString(...) is never invoked and the entire expression is evaluated to null. Once SubString() is reached, you no longer have to check for nullity and you can settle with Math.Min(newEntry.Length, 50).
I guess:
newEntry = newEntry ?? "";
og.Entry = newEntry.Substring(0,Math.Min(newEntry.Length, 50));
Almost all the rest of answers are taking advantage of the Safe Navigation Operator ?.,that was introduced in C# 6 if i'm not wrong. But the tag in your question is C# 4.0, so I think this would work for you:
log.Entry= (newEntry!=null ? newEntry.Substring(0, Math.Min(newEntry.Length, 50)):"");
This uses the ? Operator
Though other answers produce valid results, they tend to produce repetitive code which hides your intent (also there might be performance issues if you'll each time create LINQ iterators and instantiate new strings from characters).
For strings trimming I usually use extension methods:
public static string TrimTo(this string value, int maxLength)
{
if (value == null || value.Length <= maxLength)
return value;
return value.Substring(0, maxLength);
}
They give you clean and readable code wich is easy to reuse in several places:
log.Entry = newEntry.TrimTo(50);
Consider also to add ellipsis to the end of trimmed string.
I have a System.Data.DataSet and 1 single table in it. The table has many columns.
In a certain event handler, I am setting a decimal value for one of the fields, in a data row which is already existing (at the time of setting).
In a very rare case, I am getting a ArgumentOutOfRangeException exception.
Message: System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
Call Stack:
at System.ThrowHelper.ThrowArgumentOutOfRangeException()
at System.Collections.Generic.List`1.get_Item(Int32 index)
at System.Data.RecordManager.NewRecordBase()
at System.Data.DataTable.NewRecord(Int32 sourceRecord)
at System.Data.DataRow.BeginEditInternal()
at System.Data.DataRow.set_Item(DataColumn column, Object value)
at CPITS.Data.OrdersRow.set_ExecutionPrice(Decimal value)
Strange thing is, this is happening from the code which the framework has generated (Of course, I didn't write the Setter for the DataColumn).
Can you please help me understand & fix this problem?
EDIT
Below is the code where I am setting value:
void ibclient_OrderStatus(object sender, OrderStatusEventArgs e)
{
Data.OrdersRow drOrders = data.Orders.FindByOrderId(e.OrderId);
if (drOrders != null)
{
drOrders.FilledQuantity = e.Filled;
drOrders.ExecutionPrice = e.AverageFillPrice; //Sporadic Exception when setting a decimal value
}
}
Here is de decompiled code of RecordManager.NewRecordBase
internal int NewRecordBase()
{
int num;
if (this.freeRecordList.Count != 0)
{
num = this.freeRecordList[this.freeRecordList.Count - 1];
this.freeRecordList.RemoveAt(this.freeRecordList.Count - 1);
}
else
{
if (this.lastFreeRecord >= this.recordCapacity)
this.GrowRecordCapacity();
num = this.lastFreeRecord;
++this.lastFreeRecord;
}
return num;
}
as you can see, the only case where you could have a "index out of bounds" exception is here:
num = this.freeRecordList[this.freeRecordList.Count - 1];
since there DataTable is not thread safe, we could easily imagine a scenario where a record is removed by another thread before accessing the freeRecordList[..] but after having accessed to this.freeRecordList.Count.
In this case, freeRecordList.Count would have changed in the meanwhile => index out of bounds exception.
Thus, if I were you, I would try to find a concurrency issue (the fact that it happens in rare cases is another argument !)
Check the number of decimal places you are allowing in your table and check how many decimals the number you are committing has.
This exception can be thrown if the number of decimals is out of range.
DataTable.GetErrors Method
Gets an array of DataRow objects that contain errors.
I have a tricky question that has been befuddling me for a while. I have the following code declaration...
namespace ESEGURCI.WEB.BusinessLogicLayer.Commons
{
public static class ParameterUtilities
{
public enum ParameterEnum
{
MAX_LOGIN_ATTEMPTS,
AUDIT_MODIFICATIONS
}
}
}
and I call the code like so "ParameterUtilities.ParameterEnum.MAX_LOGIN_ATTEMPTS" Problem is once every full moon I get the error "object reference not set to an instance of an object" on this line... It's like the code only works 99.9% of the time...
The only thing that occurs to me is that since the enum is a value type that there can be a chance that the enum is null when the static class is called... But I can't find any documentation on this behavior...
Can someone enlighten me why this happens? I know I should probably remove the enum out of the static class, and declare the enum as standalone but I'd like to know why this is happening first...
Thanks,
S
Update
Ok, to everyone who asked for more code, the following is the full function where the error occurs...
public static int GetPageSize(int companyId)
{
int pageSize = 0;
// error happens bellow this line
ESEGURCI.WEB.BusinessLogicLayer.Entities.Parameter parameter = ESEGURCI.WEB.BusinessLogicLayer.Entities.Parameter.GetParameter(ParameterUtilities.ParameterEnum.AUDIT_MODIFICATIONS.ToString(), companyId);
// error happens above this line
int.TryParse(parameter.Value, out pageSize);
return pageSize;
}
ParameterUtilities.ParameterEnum.MAX_LOGIN_ATTEMPTS won't ever throw a null reference exception, no matter what the Moon looks like. The error is probably triggered by an other instruction on the same line (assignment to a variable?).
An enum can't be null.
Split up the line as in the listing below and see which statement throws the exception. I bet it happens somewhere in Parameter.GetParameter():
using ESEGURCI.WEB.BusinessLogicLayer.Entities;
// ...
var auditModifications =
ParameterUtilities.ParameterEnum.AUDIT_MODIFICATIONS.ToString();
var parameter = Parameter.GetParameter(auditModifications, companyId);
Enum (and any other type) cannot have null value, because it isn't a value it is a type.
The exception is thrown by something else.
As already stated your enum will not be where the error is coming from. Based on your update, I would say the NRE is most likely coming from your GetParameter method.
I use C# and ASP.NET.
I use this code pasted below in my application with no problems, but I would like to know if there is a better way to achieve the same result.
What I need to do:
I need set a variable int imageId using a Loop.
Variable imageId it is outside the Loop so can be used in other part of my code.
My questions:
Why if I use just int imageId; the compiler complain (ERROR: Use of unassigned local variable 'imageId' )?
I use a nullable int type instead of an int imageId = 0; so I can set it on a null value .. (to me seems semantically correct) would you recommend that? If no why.
What is you favorite approach to this kind of problem?
Thanks guys for your support!!!!
int? imageId = null;
foreach (DictionaryEntry valueEntry in e.Keys)
{
if (valueEntry.Key.Equals("ImageContentId"))
{
imageId = Convert.ToInt32(valueEntry.Value.ToString());
break;
}
}
Please give me a sample of your code thank!
You could use the IOrderedDictionary method Contains. This would allow you to drop the loop construct altogether. e.g.
if( e.Keys.Contains("ImageContentId") )
{
imageId = Convert.ToInt32( e.Keys["ImageContentId"].ToString() );
}
Also if you know that the Value is a string you might be interested in the Int32.TryParse method e.g.
int imageId ;
if( Int32.TryParse(e["ImageContentId"].ToString(), out imageId ) )
{ }
The only reason that you would want to use an int? is if the data you're manipulating could be uninitialised. If you're parsing data and it's garbage you have 2 options:
(NB: This assumes that you don't want to be throwing Exceptions RE the bad data).
1) Use a default value - This has the benefit of being inherently tolerant of bad data.
2) Use the int? construct - This has the advantage of informing the rest of the code that the data in known to be bad and ensures that they are designed to cope with null values.
As for which is better... that can only be answered within the constructs of the system. If you're performing interop with external dll's that don't support nullable types then the decision is pretty clear!
As for the compiler error: if you're initializing imageId within an if statement there will be occasions where the initialization branch won't be taken e.g. a bad value. To ensure that imageId is always initialized, the compiler will force you to initialize it outside of a conditional code path. Generally I always try and initialize a variable when I declare it. e.g.
int imageId = 0;
Answers for your Questions
All value type in .net are implemented as structure. And all structure must be initialized before usage.
If you are interested in checking if that value exists or not then nullable is a correct choice. Else no issues with int imageId = 0
You can use below code
int imageId = 0;
if( e.Contains("ImageContentId") )
{
//If you are sure value is int
imageId = (int)e["ImageContentId"];
}
you could use Linq to find the entry:
var foundKey = e.Keys.FirstOrDefault(k => k.Key.Equals('ImageContentId'));
Then the ternary expression to get the value:
int? imageId = foundKey == null ? (int?)null : Convert.ToInt32(foundKey.Value);
However, what type is the Value? If you're sure it's an int, you can cast it, rather than calling Convert.ToInt32. Also, Convert.ToInt32 returns 0 for some cases where you might want (int?)null.
My favorite approach to this kind of problem is not to rely on overloading the value-holding variable with information regarding whether a value was found. I do this explicitly.
bool value_present = false;
int imageId;
foreach (DictionaryEntry valueEntry in e.Keys)
{
if (valueEntry.Key.Equals("ImageContentId"))
{
value_present = true;
imageId = Convert.ToInt32(valueEntry.Value.ToString());
break;
}
}
And then test value_present before using imageId.
That said, and as others have noted, this is crazy.
Don't loop like this, just call e.Keys.Contains()
Don't convert to a string and then back to an int. If it's an int, cast it.
Hello
I'm having an error with this code:
"The out parameter 'o_BlockingSquaresArr' must be assigned to before control leaves the current method"
Now this error paints each return statement of each method apart from the last one with red..
I don't understand what is the problem regarding my specific code
Please help me,
Thanks in Advance
internal bool isLegalMove(Square i_Move, out List<Square> o_BlockingSquaresArr)
{
bool result;
if (m_GameBoard[i_Move.RowIndex, (int)i_Move.ColIndex].Coin != null)
{
result = false;
m_MessageBuffer = "You have enterd a square which is already
occupied, please try again...";
m_ErrorFlag=true;
}
else
{
result = checkIfThereIsAtLeastOneSeqInOneDirection(i_Move,out o_BlockingSquaresArr);
}
return result;
}
internal bool checkIfThereIsAtLeastOneSeqInOneDirection(Square i_Move, out List<Square> o_BlockingSquaresArr)
{
const int k_EightDirections = 8;
bool isSequenceFound, finalRes = false;
for (int i = 1; i <= k_EightDirections; i++)
{
isSequenceFound = checkOpponentSequenceInDirection(i_Move, (eDirections)i, out o_BlockingSquaresArr);
if (isSequenceFound)
{
finalRes = true;
}
}
return finalRes;
}
internal bool checkOpponentSequenceInDirection(Square i_Move, eDirections i_Direction, out List<Square> o_BlockingSquaresArr)
{
//I've shortened this code only relevant things
Square o_AdjacentSquare = new Square();
adjacentCoin = doSwitchAndRetrieveAdjacentCoin(i_Move, i_Direction, out o_AdjacentSquare);
// ...
if (isThereAnOpponentSequence)
{
o_BlockingSquaresArr.Add(o_AdjacentSquare);
}
return isThereAnOpponentSequence;
}
As the compiler error says, an out parameter has to be definitely assigned before any non-exceptional return of a method. I can't see any assignment to o_BlockingSquaresArr anywhere. Why are you even declaring it as an out parameter to start with?
An out parameter must be assigned a value before the method returns. In your isLegalMove method, o_BlockingSquaresArr is only assigned in the else block, so the compiler detects there are some cases where it is not initialized. You must make sure that all code paths in the method assign a value to o_BlockingSquaresArr before returning
You need to assign something to the out parameter in every execution path. In your case, you forget that in one case. Simply assign a default value of the beginning of the method so you don't run into it.
I can't tell you where as you didn't include the method name it is happening in.
In the IsLegalMove function, you need to assign a value to the o_BlockingSquaresArr variable
You need to assign something to out parameters in every (normally terminating) codepath. And you don't do that.
For example in some functions you only assign to the parameter inside the for-loop. And if the loop has 0 iterations this will never happen.