I have been asked to find out why an ajax call doest work if date fields are left blank on a web form, finding out was easy, its because the VB function expects an object with a Date type.
I'm going to convert these values to Nullable(Of Date), but I'm reluctant as this is a class that's quite heavily used and I don't want to break anything else.
My thinking however is that everything calling this class must be sending in a correct Date or it would throw an error currently, so I should be ok.
As long as I check for a value using HasValue and get the date out using Value then I shouldn't have any problems, or is there something else I need to consider?
If you change every reference to use the Date's Value property it will be no worse than what you have now. Then you can add the HasValue checks where you need to.
Related
I'm using Authorize.net API and they require card expiration field to be formated as "yyyy-mm". We did that with this simple line of code:
expirationDate = model.Year.ToString("D4") & "-" & model.Month.ToString("D2")
and this absolutelly worked. I still have cards stored in the system that were saved using this method! But today I was testing something completelly unrelated, and wanted to add another card, and bam, this code exploded with this exception:
System.InvalidCastException: 'Conversion from string "D4" to type 'Integer' is not valid.'
Inner exception to that one is:
Input string was not in a correct format.
This just... doesn't make sense to me. Why in the world is it trying to convert format specifier (D4) into an integer? What input string? What in the world changed in two days?
The problem is that your are using a Nullable(Of Integer). This is a different structure that does not support the overloads of the ToString method a normal Integer has.
You can view the overloads of the Nullable structure here.
I suggest you use the GetValueOrDefault() method to get the proper Integer and also apply the value you expect in case the value is Nothing.
If it is impossible that a instance with a Nothing set for the year reaches this method you can simply use the Value property.
I still do not fully understand why you get this strange error message. Maybe you could check out what the actual method that is called is? Pointing at the method should give you that information. It can't be Nullable(Of Integer).ToString
Well, I found a workable solution and something of an answer thanks to #Nitram's comment. The type of Year/Month property has been changed from Integer to Integer?. Obviously, this isn't a very satisfying answer because I still don't understand why the nullable int can't be formatted, and yet the code compiles perfectly. The working solution for me has been using static format method on String as so:
expirationDate = String.Format("{0:D4}-{1:D2}", model.Year, model.Month)
This works fine even with nullable types.
Compare weirdness when working with LINQ and Entity Framework.
I want to retrieve an ID from my DB and I get this weird message.
I could simply fix it as you can see but I want to understand why this happens.
Question:
Why do I get this error message even if I check with "HasValue" or I use "FirstOrDefault"? It can't be null in my opinion but I obviously miss something.
Add .Value if you are 100% sure the Integer? has a value.
Why do I get this error message even if I check with "HasValue"
Entity Framework just uses the objects you give it. It can't create a new object where OPX_ isn't nullable.
the setOpxRights function presumably takes an Integer as a parameter and Option Strict On won't allow an Integer? to be implicitly converted to an Integer. If you are sure that it will always have a value, pass in cctUser.OPX_Rechte.Value
The compiler is not perfect, we can see that OPX_Rechte will have a value because of the where statment, but for the compiler you are just using a the object cctUser that have an Integer? and it needs an Integer.
When designing data tables in the .xsd designer in Visual Studio, there is a property that specifies what to do when the table encounters a null value:
The problem is, if the DataType is System.DateTime, I'm unable to return empty or nothing. It always throws an exception.
As I work around, I can do the following:
If(row.IsDateLastRecallPrintedNull, DateTime.MinValue, row.DateLastRecallPrinted)
But if the value is DbNull.Value, I'd rather just have it return that.
Using IsDateLastRecallPrintedNull isn't a workaround, it's the way it's intended to be used. If you use a nullable date, you can set this to nothing rather than DateTime.MinValue in your code. Alternatively you can change the datatype in the dataset to System.Object, and then you can select '(Nothing)' in the dropdown. Note that you can overtype the NullValue entry in the properties with another value that's appropriate for the data type, although it won't work if you enter DateTime.Minvalue - it'll appear to accept it, but then fail - but you can put in another magic number such as 01/01/1900.
All this is 'by design'.*
Using databinding sidesteps this quagmire to a great extent; if you're reading programmatically from the dataset then IsxxxNull is the way to go.
*I suspect this is too often a Microsoftism for 'we didn't finish it by ship date'
We have several projects in VB.Net, using .Net Framework 4 and Linq to Entities for many of our SQL queries. Moving to EF is a new shift for us (been using it for about 4-6 months) and has the backing of upper management because we can code so much faster. We still use a lot of stored procs, but we even execute those through Linq to Entities as well.
I'm hoping to clear some confusion up and I can't find a direct answer that makes sense. We have some queries where we want records where a specific field has a NULL value. These are simple select queries, no aggregates or left joins, etc. Microsoft recommends the query look something like this MSDN Link:
dim query = from a in MyContext.MyTables
Where a.MyField = Nothing
Select a
I have several projects where I do exactly this and it works great, no warnings in the IDE. Recently a new project was created by another developer and when he did his null check like above, we all get this warning in the IDE:
Warning 1 This expression will always evaluate to Nothing (due to null propagation from the equals operator). To check if the value is null consider using 'Is Nothing'.
Comparing the projects, option explicit and option strict are on for each one. If we ignore the warning, we get the exact record set we are looking for when the app runs. The warning goes away if I change the = sign to IS. But why did this warning appear in one project and not others? It's confusing when even on MSDN there are examples using the equals operator.
Generated column should be a Nullable(Of T)
So you can check if that field has value or not like this:
dim query = from a in MyContext.MyTables
Where Not a.MyField.HasValue
Select a
I believe what you're seeing here is that MyField is a Nullable(Of T) type. Likely a primitive Integer, Single, etc ...
The reason you're seeing this warning is because the compiler promotes the normal equality operator for the primitive type to the Nullable(Of T) version. It essentially executes the following
Dim myField As Integer? = a.MyField
Dim other As Integer? = Nothing
If myField = other Then
...
End If
The issue though is that when Integer? has the value Nothing it won't compare equal to anything. Hence the above Where clause will always return False. The compiler is attempting to warn you about this problematic corner of Nullable(Of T) and push you to a Is Nothing check which will determine if a.MyField has a non-null value.
This blog article has a very detailed explanation of why this warning is being generated and all of the mechanics behind it. The article is written for C# but the basic premise is applicable to VB.Net as well.
http://blogs.msdn.com/b/abhinaba/archive/2005/12/14/503533.aspx
At least in LINQ to objects you can use this instead:
Nullable(Of Integer).Equals(a, b)
This works fine with both, either or none of the two values being Nothing.
In the example below, what would you name the parameter given that it is used to initialize the property FromDate?
For class constructor methods, I like to have the name of the constructor parameter variable match the name of the property which is being initialized. For example, the parameter "fromDate" is used to initialize the module level variable "_FromDate" with the statement _FromDate = fromDate. Likewise, I could have alternatively written Me.FromDate = fromDate.
Proponents of C#'s case sensitivity would probably say that using a leading lower cased letter for the param variable name, which I believe is MS convention, is an acceptable approach to distinguish it from the Property of the same name but different casing.
However, VB is not case sensitive, which I generally appreciate. In the following example, I am using a param name that matches the property name, 'fromDate," and VB refers to the local instance when there is ambiguity. However, many would probably argue that this "ambiguity" introduces the opportunity for the developer to get confused and not realize which variable is being used. For example, my intent below was to have TWO params passed in, "fromDate" and "toDate" but I accidentily ommited one and as a result, the VB.NET did not warn me of the mistake because it assumed that the statement _ToDate = ToDate was equivalent to _ToDate = Me.ToDate instead of informing me that the variable on the right side of the assignment statement was undeclared.
Public Class Period
Property FromDate As Date
Property ToDate As Date
Public Sub New(ByVal fromDate As Date)
If fromDate > ToDate Then
Throw New ArgumentException("fromDate must be less than or equal to toDate")
End If
_FromDate = fromDate
_ToDate = ToDate
End Sub
End Class
So what is the best solution for VB.NET?
In my judgement, we should have a convention for prefixing all parameter variable with a prefix, but hasn't the use of prefixes been discouraged by Microsoft? For example:
Public Sub New(ByVal paramFromDate As Date, paramToDate As Date)
..or maybe it could be shortened to pFromDate, pToDate...
Whatever approach is taken, I feel that it should be a consistant approach that is used throughout the application.
What do you do?
Use the clearest code possible, which I would suggest is not a prefix. I think using the same name (first letter lowercased) is the clearest code. To avoid the problem encountered I'd rely on a tool, like compiler warnings, FxCop, or ReSharper to alert me that I'm assigning something to itself, since that is almost certainly a mistake in all scenarios.
I know this is against all Microsoft convention, but we use v_ for ByVal parameters, r_ for ByRef parameters and m_ for Module level variables. This allows you to have
m_FromDate = v_FromDate
And you can see straight away what is going on without needing to check the definitions of the variables. I think the biggest argument for non-Hungarian was that modern IDE's allow you to see type on hover over, and changing the type will leave incorrect variables. This scope prefix doesn't clash with that theory and also with CodeRush and ReSharper you can update every instance of a variable if it is required.
Personally, I prefer the _ prefix convention, but there are others I like too. In PL/SQL, my parameters are prefixed with in_, out_, or io_ for in, out, or in/out parameters.
I dislike using only upper and lower cases to distinguish in any language.