Created
September 12, 2011 13:02
-
-
Save emoa2l/1211199 to your computer and use it in GitHub Desktop.
vb extension methods to serialize and deserialize datacontracts from restful web service
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Imports System.Runtime.Serialization | |
Imports System.Xml | |
Imports System.IO | |
Public Module WebClient | |
<System.Runtime.CompilerServices.Extension()> | |
Public Sub AsyncDeSerializeObjectFromService(Of T)( | |
ByVal self As Net.WebClient, | |
ByVal svcUri As Uri, | |
ByVal callBack As Action(Of Object) | |
) | |
AddHandler self.OpenReadCompleted, | |
Sub(s, e) | |
Dim dcs As New DataContractSerializer(GetType(T)) | |
Dim reader As XmlDictionaryReader = _ | |
XmlDictionaryReader.CreateTextReader(e.Result, New XmlDictionaryReaderQuotas()) | |
callBack(dcs.ReadObject(reader)) | |
End Sub | |
self.OpenReadAsync(svcUri) | |
End Sub | |
Public Function SerializeObject(Of T)(ByVal model As Object) As String | |
Dim serializer As New DataContractSerializer(GetType(T)) | |
Using ms As New MemoryStream | |
serializer.WriteObject(ms, model) | |
ms.Position = 0 | |
Dim sr As New StreamReader(ms) | |
Return sr.ReadToEnd | |
End Using | |
End Function | |
<System.Runtime.CompilerServices.Extension()> | |
Public Function DeSerializeObjectFromService(Of T)(ByVal self As Net.WebClient, ByVal svcUri As Uri) As T | |
Dim dcs As New DataContractSerializer(GetType(T)) | |
Dim reader As XmlDictionaryReader = _ | |
XmlDictionaryReader.CreateTextReader(self.OpenRead(svcUri), New XmlDictionaryReaderQuotas()) | |
Return CType(dcs.ReadObject(reader), T) | |
End Function | |
End Module |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment