VB Magic

2012/11/08

OData AddTo using WinRT and VB.net

I was trying to find a way to POST a new entity to an OData feed and found it hard to find examples of doing this. After a bit of searching I found some C# code that allowed me to do an update. After converting this to VB I ended up with

    Private Sub addPersonButton_Click_1(sender As Object, e As RoutedEventArgs)

        Dim p As New Person
        p.name = personNameTextBox.Text
        If p.name <> "" Then
            _context.AddToPerson(p)
            _context.BeginSaveChanges(AddressOf ContextSaveChanges, p)
        End If
    End Sub

Person is part of an OData feed I am using e.g. http://server/odata.svc/Person

So I create a new instance of a Person and add a name to it (From a TextBox in the UI)

Then I use the AddToPerson method of the context and as there is no synchronous way in WinRT to SaveChanges, I used the BeginSaveChanges method of the context and passed through the address of the routine that will handle the callback.

    Private Function ContextSaveChanges(result As IAsyncResult) As Task
        Try
            _context.EndSaveChanges(result)
        Catch ex As Exception
            _message = ex.Message
            If ex.InnerException IsNot Nothing Then
                _message = _message & " - " & ex.InnerException.Message
            End If
            Me.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, AddressOf UpdateUI)
        End Try
    End Function

    Public Sub UpdateUI()
        personNameTextBox.Text = _message
    End

Above is the function that gets called and it will try to run EndSaveChanges and trap any error that occurred and display it on the UI. I originally put the personNameTextBox.Text = ex.Message in the catch section but that caused a Treading error [RPC_E_WRONG_THREAD]. So after a lot of routing around and the help of a colleague I discovered the Me.Dispacher.RunAsync function in which I had a lambda expression in to update the UI. This didn’t fail but also didn’t update the UI so I used a subroutine and put the AddressOf in the RunAsync command and this worked as expected.

Phew made it 😉

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Blog at WordPress.com.

%d bloggers like this: