NullReference on a value that is not null - asp.net

I have a function that gets a string passed to it. When testing the function, I'm getting a null reference exception on the string parameter that gets passed to it, even though the string is not null, I don't understand why I'm getting this error. I have a screen shot below
I used a dummy value to verify both the string parameter in the SelectSingleNode function and the newValue string parameter being passed to my function and they both contain values, so I don't understand why it's throwing a null reference exception. Just for clarity, the purpose of the function is to write values back to the nodes of an XML file.
UPDATE
Sorry for not posting code
Private Sub setValue(ByVal nodeToMod As String, ByVal newValue As String)
''Test writing to xml config file
Dim dummy As String = "Config/" & nodeToMod
Dim xmlDoc As New XmlDocument
Using fs As FileStream = New FileStream(HttpContext.Current.Server.MapPath("~/XML_Config/Config.xml"), FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite)
xmlDoc.Load(fs)
Dim foo As XmlNode = xmlDoc.SelectSingleNode(dummy)
Console.WriteLine(foo.InnerXml)
fs.Seek(0, SeekOrigin.Begin)
fs.SetLength(0)
xmlDoc.Save(fs)
End Using
End Sub
And here is the XML file I'm working with
<?xml version="1.0" encoding="utf-8"?>
<Config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Username>john.doe#email.com</Username>
<Password>Password1</Password>
<ProductType>MyProduct</ProductType>
<DirectoryEntryPath>LDAP://myDomain</DirectoryEntryPath>
<SMTPDefaultOnly>True</SMTPDefaultOnly>
<Logo>myLogo.gif</Logo>
</Config>
Yes, the SlectSingleNode function is not returning a value. I just started working with XPath, this seemed to have worked when I was using last week. I'm not sure why it has stopped working now.
UPDATE2:
Got it, stupid mistake. I had nodeToMod being passed as "UserName" instead of "Username" in the Set method
Set(ByVal value As String)
setValue("UserName", value.ToString)
_userName = value
End Set

The null reference that is being complained about is the result of the call to SelectSingleNode. That is, when the xpath formed by concatenating /Config/ and the contents of nodeToMod is evaluated against the document, no node matches. So you get null, and attempting to set the InnerText of null gives the exception.
We would really need to see nodeToMod and the xml file itself to help further. Also, please post code rather than screenshots!

Ensure that the FileStream object you're creating doesn't come out null. Maybe it can't find the config.xml file?

It's likely that the result of SelectSingleNode is null.
Change that line to two lines, and it will be easier to see the problem in the debugger:
Dim node = xmlDoc.SelectSingleNode(dummy)
node.InnerText = newValue

Related

How do I write a VB.Net method to filter a URLs?

I am attempting to write a method using VB.NET that will allow me to read in a URL and compare it to a list. If it is one of the URLs on the list then Bing Tracking conversion will be applied.
At the moment I can only think do write it as a comaparative method, comapring the current URL with the ones that require tracking (a list). This, however, sems a little long winded.
Each page may have a different querystring value/page id, there for its fundamental to get exactly the right page for the tracking to be applied to.
Any Ideas?
Sorry I really am a novice when developing functions in VB.Net
If I were to use th Contains() function then I would imagine that it would look a little something like this:
Private sub URL_filter (ByVal thisPage As ContentPage, brandMessage? As Boolean) As String
Dim url_1 As String = "/future-contact thanks.aspx"
Dim url_2 As String = "/find-enquiry thanks.aspx?did=38"
Dim url_3 As String = "/find-enquiry-thanks.aspx?did=90"
Dim url_4 As String = "/find-enquiry-thanks.aspx?did=62"
Dim result as String
result = CStr (url_1.Contains(current_URL))
txtResult.Text = result
End Sub
If I were to use this then what type of loop would I have to run to check all the URLs that are in my list against the current_URL? Also where would I define the current_URL?
You can use the Contains() function to check if the list contains the given value. You could also implement a binary search, but it is probably overkill for your purposes. Here is an example:
Dim UrlList As New List(Of String)
UrlList.Add("www.example2.net") 'Just showing adding urls to the list
UrlList.Add("www.example3.co.uk")
UrlList.Add("www.exampletest.com")
Dim UrlToCheck As String = "www.exampletest.com" 'This is just an example url to check
Dim result As Boolean = UrlList.Contains(UrlToCheck) 'The result of whether it was found
Make sure to add these imports Imports System and Imports System.Collections.Generic
Disclaimer: I have no experience with VB.NET

asp.net JSON escaping output -- disable?

Sub Application_Start()
' ... do stuff
GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear()
End Sub
Then inside my controller I have:
Dim serializer As New JavaScriptSerializer()
Dim json As String = serializer.Serialize(Quotes.ToArray).Replace("\""", "")
Return json
When I set a break point on final statement I can clearly see the results are just as I expected but by the time I see it in Chrome JSON viewer it has been escaped with double quotes.
When I comment the configuration line provided above SO XML is the return type but still use JSON converter on the array the data packaged in the XML tags are as I would expect.
This is what I need, not the escaped gibberish provided.

DataContext Disposal error resolved but why?

I am working with VB.Net. I have resolved a behavior where the code returns with an error of "Cannot access a disposed object. Object name: 'DataContext accessed after Dispose.'."
My problem : I simply don't understand why it works !
Here is my code when happens the error :
Public Function Element_Import(ByVal id_element As Integer) As elements
Using db As New GlobalDataContext(MyConnexion)
Return (From element In db.elements
Select element
Where element.id_element = id_element).First
End Using
End Function
Then I try to retreave the data :
Dim myElement As elements = _MyConnection.Element_Import(id_element)
Dim myLocal As List(Of elements_localisation) = myElement.elements_localisation.ToList '-- ObjectDisposedException !
When I import my element then try to access sub-tables called "elements_localisation" and "elements_files" an ObjectDisposedException occures. That's fair as the DataContext is not available.
So I have done something different :
Public Function Element_ImportContext(ByVal id_element As Integer) As elements
Dim myElement As elements
Dim myElementLocalisation As New List(Of elements_localisation)
Dim myElementFiles As New List(Of elements_files)
Using db As New GlobalDataContext(MyConnexion)
myElement = (From element In db.elements
Select element
Where element.id_element = id_element).First
myElementLocalisation = myElement.elements_localisation.ToList
myElementFiles = myElement.elements_files.ToList
End Using
Return myElement
End Function
Then I try to retreave the data :
Dim myElement As elements = _MyConnection.Element_ImportContext(id_element)
Dim myLocal As List(Of elements_localisation) = myElement.elements_localisation.ToList '-- IT WORKS !
I really wanna understand what happened as, in both case, the DataContext is disposed.
Can anyone explain ?
When you write LINQ, you write a query to be executed against some data, that query is only executed when another part of the code needs the data.
In your case, you are returning the myElement variable because you have used .First(), which forces the query to be executed and the first item to be returned.
The properties elements_localisation and elements_files are likely to be virtual properties that are only loaded when you request them. (This is certainly the case with Entity Framework, I'm not sure what you're using here).
Your program will try to access the virtual property which will then go off to the data context to get the next bit of data you requested, but in your case the data context is disposed.
Your second approach works because you have used ToList() on the virtual properties, which forces the data to be retrieved then and there, before your data context has been disposed.

Using ParseQueryString function to get values from QueryString

I needed to get values out of a string in a QueryString format, that is such as: data1=value1&data2=value2...
Someone suggested I used HttpUtility.ParseQueryString to get the value, I've searched and searched but I can't find any documentation or implementation of this and the Microsoft documentation for it doesn't explain how it works, can someone tell me hwat I'm doing wrong, my code is below;
Public Shared Sub ProcessString(ByVal Vstring As String)
Dim var As NameValueCollection = HttpUtility.ParseQueryString(Vstring)
Dim vname As String = var.QueryString("VNAME")
End Sub
MSDN has an example.
' Parse the query string variables into a NameValueCollection.
Dim qscoll As System.Collections.Specialized.NameValueCollection = HttpUtility.ParseQueryString(Vstring)
Dim vname As String = qscoll("VNAME")
A NameValueCollection represents a collection of associated String keys and String values that can be accessed either with the key or with the index.
I found the problem, I was referencing everything fine but I was doing it in a separate .VB dependency file, once I did it on the actual code behind of the aspx form that solved the problem and it all worked. So now I'm just passing the string from Codebehind as a specialised.NameValue collection in to the function.

updating properties of a class with dynamic references

Sorry for what is probably a very basic question. I have a vb.net class with properties defined as follows:
Private m_Property1 As String
Public Property Property1() As String
Get
Return m_Property1
End Get
Set(ByVal value As String)
If IsNothing(value) Then
m_Property1 = String.Empty
Else
m_Property1 = value
End If
End Set
End Property
I can then set the values as follows:
classname.Property1 = "myvalue"
How do I set the value of a property that is defined dynmically eg
Dim strPropertyName As String = "Property1"
Hope that makes sense.
Thanks,
Josh
You would use reflection
Dim strPropertyName as string = "Property1"
Dim pi As PropertyInfo = myClass.GetType().GetProperty(strPropertyName)
pi.SetValue(myClass.GetType(), "some string", Nothing)
You want to use Reflection in order to do this. VB.NET provides a way to do this if you know the value at compile-time, but for run-time operations, you need to use the GetType keyword in order to get the type of your class (or, use the GetType method on an instance of it if you don't know it).
Then, with that Type instance, you would call GetProperty, passing the string with the name of the property. It will return an PropertyInfo instance which you then call GetValue on, passing the instance of the object in, which will return an Object which you have to cast back to a type you wish to use (if you are).
VB.NET makes a lot of this easier with the CallByName function.
Also, if you know at compile-time what the name of the property is, you can always cast to object and use VB.NET's inherent late binding:
Dim o As Object = <your object>
o.Property1 = ...
VB.NET will perform the late-binding for you.

Resources