Working with VB.Net NullReferenceException

It should be simple, but I have problems. Using the eBay.Net library, sometimes certain fields in the Nothing response and sometimes contain a value. When they are Nothing , they can simply be represented as an empty string, but the developers decided to return them as Nothing , so when I try to set the String to a value (when nothing exists), I get a NullReferenceException, see below

 Imports System Imports System.Configuration.ConfigurationManager Imports System.Globalization Imports System.Threading Imports System.Xml Imports eBay.Service.Core.Soap Imports eBay.Service.Core.Sdk Imports eBay.Service.Call Imports eBay.Service.Util Public Class eBayOrderImportService Private Sub ServiceWorkerThread(ByVal state As Object) ' Periodically check if the service is stopping. Do While Not Me.stopping ' Perform main service function here... GetLastTime() Dim apiContext As ApiContext = GetApiContext() Dim apiCall As GetOrdersCall = New GetOrdersCall(apiContext) Dim orders As New OrderTypeCollection Dim timeFilter As New TimeFilter timeFilter.TimeFrom = lastUpdate timeFilter.TimeTo = Date.Now Dim lastTime As Boolean = SetLastTime() apiCall.IncludeFinalValueFee = True orders = apiCall.GetOrders(timeFilter, TradingRoleCodeType.Seller, OrderStatusCodeType.Completed) Dim order As OrderType For Each order In orders 'do order-wide stuff here LogOrder(order) Next Thread.Sleep(30 * 1000) ' Simulate some lengthy operations. Loop ' Signal the stopped event. Me.stoppedEvent.Set() End Sub Private Sub LogOrder(ByVal Order As OrderType) Dim OrderID, AccountID, BillingFirstName, BillingLastName, _ BillingCompany, BillingEmailAddress, BillingPhone, _ BillingAddress1, BillingAddress2, BillingCity, _ BillingStateProvidence, BillingPostalCode, _ BillingCountry, ShippingFirstName, ShippingLastName, _ ShippingCompany, ShippingEmailAddress, ShippingPhone, _ ShippingAddress1, ShippingAddress2, ShippingCity, _ ShippingStateProvidence, ShippingPostalCode, _ ShippingCountry, OrderStatus, BillingStatus, _ OrderDate, ShippingMethod, SalesTax, _ PreShippingCharge, OrderDiscount, OrderTotalCharged, _ PaymentMethod, RepeatOrder, GiftCode, CouponCode, RID, _ OrderNotes, OrderChannel, IsPrinted, IsShipped, PrintDate, _ ShipDate, ActualShipCharge, DaysInTransit, DeliveryDate, _ TrackingNumber, ShippedMethod As String OrderID = Order.OrderID AccountID = "" Dim name As String = If(Order.ShippingAddress.Name.ToString(), "None Given") BillingFirstName = name.Substring(0, name.IndexOf(" ")) BillingLastName = name.Substring(name.IndexOf(" ") + 1) BillingCompany = If(Order.ShippingAddress.CompanyName.ToString(), "") BillingEmailAddress = If(Order.TransactionArray(0).Buyer.Email.ToString(), "") BillingPhone = If(Order.ShippingAddress.Phone.ToString(), "") BillingAddress1 = If(Order.ShippingAddress.Street1.ToString(), "") BillingAddress2 = If(Order.ShippingAddress.Street2.ToString(), "") BillingCity = If(Order.ShippingAddress.CityName.ToString(), "") BillingStateProvidence = If(Order.ShippingAddress.StateOrProvince.ToString(), "") BillingPostalCode = If(Order.ShippingAddress.PostalCode.ToString(), "") BillingCountry = If(Order.ShippingAddress.CountryName.ToString(), "") ShippingFirstName = If(BillingFirstName, "") ShippingLastName = If(BillingLastName, "") ShippingCompany = If(Order.ShippingAddress.CompanyName.ToString(), "") ShippingEmailAddress = If(Order.TransactionArray(0).Buyer.Email.ToString(), "") ShippingPhone = If(Order.ShippingAddress.Phone.ToString(), "") ShippingAddress1 = If(Order.ShippingAddress.Street1.ToString(), "") ShippingAddress2 = If(Order.ShippingAddress.Street2.ToString(), "") ShippingCity = If(Order.ShippingAddress.CityName.ToString(), "") ShippingStateProvidence = If(Order.ShippingAddress.StateOrProvince.ToString(), "") ShippingPostalCode = If(Order.ShippingAddress.PostalCode.ToString(), "") ShippingCountry = If(Order.ShippingAddress.CountryName.ToString(), "") OrderStatus = If(Order.OrderStatus.ToString(), "") BillingStatus = If(Order.OrderStatus.ToString(), "") OrderDate = If(Order.CreatedTime.ToString("MM/DD/yyyy"), "") If Order.TransactionArray(0).Taxes IsNot Nothing Then Dim tmpTax As Double = 0.0 Dim tmpTrans As TransactionType For Each tmpTrans In Order.TransactionArray tmpTax = tmpTax + tmpTrans.Taxes.TotalTaxAmount.Value Next SalesTax = tmpTax.ToString() Else SalesTax = "0.0" End If ShippingMethod = If(Order.ShippingServiceSelected.ShippingService.ToString(), "") ShippingMethod = ShippingMethod & ":" & If(Order.ShippingServiceSelected.ShippingServicePriority.ToString(), "") OrderTotalCharged = If(Order.Total.Value.ToString(), "") OrderChannel = "eBay" comm = New OdbcCommand comm.CommandText = _ "INSERT INTO Orders (OrderID, AccountID, BillingFirstName, BillingLastName, " & _ "BillingCompany, BillingEmailAddress, BillingPhone, BillingAddress1, " & _ "BillingAddress2, BillingCity, BillingStateProvidence, BillingPostalCode, " & _ "BillingCountry, ShippingFirstName, ShippingLastName, ShippingCompany, " & _ "ShippingEmailAddress, ShippingPhone, ShippingAddress1, ShippingAddress2, " & _ "ShippingCity, ShippingStateProvidence, ShippingPostalCode, ShippingCountry, " & _ "OrderStatus, BillingStatus, OrderDate, SalesTax, ShippingMethod, OrderTotalCharged, OrderChannel) " & _ "VALUES('" & OrderID & "', '" & AccountID & "', '" & BillingFirstName & "', '" & _ BillingLastName & "', '" & BillingCompany & "', '" & BillingEmailAddress & "', '" & _ BillingPhone & "', '" & BillingAddress1 & "', '" & BillingAddress2 & "', '" & BillingCity & "', '" & _ BillingStateProvidence & "', '" & BillingPostalCode & "', '" & BillingCountry & "', '" & _ ShippingFirstName & "', '" & ShippingLastName & "', '" & ShippingCompany & "', '" & _ ShippingEmailAddress & "', '" & ShippingPhone & "', '" & ShippingAddress1 & "', '" & _ ShippingAddress2 & "', '" & ShippingCity & "', '" & ShippingStateProvidence & "', '" & _ ShippingPostalCode & "', '" & ShippingCountry & "', '" & OrderStatus & "', '" & _ BillingStatus & "', '" & OrderDate & "', '" & SalesTax & "', '" & ShippingMethod & "', '" & _ OrderTotalCharged & "', '" & OrderChannel & "')" ' Dim orderResult As Integer = comm.ExecuteNonQuery() sysLog.WriteEntry(comm.CommandText) End Sub End Class 

There is an updated code, please note that an exception is not thrown until: BillingCompany = If (Order.ShippingAddress.CompanyName.ToString (), "") is executed. The Name property has a value that is successfully stored in its variable, and Order.ShippingAddress.CompanyName is Nothing (this property exists and can sometimes have a value). I updated the code to include an Anthony Pegram answer that didn't help.

Everything is declared correctly, in order to shorten the code that I just showed, the corresponding example. Consider this inside the loop for each order returned by the call to GetOrders (), sometimes Order.ShippingAddress.CompanyName will be nothing, at this time can it be treated as an empty string? I tried the ToString () method. In other languages, I could $ CompanyName = this || what;

Anything like that in VB.Net?

+4
source share
2 answers

You can use If(a, b) to combine the null value into another. Example:

 Dim obj as String = Nothing Dim foo as String = If(obj, "foo") 

The result of foo in this example is the string "foo". If a non-zero string has been assigned to obj, then foo also refers to this string.

However, I have a strong feeling that null reference exclusion can occur not on a property, but on an object. Order or ShippingAddress may be zero. Accessing properties or methods in a null reference is a mistake. Simply accessing a null value by storing it in a variable is not an error in itself.

If you get your exception on one of these lines

 CompanyName = Order.ShippingAddress.CompanyName State = Order.ShippingAddress.StateOrProvince 

This is because either Order or ShippingAddress is null.

Check and see if these objects can really return as nothing. If so, you will need to apply a null check around them before accessing their properties.


Your update:

There is an updated code, please note that an exception is not raised until:

BillingCompany = If(Order.ShippingAddress.CompanyName.ToString(), "")

Performed

.

This may be because Order may be empty, ShippingAddress may be null or CompanyName may be null. This is an exception for accessing a property or method with a null reference. If Order is null, you will receive a ShippingAddress error message. Similarly, if ShippingAddress is NULL, you cannot access CompanyName. If CompanyName is NULL, you cannot call ToString ().

You should at some point check which object is null. I have no confidence that none of them will be empty. You? Check it out. Go through your program and observe the state of the object.

If it refers to properties such as CompanyName, which are null, and if CompanyName is a string, omit the ToString () call.

 BillingCompany = If(Order.ShippingAddress.CompanyName, "") 

If CompanyName is not a string, you just need to compare it to Nothing before calling ToString () or accessing the property.

+9
source

Take a look at this line:

 CompanyName = Order.ShippingAddress.CompanyName 

If the CompanyName property in Order.ShippingAddress.CompanyName is Nothing , this code is still completely legal and will not throw a NullReferenceException. An exception is Order.ShippingAddress because either Order.ShippingAddress or Order itself is Nothing. You get an exception because you are trying to find a specific property for an object that does not exist. Based on your sample code, it's easy to see why this might be:

 Dim Order As OrderType 

This string declares a variable, but it never gives this variable a value. Order is a reference variable of an object ... which has not yet been set to an instance of the object. Now it sounds like you can omit the code in which the instance is installed, but it is worth mentioning, because if so, this is a very simple part of how this code should work, and it makes sense to include at least a stub for this in the sample.

+2
source

Source: https://habr.com/ru/post/1395998/


All Articles