AsyncCallback of BackgroundWorker Webservice reference Function - vb.net

I am trying to build a new class from where I can call functions with a background worker from a web service in a windows Phone 8.1 silverlight app.
calling page
LoginPage.xaml.vb
Partial Public Class LoginPage
Private sub Logon()
WebServiceHelper.a(WebServiceHelper.Functions.Logon)
LoginFinish()
End Sub
End Class
WebserviceHelper
WebServiceHelper.vb
Public Class WebServiceHelper
Public Shared Sub a(ByVal _Task As Functions)
If _Task = Functions.Logon Then
_Service.BeginLogonWindowsPhone(usr, pass, New AsyncCallback(AddressOf ResultBackGroundTask), result)
End If
End Sub
Public Shared Sub ResultBackGroundTask(ByVal result As Object)
If _Task = Functions.Logon Then
ResultObject = result
End If
End Sub
End Class
The problem is when I call webservice.a() the AsyncCallback ResultBackGroundTask doesn’t fire in time. Instead LoginFinish is called resulting in an error because the resultobject isn’t initialized yet.
I've tried:
Task.Factory.FromAsync(_Service.BeginLogonWindowsPhone, ResultBackGroundTask, usr, pass, Nothing)
But I get an error:
Argument not specified for parameter 'asyncState' of
'Public Function BeginLogonWindowsPhone(userName As String, password As String, callback As System.AsyncCallback, asyncState As Object) As System.IAsyncResult'.
The function I try to call is:
<System.ServiceModel.OperationContractAttribute(AsyncPattern:=true, Action:="http://test.com/LogonWindowsPhone", ReplyAction:="*"), _
System.ServiceModel.XmlSerializerFormatAttribute(SupportFaults:=true)> _
Function BeginLogonWindowsPhone(ByVal userName As String, ByVal password As String, ByVal callback As System.AsyncCallback, ByVal asyncState As Object) As System.IAsyncResult
This function is automatically generated in the webservice reference.
I use the Webservice to connect with the clients database, for security reasons.

Related

"This method is not implemented by this class.": SoapHttpClientProtocol

I have two calls to my server application. One is normal Invoke method and another is InvokeAsync method. We are using HttpWebRequestCompressed code as well with request.Headers.Add("Accept-Encoding", "gzip, deflate").
Invoke method
<System.Web.Services.Protocols.SoapDocumentMethodAttribute("://abc.com/myApp/WS/OpenAllSupplier", RequestNamespace:="://abc.com/myApp/WS", ResponseNamespace:="://abc.com/myApp/WS", Use:=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle:=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)> _
Public Function OpenAllSupplier() As dsSupplier
Dim results() As Object = Me.Invoke("OpenAllSupplier", New Object(-1) {})
Return CType(results(0),dsSupplier)
End Function
Invoke Async method
Public Overloads Sub OpenSupplierAsync(ByVal buCode As String, ByVal buType As String, ByVal userState As Object)
If (Me.OpenSupplierOperationCompleted Is Nothing) Then
Me.OpenSupplierOperationCompleted = AddressOf Me.OnOpenSupplierOperationCompleted
End If
Me.InvokeAsync("OpenSupplier", New Object() {buCode, buType}, Me.OpenSupplierOperationCompleted, userState)
End Sub
Private Sub OnOpenSupplierOperationCompleted(ByVal arg As Object)
If (Not (Me.OpenSupplierCompletedEvent) Is Nothing) Then
Dim invokeArgs As System.Web.Services.Protocols.InvokeCompletedEventArgs = CType(arg,System.Web.Services.Protocols.InvokeCompletedEventArgs)
RaiseEvent OpenSupplierCompleted(Me, New OpenSupplierCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState))
End If
End Sub
WebRequest Class
Partial Public Class BusinessUnits
Inherits System.Web.Services.Protocols.SoapHttpClientProtocol
Protected Overrides Function GetWebRequest(ByVal uri As Uri) As System.Net.WebRequest
Try
'System.Net.HttpWebRequest.Create(uri) '
Dim request As HttpWebRequest = CType(MyBase.GetWebRequest(uri), HttpWebRequest)
request.Headers.Add("Accept-Encoding", "gzip, deflate")
Return New HttpWebRequestCompressed(request)
Catch ex As Exception
End Try
End Function
End Class
In HttpWebRequestCompressed class
Public Class HttpWebRequestCompressed
Inherits System.Net.WebRequest
Dim request As HttpWebRequest
Public Sub New(ByVal request As WebRequest)
Me.request = CType(request, HttpWebRequest)
End Sub
Public Overrides Function GetResponse() As WebResponse
Return New HttpWebResponseDecompressed(Me.request)
End Function
Public Overrides Function GetRequestStream() As Stream
Return New GZipStream(Me.request.GetRequestStream(), CompressionMode.Compress)
End Function
GetRequestStream executes only when Invoke method calls.
Invoke method is working as expected and no issues.
On Invoke Async the call is not going to Server, and we are getting error in client side as,
"This method is not implemented by this class."
What exactly I am missing here in Async call? Unable to get the method invoke in server only when Async call is happening.
Thank you for supporting.
Regards
Sangeetha

How to route two get methods with same params in WebApi?

In my ApiController i had one GET method which was returning some data from DB.
Now i have to enlarge that controller by adding one more GET method which will return data from same database but formatted in another way so the parameters i'd pass to that method will be the same as from the 1st one.
I was trying to do the following:
Public Class CshController
Inherits ApiController
Public Function GetValoriCsh(ByVal npv As String, ByVal nc As String) As IEnumerable(Of Cshlvl)
Dim csh As Cshlvl = New Cshlvl
Return csh.ValoreCsh(npv, nc)
End Function
Public Function GetOperazioni(ByVal npv As String, ByVal nc As String) As IEnumerable(Of OperazioniCsh)
Dim operazioni As OperazioniCsh = New OperazioniCsh
Return operazioni.OperazioniCsh(npv, nc)
End Function
End Class
So here come the issue, the api fails as there are two method which require same parameters so it doesn't know how to chose which i would to use.
actually i'm calling the following api by the following url api/csh/ is it possible in some way by calling api/csh/ to get data from GetValoriCsh and like by calling something like api/csh/operazioni/ to get data from GetOperazioni?
My WebApiConfig
Public Module WebApiConfig
Public Sub Register(ByVal config As HttpConfiguration)
' Servizi e configurazione dell'API Web
' Route dell'API Web
config.MapHttpAttributeRoutes()
config.Routes.MapHttpRoute(
name:="DefaultApi",
routeTemplate:="api/{controller}/{id}",
defaults:=New With {.id = RouteParameter.Optional}
)
End Sub
End Module
I've tryed to add <Route("api/csh/op")> above GetOperazioni but it had no effect.
If using attribute routing it is all or nothing.
<RoutePrefix("api/csh")>
Public Class CshController
Inherits ApiController
'GET api/csh
<HttpGet()>
<Route("")>
Public Function GetValoriCsh(ByVal npv As String, ByVal nc As String) As IEnumerable(Of Cshlvl)
Dim csh As Cshlvl = New Cshlvl
Return csh.ValoreCsh(npv, nc)
End Function
'GET api/csh/op
<HttpGet()>
<Route("op")>
Public Function GetOperazioni(ByVal npv As String, ByVal nc As String) As IEnumerable(Of OperazioniCsh)
Dim operazioni As OperazioniCsh = New OperazioniCsh
Return operazioni.OperazioniCsh(npv, nc)
End Function
End Class
Reference Attribute Routing in ASP.NET Web API 2

Logging errors and events, best practice?

I'm currently developing a 3-tier application and now I have come to logging, I am curios as to the best practices. Below is my interface and model for a LogEntry, I then implement that in a service called JsonLogService which serializes the entries and stores them in the file system.
Public Interface ILogService
Sub Log(logEntry As LogEntry)
Sub Log(source As String, type As LogEntryType, message As String)
Sub Log(source As String, type As LogEntryType, format As String, ParamArray arguments() As Object)
End Interface
Public Enum LogEntryType
Information
Warning
[Error]
Debug
End Enum
Public Class LogEntry
Public Property Source As String
Public Property Type As LogEntryType
Public Property Message As String
Public Property LoggedAt As Date = DateTime.Now
Public Sub New()
End Sub
Public Sub Now(source As String, type As LogEntryType, message As String)
Me.Source = source
Me.Type =
Me.Message = message
End Sub
Public Sub New(source As String, type As LogEntryType, format As String, ParamArray arguments() As Object)
Me.Source = source
Me.Type = type
Me.Message = String.Format(format, arguments)
End Sub
I'm currently using this service in my managers to log when events happen which works well, but now I am unsure how to implement this for catching errors.
Does it actually make sense to catch errors in my managers methods because surely my tests should prevent any errors from happening there?

Executing a Callback Method When an Asynchronous Call Completes

I am trying to learn more about Asynchronous calls, which are part of the MCSD exam. I have followed all of the examples on the following page successfully: http://msdn.microsoft.com/en-gb/library/2e08f6yc.aspx.
I have created console applications and Winform applications for all of the examples. However, the callback function is never called in the last example (Executing a Callback Method When an Asynchronous Call Completes) if a WinForm application is used. Please see the code below:
Imports System
Imports System.Threading
Imports System.Runtime.InteropServices
Public Class AsyncDemo
' The method to be executed asynchronously.
'
Public Function TestMethod(ByVal callDuration As Integer, _
<Out()> ByRef threadId As Integer) As String
Console.WriteLine("Test method begins.")
Thread.Sleep(callDuration)
threadId = AppDomain.GetCurrentThreadId()
Return "MyCallTime was " + callDuration.ToString()
End Function
End Class
' The delegate must have the same signature as the method
' you want to call asynchronously.
Public Delegate Function AsyncDelegate(ByVal callDuration As Integer, _
<Out()> ByRef threadId As Integer) As String
Public Class AsyncMain
' The asynchronous method puts the thread id here.
Private Shared threadId As Integer
Shared Sub Main()
' Create an instance of the test class.
Dim ad As New AsyncDemo()
' Create the delegate.
Dim dlgt As New AsyncDelegate(AddressOf ad.TestMethod)
' Initiate the asynchronous call.
Dim ar As IAsyncResult = dlgt.BeginInvoke(3000, _
threadId, _
AddressOf CallbackMethod, _
dlgt)
Console.WriteLine("Press Enter to close application.")
Console.ReadLine()
End Sub
' Callback method must have the same signature as the
' AsyncCallback delegate.
Shared Sub CallbackMethod(ByVal ar As IAsyncResult)
' Retrieve the delegate.
Dim dlgt As AsyncDelegate = CType(ar.AsyncState, AsyncDelegate)
' Call EndInvoke to retrieve the results.
Dim ret As String = dlgt.EndInvoke(threadId, ar)
Console.WriteLine("The call executed on thread {0}, with return value ""{1}"".", threadId, ret)
End Sub
End Class
Why is CallbackMethod never reached in a WinForm application? Please note that I understand the difference between a Console application and a WinForm application.
The problem is the Console.ReadLine(). In a WinForms app this call does not block. Instead you can use Thread.Sleep(Timeout.Infinite) or whatever suits your needs best.

Null reference issue when adding services running on a terminal server to a dictionary

In VB.NET, I am trying to retrieve what services are running on a TS using the following code:
Imports System.ServiceProcess
...
Dim dictservice As Generic.Dictionary(Of String, Services)
Public Sub GetService()
Dim localServices As ServiceController() = ServiceController.GetServices()
For Each service As ServiceController In localServices
dictservice.Add(service.DisplayName, New Services(service.DisplayName, service.ServiceName, service.Status.ToString))
Next
End Sub
My services class is as follows:
Class Services
Private _displayName As String
Private _serviceName As String
Private _serviceStatus As String
Sub New(ByVal DisplayName As String, ByVal ServiceName As Object, ByVal ServiceStatus As String)
_displayName = DisplayName
_serviceName = ServiceName
_serviceStatus = ServiceStatus
End Sub
Public Overrides Function ToString() As String
Return _serviceStatus
End Function
End Class
When i step through in debug mode it seems to being to populate the dictionary
display name: Application Experience
service name: AElookUpSVC
service status: Running (4)
When it tries to move onto the next item i get the following error:
Null reference exception was unhandled:
Object reference not set to an instance of an object.
I can't for the life of me work out where it is finding a null reference?
You need to initialize your dictionary with New:
Dim dictservice As New Generic.Dictionary(Of String, Services)
Public Sub GetService()
Dim localServices As ServiceController() = ServiceController.GetServices()
For Each service As ServiceController In localServices
dictservice.Add(service.DisplayName, New Services(service.DisplayName, service.ServiceName, service.Status.ToString))
Next
End Sub
Right now it's Nothing, hence the NullReferenceException.
The most likely problem appears to be that dictService is Nothing and hence you get a NullReferenceException. Where do you initialize / declare dictService and are you certain the initialization happens before this method?
If this is not the problem have you tried running this with the debugger attached? it should point you to the line that is failing.