EWS SubscribeToPullNotifications does not get new emails - vb.net

I had the following code written using EWS to subscribe to Pull notifications and read new emails. It was working all fine. All of a sudden it does not read the new emails. Any ideas what could the cause be? And how to resolve it?
Imports Microsoft.Exchange.WebServices.Data
Imports System.Threading
Public Class FormTest
Dim subscription As PullSubscription
Dim service As ExchangeService
Private Sub ButtonStart_Click(sender As Object, e As EventArgs) Handles ButtonStart.Click
service = New ExchangeService
service.Credentials = New WebCredentials("myusername", "mypassword", "mydomain")
service.Url = New Uri("https://webmail.mydomain.com/EWS/exchange.asmx")
subscription = service.SubscribeToPullNotifications(New FolderId() {WellKnownFolderName.Inbox}, 1440, Nothing, EventType.NewMail)
End Sub
Private Sub ButtonPoll_Click(sender As Object, e As EventArgs) Handles ButtonPoll.Click
PollEmails()
End Sub
Private Sub PollEmails()
Dim events As GetEventsResults = subscription.GetEvents()
For Each itemEvent As ItemEvent In events.ItemEvents
Dim message As EmailMessage = EmailMessage.Bind(service, itemEvent.ItemId)
message.Load()
' Do something with 'message'
Next
End Sub
End Class
Basically when I press ButtonPoll events does not contain any new evenets, even though there has been new emails since the ButtonStart was pressed.

Heyo!! I am doing something very similar. Looks like you have posted this question a month and a half ago so you may have solved it by now, but I wanted to put my initial experiences up here for anyone else that may be looking. The way I am posting below is a way to get notifications without having to push a poll button. This may help! I stripped all my fancy stuff out, as it is always important to learn, but this initial part of it was the most obnoxious part to figure out.
Imports System.Net
Imports System.Net.Security
Imports Microsoft.Exchange.WebServices.Data
Imports System.Security.Cryptography.X509Certificates
Public Class MainForm
Private Sub ExecuteButton_Click(sender As System.Object, e As System.EventArgs) Handles ExecuteButton.Click
Console.Clear()
Dim exch As ExchangeService = New ExchangeService(ExchangeVersion.Exchange2010_SP2)
exch.Url = New Uri("https://" + ExchangeURLTB.Text + "/EWS/Exchange.asmx")
exch.UseDefaultCredentials = False
exch.Credentials = New System.Net.NetworkCredential(UsernameTB.Text, PasswordTB.Text, DomainTB.Text)
ServicePointManager.ServerCertificateValidationCallback = New RemoteCertificateValidationCallback(AddressOf ValidateCertificate)
Dim subscribeStreaming As StreamingSubscription = exch.SubscribeToStreamingNotifications(New FolderId() {WellKnownFolderName.Inbox}, EventType.NewMail, EventType.Created, EventType.Deleted)
Dim subscribeStreamingConnection = New StreamingSubscriptionConnection(exch, 30)
subscribeStreamingConnection.AddSubscription(subscribeStreaming)
AddHandler subscribeStreamingConnection.OnNotificationEvent, AddressOf OnNotificationEvent
AddHandler subscribeStreamingConnection.OnSubscriptionError, AddressOf OnSubscriptionError
AddHandler subscribeStreamingConnection.OnDisconnect, AddressOf OnDisconnect
subscribeStreamingConnection.Open()
Console.Write("Steaming subscription open")
End Sub
Private Sub OnNotificationEvent(sender As Object, args As NotificationEventArgs)
Dim subscription As StreamingSubscription = args.Subscription
For Each notification As NotificationEvent In args.Events
Select Case notification.EventType
Case EventType.NewMail
Console.WriteLine(vbNewLine)
Console.WriteLine("-------------Mail created:-------------")
End Select
Next
End Sub
Private Sub OnSubscriptionError(sender As Object, args As SubscriptionErrorEventArgs)
End Sub
Private Sub OnDisconnect(sender As Object, args As SubscriptionErrorEventArgs)
End Sub
Private Function ValidateCertificate(ByVal sender As Object, ByVal certificate As X509Certificate, ByVal chain As X509Chain, ByVal sslPolicyErrors As SslPolicyErrors) As Boolean
'Return True to force the certificate to be accepted.
Return True
End Function
End Class

Related

Getting an access denied error when trying to pause/resume an outgoing message queue

Imports System.Messaging
Imports System.Collections
Imports MSMQ
Imports System.IO
Imports System
Imports System.Messaging.MessageQueue
Imports System.Runtime.InteropServices
Public Class PauseOutMessages
'Declare everything to be in the scope of all methods.
Dim mgmt As New MSMQManagement
Dim outqmgmt As MSMQOutgoingQueueManagement
Dim q As New MSMQApplication
Dim outgoingQueues As New ArrayList
Dim myQueue As New MessageQueue("FormatName:DIRECT=OS:myMachine\Private$\myQueue", QueueAccessMode.ReceiveAndAdmin)
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
For Each queue In q.ActiveQueues
If queue.IndexOf("DIRECT=") >= 0 Then
outgoingQueues.Add(queue)
End If
Next
End Sub
Private Sub Pause_Click(sender As Object, e As EventArgs) Handles Pause.Click
For Each queuePath In outgoingQueues
mgmt.Init(FormatName:=queuePath)
outqmgmt = mgmt.Pause()
Next
End Sub
Private Sub Restart_Click(sender As Object, e As EventArgs) Handles Restart.Click
For Each queuePath In outgoingQueues
mgmt.Init(FormatName:=queuePath)
outqmgmt = mgmt.Resume()
Next
End Sub
Private Sub Send_Click(sender As Object, e As EventArgs) Handles Send.Click
myQueue.Send("Test")
For Each queue In q.ActiveQueues
If queue.IndexOf("DIRECT=") >= 0 Then
outgoingQueues.Add(queue)
End If
Next
End Sub
End Class
Here is the code I am using, by sending the test message to a non-existing path it gets stuck in the outgoing queue where I want to be able to call MSMQOutgoingQueueManagement.Pause or .Resume to be able to start and stop all outgoing queues.
However I keep getting an error on either mgmt.Pause() or mgmt.Resume() saying Access is denied. I can't seem to find a way to get on to the properties of outgoing queues to be able to adjust security settings. Any help would be greatly appreciated!
SOLVED!
Turns out I just needed to start up visual studio as an administrator and then it worked.

Bug on login form while trying to close the app vb.net

So currently I am using a code which provides me the possibility to manager whenever or not the application will logout or keep on track. Basically if the user is not using the program for quite some time it will move to the Login form and of course if the user wants to login back he had to type again.
I got a class where I am able to produce more or less that code:
Public Class TimerWatcher
Private _timer As System.Threading.Timer
Private _enabled As Boolean
Private _lastEvent As DateTime
Public Sub New()
_timer = New System.Threading.Timer(AddressOf watch)
_enabled = False
Timeout = 0
End Sub
Public Event Idle(sender As Form)
Public Property Timeout As Long
Public Property Enabled As Boolean
Get
Return _enabled
End Get
Set(value As Boolean)
If value Then
_lastEvent = DateTime.Now
_timer.Change(0, 1000)
Else
_timer.Change(System.Threading.Timeout.Infinite, System.Threading.Timeout.Infinite)
End If
End Set
End Property
Private Sub watch()
If DateTime.Now.Subtract(_lastEvent).TotalMilliseconds > Timeout Then
Enabled = False
' "End" is quite blunt. You may want to raise an event
' so the form can terminate the application gracefully.
RaiseEvent Idle(Login)
End If
End Sub
Public Sub Refresh()
_lastEvent = DateTime.Now
End Sub
End Class
And then on my main form I got this:
Private Sub MainForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load
watcher.Timeout = 5000
watcher.Enabled = True
End Sub
Private Sub PaginaInicial_MouseMove(sender As Object, e As MouseEventArgs) Handles Me.MouseMove
watcher.Refresh()
End Sub
Private Sub watcher_idle(sender As Form) Handles watcher.Idle
Dim logIN = New Login
If MsgBox("The application will close, are you sure you want to do it?", MsgBoxStyle.YesNo) = MsgBoxResult.Yes Then
logIN.Show()
Else
End If
End Sub
But, because some bug I am not able to return the Login form...And this is what happen to the form after I click yes on the MessageBox. The login form crash or something
Do you have any idea how I can solve this bug?

Form on top but not clickable when modal dialog is shown

What I want is a small notification message that is shown in the lower right corner when there are any messages to be shown. If there are none the notification message will not be shown. The notification message should not steal focus or block the main application.
What I have is an application that runs a Task as a kind of messageservice. This application contains multiple dialogs that opens as modal dialogs.
When a message arrives to the application it is added to a observable list. This fires an eventhandler in the form showing the notification message and it is redrawn to show the first item in the list.
When a message is read/closed it is removed from the list which fires the event again and the form is updated with the information from the first item in the list.
If the list is empty the form is hidden.
My problem is that if i get a message and the notification message form is shown, and before I close it a modal dialog is opened in the main application, my form with the notification message is still on top of everything, even the modal dialog, but it's not clickable.
I've searched and read several forums for an answer but haven't been able to come up with an answer.
A small testapplication that simulates this behaviour can be found at Github.
https://github.com/Oneleg/NotificationMessage
Some fast info:
The NotificationMessage form has:
FormBorderStyle = None
Topmost = False
Is shown with Show()
Overloads ShowWithoutActivation()
Overloads CreateParams with WS_EX_NOACTIVATE WS_EX_TOOLWINDOW WS_EX_TOPMOST
Any ideas on how I could solve this?
Looks like I'll be able to answer my own question.
The answer is to create the NotificationMessage as an application withs it's own messagepump.
Application.Run(New NotificationMessage(_messageList))
After some modifications my Main now looks like this:
Imports System.Threading
Imports System.Threading.Tasks
Public Class frmMain
Private _notificationMessage As NotificationMessage
Private _task As Task
Private _messageList As ObservableGenericList(Of String) = New ObservableGenericList(Of String)
Private ReadOnly _cancelMessages As CancellationTokenSource = New CancellationTokenSource()
Private Sub btnModal_Click(sender As System.Object, e As System.EventArgs) Handles btnModal.Click
frmModal.ShowDialog()
End Sub
Private Sub frmMain_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
AddHandler _messageList.Changed, AddressOf MessageListChanged
End Sub
Private Sub NotificationMessageLoop(mess As String)
_notificationMessage = New NotificationMessage(_messageList)
_messageList.Add(mess)
Application.Run(_notificationMessage)
End Sub
Private Sub btnMessage_Click(sender As System.Object, e As System.EventArgs) Handles btnMessage.Click
Dim newMessage = String.Format("Message no {0}", _messageList.Count + 1)
If _task Is Nothing Then
_task = Task.Factory.StartNew(Sub() NotificationMessageLoop(newMessage), _cancelMessages.Token)
Else
_messageList.Add(newMessage)
End If
End Sub
Private Sub MessageListChanged()
If Not _messageList.Any Then
_cancelMessages.Cancel()
End If
End Sub
End Class
And the NotificationMessage looks like this:
Imports System.Runtime.InteropServices
Public Class NotificationMessage
Public Sub New(messages As ObservableGenericList(Of String))
InitializeComponent()
_messages = messages
AddHandler _messages.Changed, AddressOf ListChanged
End Sub
Private ReadOnly _messages As ObservableGenericList(Of String)
Private Delegate Sub ListChangedDelegate()
Private Sub ListChanged()
If InvokeRequired Then
BeginInvoke(New ListChangedDelegate(AddressOf ListChanged))
Return
End If
If _messages.Any Then
Dim message As String = _messages.First
txtMessage.Text = message
lblCounter.Text = String.Format("({0} messages)", _messages.Count)
Show()
Else
Hide()
End If
End Sub
Private Sub MessageLoad(sender As System.Object, e As EventArgs) Handles MyBase.Load
Left = Screen.PrimaryScreen.WorkingArea.Width - Width
Top = Screen.PrimaryScreen.WorkingArea.Height - Height
End Sub
Private Sub btnClose_Click(sender As System.Object, e As System.EventArgs) Handles btnClose.Click
_messages.RemoveFirst()
End Sub
#Region "Overrides"
Private Const WS_EX_NOACTIVATE = &H8000000 ' Do not steal focus
Private Const WS_EX_TOOLWINDOW = &H80 ' Makes form hidden from Alt + Tab window
Private Const WS_EX_TOPMOST = &H8 ' Makes window topmost
''' <summary> Indicates whether the window will be activated when it is shown. </summary>
''' <remarks> http://msdn.microsoft.com/en-us/library/system.windows.forms.form.showwithoutactivation.aspx </remarks>
Protected Overrides ReadOnly Property ShowWithoutActivation() As Boolean
Get
Return True
End Get
End Property
''' <summary> Override for creation parameters that are set when control handle is created. </summary>
Protected Overrides ReadOnly Property CreateParams() As CreateParams
Get
Dim params As CreateParams = MyBase.CreateParams
params.ExStyle = params.ExStyle Or WS_EX_NOACTIVATE Or WS_EX_TOOLWINDOW Or WS_EX_TOPMOST
Return params
End Get
End Property
#End Region
End Class
I now have a notification message that is only visible when there are any messages to show, doesn't steal focus when a new message arrives, is always on top and is clickable even after a modal form is opened in the main application.

How is it possible to parse the URL of the desired popup to the popup-form AND show hints/tooltips in the WebKit-Component?

I'm trying to use the WebKit-component (http://www.webkit.org/) in VB with the help of Visual Studio 2008.
This is running without problems, except for two following two issues:
1. Hints/Tooltips are not shown (e.g. as there usually will appear one if you stay with the mouse over the Google-logo)
2. If there's a popup-window, I don't know how to get the new desired URL.
I'm already working a few days on this matter and couldn't find any solution yet :(
Maybe you know a solution to this problem.
Cheers
Markus G.
P.S.: If you need more than the following Source Code to analyze the problem, then let me know ...
Source Code Form1
Imports System.IO
Imports WebKit
Public Class frmMain
Private _url As String
Private _mode As String
Private _popupUrl As String
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
On Error Resume Next
Dim bLogging As Boolean
setWindowAndBrowserSettings()
_url = "http://www.google.com"
browserComp.Navigate(_url)
End Sub
Private Sub setWindowAndBrowserSettings()
Me.Text = "Test - Browser"
Me.WindowState = FormWindowState.Maximized
browserComp.Dock = DockStyle.Fill
browserComp.Visible = True
End Sub
Private Sub browserComp_NewWindowCreated(ByVal sender As Object, ByVal e As WebKit.NewWindowCreatedEventArgs) Handles browserComp.NewWindowCreated
'frmPopup.WindowState = FormWindowState.Maximized
frmPopup.Text = "ixserv - POPUP"
frmPopup.popup.Navigate(_popupUrl)
frmPopup.Show()
End Sub
Private Sub browserComp_NewWindowRequest(ByVal sender As Object, ByVal e As WebKit.NewWindowRequestEventArgs) Handles browserComp.NewWindowRequest
e.Cancel = False
_popupUrl = browserComp.Url.ToString ' WHERE can I get the clicked URL? This is the old one of the remaining window
End Sub
End Class
Code Form2
Public Class frmPopup
End Class
Following popup/new-Window-Create-function works for me:
Private Sub browserComp_NewWindowCreated(ByVal sender As Object, ByVal e As WebKit.NewWindowCreatedEventArgs) Handles browserComp.NewWindowCreated
frmPopup.Text = "POPUP"
Dim popupBrowser As WebKit.WebKitBrowser
popupBrowser = e.WebKitBrowser
frmPopup.Controls.Add(popupBrowser)
frmPopup.Show()
End Sub
whereas frmPopup is a new form.
Before I tried this I already added the Webkit-component to the new form, which might had been the problem. I assume, the trick is, to create a new WebKitBrower-element that is directly connected to the argument e.WebkitBrowser instead of overloading an existing webkitbrowser-component in the form. Don't ask me for reasons for this now (I really don't know) :P
Oh, I should add that I used the Webkit.NET component. The same trick works also for the OpenWebkitSharp-wrapper
The hint-problem still remains ...

How to raise events from class library to form using module?

i've a app that starts from a sub in a module, do a few things, and then load the form.
But it doesn't work :/
Here we execute dBase.AddTemporalFilepath
module.vb
Public dBase As New Core.clsDatabase
Public Sub Main()
FurBase.Directory = My.Application.Info.DirectoryPath
If appMutex.WaitOne(TimeSpan.Zero, True) Then
ShowUploader()
End If
Dim returnValue As String()
returnValue = Environment.GetCommandLineArgs()
If returnValue.Length > 1 Then
If My.Computer.FileSystem.FileExists(returnValue(1).ToString) Then
dBase.AddTemporalFilepath(returnValue(1).ToString)
End If
End If
End Sub
Private Sub ShowUploader()
Application.EnableVisualStyles()
Application.Run(frmUploader)
End Sub
We raise the event TempFilepathAdded
clsDatabase.vb
Public Class clsDatabase
Public Event TempFilepathAdded()
Public Function AddTemporalFilepath(ByVal filepath As String)
...
RaiseEvent TempFilepathAdded()
...
End Function
End Class
We catch the event
form.vb
Private Sub form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
AddHandler dBase.TempFilepathAdded, AddressOf TempFilepathAddedHandler
End Sub
Private Sub TempFilepathAddedHandler()
MsgBox("Event raised")
End Sub
Any Idea?
More info:
The event is raised when the form is closed.
The line "Application.Run(frmUploader)" pauses your program until the Window closes. Basically it hijacks the main thread to handle stuff like users clicking buttons.
Normally your Main function should look like this:
Setup
Application.Run
Clean-up
Sorry, but it looks like its time to reorganize your code.