calling webservice asynchronously in vb.net - vb.net

I am trying to call this webservice asynchrounously in vb.net. So on the aspx side i added this property async="true". Now on the vb.net code side i have this function inside my webservice that i am calling.
So -
dim as as webservice.webstring
as.functionasync(param1, param2)
Now when i run the page, i can see that it wont call the webservice after a timegap.
Should i add .thread.sleep()?
Do i require the beginAsyn function and the EndAsyn function.
I'm using asp.net 3.5 with IIS7

First, please read this MSDN article about how the asynchronous pages work in ASP.NET.
Second, you need to have an asynchronous method in your web-service. Please read this HOWTO article about how to create such methods.
This is how your implementation of the async page could look like:
private _as as WebService.WebString = Nothing
Public Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles MyBase.Load
AddOnPreRenderCompleteAsync(New BeginEventHandler(BeginCallingWebService),
New EndEventHandler(EndCallingWebService));
End Sub
Private Function BeginCallingWebService(Byval sender As Object, ByVal e As EventArgs, ByVal cb As AsyncCallback, ByVal state As Object)
_as = New WebService.WebString()
Return _as.BeginMyMethod(cb, state)
End Function
Private Sub EndCallingWebService(ByVal ar as IAsyncResult)
Dim result As MyWebServiceResult = _as.EndMyMethod(ar)
' Process the result of the web-service method
End Sub
Hope this will help you.

Related

Send a form to a sub declared in a DLL files

I'm trying to create (finally) my own DLL files to some code that I will use constantly in a new project, I'm using Visual Basic 2010
I created the DLL correctly but I got a problem with a sub have the code Me.Handle
I don't know how to send the "me" to my sub
This is my sub (from an example in msdn)
Sub Start_Detection()
Dim di As New DEV_BROADCAST_DEVICEINTERFACE
di.dbcc_size = CUInt(Marshal.SizeOf(GetType(DEV_BROADCAST_DEVICEINTERFACE)))
di.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE
di.dbcc_reserved = 0
di.dbcc_classguid = Guid.Parse("{88BAE032-5A81-49f0-BC3D-A4FF138216D6}")
di.dbcc_name = Nothing
hDevNotify = RegisterDeviceNotification(Me.Handle, di, DEVICE_NOTIFY_WINDOW_HANDLE)
End Sub
When I put that inside a DLL, I don't know how to send the Me because in the DLL project says that "Me" isn't a member of my DLL project.
If I declare the sub as Sub Start_Detection(ByRef Form) or Sub Start_Detection(ByVal Form) the DLL project works ok, but when I call it from the windows form project a "Null Reference Exception" happen.
Is not possible to send forms as arguments in Visual Basic 2010 ?
Thanks!
Edit: I'm calling the sub in this way
Private Sub Frm_Config_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
MyDLL.Start_Detection(Me)
End Sub
You might also want to consider using the following naming convention for the parameter
Sub Start_Detection (ByVal sender As System.Object)
or
Sub Start_Detection (ByVal handle As IntPtr)
When your calling the method, pass the handle value to the Class method
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
If Me.IsHandleCreated Then
RecieveHandle.Start_Detection(Me.Handle)
End If
End Sub
Then once your in the class module, you can do a common trick to confirm the variable has been supplied and don't pass a reference to the whole form via the "Me" (VB) or "This" (C#) variable.
Public Class RecieveHandle
Public Shared Sub Start_Detection(ByVal sender As System.Object)
If sender Is Nothing Then
Throw New ArgumentException("Method requires sender parameter to be supplied")
End If
If Not TypeOf (sender) Is IntPtr Then
Throw New ArgumentException("Method requires a valid pointer (handle) to the form.")
End If
Dim myFormHandle As IntPtr = CType(sender, IntPtr)
Debug.Print(myFormHandle.ToInt64.ToString)
End Sub
End Class
Me belongs to a form not a dll. If you pass the IntPtr you will be fine.
Sub Start_Detection(ptr As IntPtr)
Dim di As New DEV_BROADCAST_DEVICEINTERFACE
di.dbcc_size = CUInt(Marshal.SizeOf(GetType(DEV_BROADCAST_DEVICEINTERFACE)))
di.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE
di.dbcc_reserved = 0
di.dbcc_classguid = Guid.Parse("{88BAE032-5A81-49f0-BC3D-A4FF138216D6}")
di.dbcc_name = Nothing
hDevNotify = RegisterDeviceNotification(ptr, di, DEVICE_NOTIFY_WINDOW_HANDLE)
End Sub
Usage:
Start_Detection(Me.Handle)

vb.net task.delay locks browser

I am trying to do a very simple job in vb.net 4.5 framework; Create and run a simple Async Task that will symbolize (making several database calls asynchrnously/ parallel).
I am using vs2012 and vb.net Very simple MVC app and one control.
The code is simple>
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim newTask As Task(Of String) = TryPause()
lblResults2.Text = newTask.Result
End Sub
Public Async Function TryPause() As Task(Of String)
Await Task.Delay(100)
Return "hello World"
End Function
Code runs fine when the "task.delay" is remarked out.
But if it stays inside of the code, the Browser locks up.
Notice: thread.sleep works fine....
What am i missing?
As #SLaks correctly pointed out, the Result is causing a deadlock. I explain this in more detail on my blog and in a recent MSDN article.

Simulate a button click within the application (VB.NET)

Good day,
In my application, I have Private Sub btnSendSMS_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSendMessage.Click in my program.
I would like to simulate a button click of the above within my other sub (an SMS receive detector) when an SMS is received.
How do I do this? I know this is not the best way of doing things but just for the sake of learning. Thanks.
You can call the Button.PerformClick method:
btnSendSMS.PerformClick()
You can call the function directly.
btnSendSMS_Click(Me, EventArgs.Empty)
Why don't you put the code in a seperate method
Private Sub SendSMS()
' do your thing
End Sub
and in your button event handler, call that method.
Private Sub btnSendSMS_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSendMessage.Click
Call SendSMS()
End Sub
Now you can call SendSMS() anywhere in your class without having to do something funky like simulating button clicks.
Or in case of using VB in WPF:
Dim peer As New ButtonAutomationPeer(btnSendSMS)
Dim invokeProv As IInvokeProvider = TryCast(peer.GetPattern(PatternInterface.Invoke), IInvokeProvider)
invokeProv.Invoke()

using GoogleEarth plugin from VB.NET through FC.GEPluginCtrls

I'm really looking for a simple way to build VB.NET apps that use the GEplugin. So I have found this project that seems to do the dirty job I need: http://code.google.com/p/winforms-geplugin-control-library/
Well, all the code posted there around works on C#, but I need to have it on VB.NET. So I have tried this:
created a new 32-bit solution from VB.NET 2010 Express (I simply added
<PlatformTarget>x86</PlatformTarget >
inside the .vbproj file)
added a reference to FC.GEPluginCtrls.dll
inserted a GeWebBrowser control on the form
at the top of the code, added
Imports FC.GEPluginCtrls
then, in the form Load event, put this code:
InitializeComponent()
GeWebBrowser1.LoadEmbeddedPlugin()
Do
Loop Until GeWebBrowser1.PluginIsReady = False
GeWebBrowser1.CreateInstance(ImageryBase.Earth)
that, I think, would be equivalent to
http://code.google.com/p/winforms-geplugin-control-library/wiki/CreateInstance
So, the project compiles and doesn't get errors, but the GeWebBrowser control remains empty.
I actually wrote the library you are using. You are not listening for the PluginReady event. http://code.google.com/p/winforms-geplugin-control-library/wiki/PluginReady
To use it with VB simply convert the basic examples to VB -
http://code.google.com/p/winforms-geplugin-control-library/wiki/ExampleForm
Also, a loop polling PluginIsReady is totally unnecessary as the PluginReady event is asynchronous.
To show the earth all you would need is the following.
Private Sub Form1_Load( ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
GeWebBrowser1.LoadEmbeddedPlugin()
End Sub
To use the plugin when it has initialzesd use the PluginReady event. Something like.
Option Strict Off
Public Class Form1
Private Dim _ge as Object = Nothing
Private Sub GeWebBrowser1_PluginReady( ByVal sender As System.Object, ByVal e As FC.GEPluginCtrls.GEEventArgs) Handles GeWebBrowser1.PluginReady
_ge = e.ApiObject ' reference to the Google Earth Plugin object
MessageBox.Show(_ge.getApiVersion()) ' _ge is the plugin -use it just as in the javascript api...
End Sub
Private Sub Form1_Load( ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
GeWebBrowser1.LoadEmbeddedPlugin() ' load the plugin
End Sub
End Class

VB.NET DownloadDataAsync:

I am having the worst trouble getting around a bug, and am hoping that I can get some advice on this site. In short, I am trying to make an asynchronous web service call from my VB.NET application. But my "client_DownloadDataCompleted" callback is NEVER being called when the download is complete.
Here is my complete code:
Public Sub BeginAsyncDownload(ByVal Url As String)
Dim waiter As System.Threading.AutoResetEvent = New System.Threading.AutoResetEvent(False)
Dim client As WebClient = New WebClient()
'client_DownloadDataCompleted method gets called when the download completes.
AddHandler client.DownloadDataCompleted, AddressOf client_DownloadDataCompleted
Dim uri As Uri = New Uri(Url)
Downloading = True 'Class variable defined elsewhere
client.DownloadDataAsync(uri, waiter)
End Sub
Private Sub client_DownloadDataCompleted(ByVal sender As Object, ByVal e As AsyncCompletedEventArgs)
MessageBox.Show("Download Completed")
Downloading = False
Debug.Print("Downloaded")
End Sub
Again, the client_DownloadDataCompleted method is never being called. I have also tried using the method:
Private Sub client_DownloadDataCompleted(ByVal sender As Object, ByVal e As DownloadDataCompletedEventArgs)
With no luck. What I really need is that "Downloading" variable to be switched off when the download is complete.
Thanks in advance!
Brett
The client (Webclient) should be declared outside the BeginAsyncDownload subroutine, so it has a form/class level visibility. Please refer to the following code:
Public Class Form1
Dim client as New WebClient()
Private Sub BeginAsyncDownload(ByVal Url As String)
AddHandler client.DownloadDataCompleted, AddressOf client_DownloadDataCompleted
Dim uri As Uri = New Uri(Url)
Downloading = True 'Class variable defined elsewhere
client.DownloadDataAsync(uri, waiter)
End Sub
Private Sub client_DownloadStringCompleted(ByVal sender As Object, ByVal e As System.Net.DownloadStringCompletedEventArgs)
MessageBox.Show("Download Completed")
Downloading = False
Debug.Print("Downloaded")
End Sub
This is a tough one. I spent a little time on this and wasn't able to figure out why it wasn't getting called, sorry.
If you aren't able to get this to work, I have some code on CodePlex that includes a WebHelper class that might help you. I tried to make it as easy to use as WebClient but with all the power of HttpWebRequest.
The project is called BizArk. I wrote it just as a repository of code for myself. Feel free to just use the bits you want, I don't have any particular interest in how the code is used (as long as it's not used for evil :).
In what context are you invoking the webclient? WebClient will pick up your SynchronizationContext.Current and post its completion callback to it.
If you are using WinForms and your UI thread is blocked it will never be able to process your callback.