DateTime? Cannot assign a value - vb.net

I need to have a property that is a nullable date as the datestamp is used for when a process is completed.
If there is no date this is a way to determain if the process has occured.
I have created a Nuallable DateTime property (DateTime?) however when i try to assign a value from my database entity(when debugged has a date value) i am not thrown an exception however my property still reads a null value after assignment.
How can i get a DateTime? type to accept a DateTime value? i thought this would do the trick _object.DateStamp (type = DateTime?) = _entity.DateStamp (Type = DateTime?, Value = DateTime) or for more understandable syntax
Ctype(object.DateStamp, DateTime?) = Ctype(entity.DateStamp, DateTime?)
Strange thing is i can assign the properties value like this.
Ctype(object.DateStamp, DateTime?) = Now
Oh btw im uisng LinQ Entities.
Any Help?

I had this same problem. I would assign a date from a user entered value and it would never assign to the Nullable Date property on my custom object. My solution was to assign the user entered value into a local Nullable date variable, and then assign that value to the property. Trying to cast the user entered value into a nullable type on a single line didn't work for me either. The solution that worked for me is below:
Dim MyDate As Date? = Date.Parse(Me.txtDate.Text.Trim())
MyObject.Date1 = AppearanceDateAlternate

Another way this can burn you is if you try to use the "<>" operator on a mixture of null and not-null.
Public Property OwnerSignoffDate As Date?
Get
Return _ownerSignoffDate
End Get
Set(value As Date?)
If value <> _ownerSignoffDate Then 'BAD!
_ownerSignoffDate = value
Dirty = True
RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs("OwnerSignoffDate"))
End If
End Set
End Property
change to:
Public Property OwnerSignoffDate As Date?
Get
Return _ownerSignoffDate
End Get
Set(value As Date?)
If value <> _ownerSignoffDate OrElse value.HasValue <> _ownerSignoffDate.HasValue Then 'GOOD!
_ownerSignoffDate = value
Dirty = True
RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs("OwnerSignoffDate"))
End If
End Set
End Property

Related

How to check for Null on a `SqlString` in VB.Net 2.0?

I have a property of type SqlString which is currently returning Null.
_oData.Customer.Name
Here are the following checks I have tried that have not worked.
IsNothing(_oData.Customer.Name)
_oData.Customer.Name.IsNull
_oData.Customer.Name.Value IsNot Nothing
_oData.Customer.Name = Nothing
Each of those results in the error below. How does one really check for the value being Null.
Data is Null. This method or property cannot be called on Null values.
_oData.Customer has values on the other properties.
EDIT
Adding the class which has the name property. Here is how it is defined in the Customer class
Private mName As SqlTypes.SqlString
Public Property Name() As SqlTypes.SqlString
Get
Return mName
End Get
Set(ByVal value As SqlTypes.SqlString)
mName = value
End Set
End Property
SqlString as seen in the SqlTypes Namespace
EDIT-2
Ok seems to be an issue with the way ternery operations are being handled
This works
If _oData.Customer.Name.IsNull Then
CName = ""
Else
CName = _oData.Customer.Name
End If
This doesn't
CName = IIf(_oData.Customer.Name.IsNull, "", _oData.Customer.Name.Value)
Can anyone tell me why this doesnt work when using a ternary operation?
You should use Microsoft.VisualBasic.Information.IsDBNull() Method:
If IsDBNull(_oData.Customer.Name) Then

How does one set a range of possible values a property can be in Visual Basic?

I need a property to never be less than 0. Is there a way to set a property's range so that it can never be a certain value, or in this case, never less than zero?
I've looked into this, but since I'm not sure what I'm looking for, it's hard to do research.
Raise an argument exception if the value is invalid.
Public Property MyProperty As Integer
Get
Return _myProperty
End Get
Set(value As Integer)
If value < 0 Then
Throw New ArgumentException("Value must be greater than or equal to zero.", "MyProperty")
End If
_myProperty = value
End Set
End Property
Alternatively, the property setter might be able to handle the out-of-range value. For example, if we don't what get raise the exception but instead use an alternate value within an acceptable range. Example:
Public Property MyProperty As Integer
Get
Return _myProperty
End Get
Set(value As Integer)
If value < 0 Then
_myProperty = 0
Else
_myProperty = value
End If
End Set
End Property

Can't serialize using DataContractSerializer

I have tried the following code:
PolicyProcessRequest.BranchCode = "HeadOff"
PolicyProcessRequest.Policy.BranchCode = "HeadOff"
PolicyProcessRequest.Policy.Risks.Item(0).BranchCode = "HeadOff"
Dim dcs As DataContractSerializer = New DataContractSerializer(GetType(PureMessagingService.PolicyProcessRequestType))
Dim ms As New MemoryStream()
dcs.WriteObject(ms, PolicyProcessRequest)
Am getting the following exception on the call to WriteObject
System.Runtime.Serialization.SerializationException was caught
HResult=-2146233076 Message=Member BranchCode in type Sirius.SBO.Import.PureMessagingService.BaseRequestType cannot be serialized.
This exception is usually caused by trying to use a null value where a null value is not allowed.
The 'BranchCode' member is set to its default value (usually null or zero). The member's EmitDefault setting is 'false', indicating that the member should not be serialized.
However, the member's IsRequired setting is 'true', indicating that it must be serialized. This conflict cannot be resolved. Consider setting 'BranchCode' to a non-default value. Alternatively, you can change the EmitDefaultValue property on the DataMemberAttribute attribute to true, or changing the IsRequired property to false.
Yet I've set the 'BranchCode' property to the non default value everywhere in the request.
Public Class BaseNBQuoteRequestType
Private agentCodeField As String
Private branchCodeField As String
Private currencyCodeField As CurrencyType
Private currencyCodeFieldSpecified As Boolean
Private itemField As BasePartyType
Private policyField As BaseQuoteRiskMsgType
Private updatePartyField As Boolean
Public Property AgentCode() As String
Get
Return Me.agentCodeField
End Get
Set(ByVal value As String)
Me.agentCodeField = value
End Set
End Property
Public Property BranchCode() As String
Get
Return Me.branchCodeField
End Get
Set(ByVal value As String)
Me.branchCodeField = value
End Set
End Property
Public Property CurrencyCode() As CurrencyType
Get
Return Me.currencyCodeField
End Get
Set(ByVal value As CurrencyType)
Me.currencyCodeField = value
End Set
End Property
Public Property CurrencyCodeSpecified() As Boolean
Get
Return Me.currencyCodeFieldSpecified
End Get
Set(ByVal value As Boolean)
Me.currencyCodeFieldSpecified = value
End Set
End Property
Public Property Party() As BasePartyType
Get
Return Me.itemField
End Get
Set(ByVal value As BasePartyType)
Me.itemField = value
End Set
End Property
Public Property Policy() As BaseQuoteRiskMsgType
Get
Return Me.policyField
End Get
Set(ByVal value As BaseQuoteRiskMsgType)
Me.policyField = value
End Set
End Property
Public Property UpdateParty() As Boolean
Get
Return Me.updatePartyField
End Get
Set(ByVal value As Boolean)
Me.updatePartyField = value
End Set
End Property
End Class
I have the same problem, and it comes from the DataContractSerializer which is used to generate the code. I have other services which use the XmlSerializer with no problem.
Unfortunatly, when using Svcutil.exe or the 'Add Service Reference' feature in Visual Studio to generate client code, an appropriate serializer is automatically selected for you. If the schema is not compatible with the DataContractSerializer, the XmlSerializer is selected (source).
So, you have to manualy fix the IsRequired setting in references.cs each time you generate it.
Replace
IsRequired=true
by
IsRequired=false
in the references.cs file.

Property return value error

I have a class classed class1.vb, it has a public property named prop1 with a get and a set clause. I add one to the value passed in the set clause and in the get clause return the value variable as determined in the set clause. However, I get an error on the variable in the get clause...
Public Property prop1()
Get
Return value
End Get
Set (value)
value = value +1
End Set
End Property
any ideas?
Try setting the type of the property and try changing your value variable to something else, since the Set is using it's own local variable of the same name:
Private myValue As Integer
Public Property prop1() As Integer
Get
Return MyValue
End Get
Set (ByVal value As Integer)
MyValue = value
End Set
End Property

Why can't I check if a 'DateTime' is 'Nothing'?

In VB.NET, is there a way to set a DateTime variable to "not set"? And why is it possible to set a DateTime to Nothing, but not possible to check if it is Nothing? For example:
Dim d As DateTime = Nothing
Dim boolNotSet As Boolean = d Is Nothing
The second statement throws this error:
'Is' operator does not accept operands of type 'Date'. Operands must be reference or
nullable types.
This is one of the biggest sources of confusion with VB.Net, IMO.
Nothing in VB.Net is the equivalent of default(T) in C#: the default value for the given type.
For value types, this is essentially the equivalent of 'zero': 0 for Integer, False for Boolean, DateTime.MinValue for DateTime, ...
For reference types, it is the null value (a reference that refers to, well, nothing).
The statement d Is Nothing is therefore equivalent to d Is DateTime.MinValue, which obviously does not compile.
Solutions: as others have said
Either use DateTime? (i.e. Nullable(Of DateTime)). This is my preferred solution.
Or use d = DateTime.MinValue or equivalently d = Nothing
In the context of the original code, you could use:
Dim d As DateTime? = Nothing
Dim boolNotSet As Boolean = Not d.HasValue
A more comprehensive explanation can be found on Anthony D. Green's blog
DateTime is a value type, which is why it can't be null. You can check for it to be equal to DateTime.MinValue, or you can use Nullable(Of DateTime) instead.
VB sometimes "helpfully" makes you think it's doing something it's not. When it lets you set a Date to Nothing, it's really setting it to some other value, maybe MinValue.
See this question for an extensive discussion of value types vs. reference types.
DateTime is a value type, which means it always has some value.
It's like an integer - it can be 0, or 1, or less than zero, but it can never be "nothing".
If you want a DateTime that can take the value Nothing, use a Nullable DateTime.
Some examples on working with nullable DateTime values.
(See Nullable Value Types (Visual Basic) for more.)
'
' An ordinary DateTime declaration. It is *not* nullable. Setting it to
' 'Nothing' actually results in a non-null value.
'
Dim d1 As DateTime = Nothing
Console.WriteLine(String.Format("d1 = [{0}]\n", d1))
' Output: d1 = [1/1/0001 12:00:00 AM]
' Console.WriteLine(String.Format("d1 is Nothing? [{0}]\n", (d1 Is Nothing)))
'
' Compilation error on above expression '(d1 Is Nothing)':
'
' 'Is' operator does not accept operands of type 'Date'.
' Operands must be reference or nullable types.
'
' Three different but equivalent ways to declare a DateTime
' nullable:
'
Dim d2? As DateTime = Nothing
Console.WriteLine(String.Format("d2 = [{0}][{1}]\n", d2, (d2 Is Nothing)))
' Output: d2 = [][True]
Dim d3 As DateTime? = Nothing
Console.WriteLine(String.Format("d3 = [{0}][{1}]\n", d3, (d3 Is Nothing)))
' Output: d3 = [][True]
Dim d4 As Nullable(Of DateTime) = Nothing
Console.WriteLine(String.Format("d4 = [{0}][{1}]\n", d4, (d4 Is Nothing)))
' Output: d4 = [][True]
Also, on how to check whether a variable is null (from Nothing (Visual Basic)):
When checking whether a reference (or nullable value type) variable is null, do not use = Nothing or <> Nothing. Always use Is Nothing or IsNot Nothing.
In any programming language, be careful when using Nulls. The example above shows another issue. If you use a type of Nullable, that means that the variables instantiated from that type can hold the value System.DBNull.Value; not that it has changed the interpretation of setting the value to default using "= Nothing" or that the Object of the value can now support a null reference. Just a warning... happy coding!
You could create a separate class containing a value type. An object created from such a class would be a reference type, which could be assigned Nothing. An example:
Public Class DateTimeNullable
Private _value As DateTime
'properties
Public Property Value() As DateTime
Get
Return _value
End Get
Set(ByVal value As DateTime)
_value = value
End Set
End Property
'constructors
Public Sub New()
Value = DateTime.MinValue
End Sub
Public Sub New(ByVal dt As DateTime)
Value = dt
End Sub
'overridables
Public Overrides Function ToString() As String
Return Value.ToString()
End Function
End Class
'in Main():
Dim dtn As DateTimeNullable = Nothing
Dim strTest1 As String = "Falied"
Dim strTest2 As String = "Failed"
If dtn Is Nothing Then strTest1 = "Succeeded"
dtn = New DateTimeNullable(DateTime.Now)
If dtn Is Nothing Then strTest2 = "Succeeded"
Console.WriteLine("test1: " & strTest1)
Console.WriteLine("test2: " & strTest2)
Console.WriteLine(".ToString() = " & dtn.ToString())
Console.WriteLine(".Value.ToString() = " & dtn.Value.ToString())
Console.ReadKey()
' Output:
'test1: Succeeded()
'test2: Failed()
'.ToString() = 4/10/2012 11:28:10 AM
'.Value.ToString() = 4/10/2012 11:28:10 AM
Then you could pick and choose overridables to make it do what you need. Lot of work - but if you really need it, you can do it.
You can also use below just simple to check:
If startDate <> Nothing Then
your logic
End If
It will check that the startDate variable of DateTime datatype is null or not.
You can check this like below :
if varDate = "#01/01/0001#" then
' blank date. do something.
else
' Date is not blank. Do some other thing
end if
A way around this would be to use Object datatype instead:
Private _myDate As Object
Private Property MyDate As Date
Get
If IsNothing(_myDate) Then Return Nothing
Return CDate(_myDate)
End Get
Set(value As Date)
If date = Nothing Then
_myDate = Nothing
Return
End If
_myDate = value
End Set
End Property
Then you can set the date to nothing like so:
MyDate = Nothing
Dim theDate As Date = MyDate
If theDate = Nothing Then
'date is nothing
End If