Skip to content

Commit

Permalink
Invalid certificates and Exchange connection errors fixed.
Browse files Browse the repository at this point in the history
1. New option for accepting invalid ssl certificate from Exchange server.
2. Reconnection after timeout if error occured while connecting to Exchange server.
3. Improved errors processing while while connecting to Exchange server.
  • Loading branch information
ddummy committed Jan 1, 2014
1 parent 6aba15a commit d595112
Show file tree
Hide file tree
Showing 6 changed files with 156 additions and 84 deletions.
2 changes: 2 additions & 0 deletions Exchposer/AppSettings.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ public class AppSettings : XmlSettings<AppSettings>
public string ExchangeUserName = "";
public string ExchangePasswordCrypted = "";
public int ExchangeSubscriptionLifetime = 30;
public bool ExchangeAcceptInvalidCertificate = false;
public string ExchangePassword
{
get { return Crypto.Decrypt(ExchangePasswordCrypted, SettingsPassword); }
Expand Down Expand Up @@ -52,6 +53,7 @@ public void Copy(AppSettings appSettings)
ExchangeUserName = appSettings.ExchangeUserName;
ExchangePasswordCrypted = appSettings.ExchangePasswordCrypted;
ExchangeSubscriptionLifetime = appSettings.ExchangeSubscriptionLifetime;
ExchangeAcceptInvalidCertificate = appSettings.ExchangeAcceptInvalidCertificate;
MailServerName = appSettings.MailServerName;
MailServerPort = appSettings.MailServerPort;
MailServerType = appSettings.MailServerType;
Expand Down
10 changes: 9 additions & 1 deletion Exchposer/CertificateCallback.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,13 @@ namespace Exchposer
{
public static class CertificateCallback
{
private static bool acceptInvalidCertificate = false;
public static bool AcceptInvalidCertificate
{
get { return acceptInvalidCertificate; }
set { acceptInvalidCertificate = value; }
}

static CertificateCallback()
{
ServicePointManager.ServerCertificateValidationCallback = CertificateValidationCallBack;
Expand Down Expand Up @@ -48,7 +55,8 @@ private static bool CertificateValidationCallBack(
{
// If there are any other errors in the certificate chain, the certificate is invalid,
// so the method returns false.
return false;
//return false;
return acceptInvalidCertificate;
}
}
}
Expand Down
144 changes: 84 additions & 60 deletions Exchposer/ExchangeServer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Timers;
using Microsoft.Exchange.WebServices.Data;

namespace Exchposer
Expand All @@ -20,22 +21,30 @@ public class ExchangeServer
private StreamingSubscriptionConnection subscriptionConnection = null;
private StreamingSubscription streamingSubscription = null;
private Action<EmailMessage> onReceive = null;
private int subscriptionConnectionLifetime = 0;

private readonly Action<int, string> logger = null;

private Timer restartTimer = new Timer();

protected void Log(int level, string message)
{
if (logger != null)
logger(level, message);
}

public ExchangeServer(string exchangeUserName, string exchangePassword, string exchangeDomain, string exchangeUrl, Action<int, string> logger = null)
public ExchangeServer(string exchangeUserName, string exchangePassword, string exchangeDomain, string exchangeUrl,
int restartTimeout, Action<int, string> logger = null)
{
this.logger = logger;
this.exchangeUserName = exchangeUserName;
this.exchangePassword = exchangePassword;
this.exchangeDomain = exchangeDomain;
this.exchangeUrl = exchangeUrl;

restartTimer.Elapsed += new ElapsedEventHandler(restartTimer_Elapsed);
restartTimer.Interval = restartTimeout * 1000;
restartTimer.AutoReset = false;
}

public void Open()
Expand All @@ -61,7 +70,12 @@ public void Open()

public void Close()
{
ClearStreamingNotifications();
Log(2, "Exchange server closing...");

StopStreamingNotifications();

this.onReceive = null;
this.subscriptionConnectionLifetime = 0;

if (service != null)
Log(2, "Exchange server closed");
Expand All @@ -71,6 +85,15 @@ public void Close()

public void ProcessMessages(DateTime fromTime, DateTime toTime, Action<EmailMessage> messageAction)
{
if (messageAction == null)
return;

if (service == null)
{
Log(2, "Exchange server is null");
return;
}

Folder inbox = Folder.Bind(service, WellKnownFolderName.Inbox);

SearchFilter sf = new SearchFilter.SearchFilterCollection(LogicalOperator.And,
Expand All @@ -86,8 +109,7 @@ public void ProcessMessages(DateTime fromTime, DateTime toTime, Action<EmailMess
FindItemsResults<Item> findResults = service.FindItems(WellKnownFolderName.Inbox, sf, view);

foreach (EmailMessage msg in findResults)
if (messageAction != null)
messageAction(msg);
messageAction(msg);

if (!findResults.MoreAvailable)
break;
Expand All @@ -109,13 +131,27 @@ public void LoadMessage(EmailMessage msg)
}));
}

public void SetStreamingNotifications(Action<EmailMessage> onReceive, int lifetime)
public void StartStreamingNotifications(Action<EmailMessage> onReceive, int lifetime)
{
this.onReceive = onReceive;
this.subscriptionConnectionLifetime = lifetime;

StartStreamingNotifications();
}

public void StartStreamingNotifications()
{
if (service == null)
{
Log(2, "Exchange server is null");
return;
}

StopStreamingNotifications();

try
{
subscriptionConnection = new StreamingSubscriptionConnection(service, lifetime);
subscriptionConnection = new StreamingSubscriptionConnection(service, subscriptionConnectionLifetime);
subscriptionConnection.OnNotificationEvent +=
new StreamingSubscriptionConnection.NotificationEventDelegate(OnEvent);
subscriptionConnection.OnSubscriptionError +=
Expand All @@ -126,68 +162,67 @@ public void SetStreamingNotifications(Action<EmailMessage> onReceive, int lifeti
catch (Exception ex)
{
Log(1, String.Format("Exchange subscription connection creating error: {0}", ex.Message));
ClearStreamingNotifications();
if (subscriptionConnection != null)
subscriptionConnection.Dispose();
subscriptionConnection = null;
return;
}

try
{
subscriptionConnection.AddSubscription(streamingSubscription = service.SubscribeToStreamingNotifications(
new FolderId[] { WellKnownFolderName.Inbox },
EventType.NewMail,
EventType.Created,
EventType.Deleted));
new FolderId[] { WellKnownFolderName.Inbox }, EventType.NewMail, EventType.Created, EventType.Deleted));
subscriptionConnection.Open();
}
catch (Exception ex)
{
Log(1, String.Format("Exchange subscription creating error: {0}", ex.Message));
ClearStreamingNotifications();
RestartStreamingNotifications();
return;
}

Log(2, "Exchange subscription started");
}

public void ClearStreamingNotifications()
public void StopStreamingNotifications()
{
restartTimer.Stop();

try
{
/*
if (subscriptionConnection != null)
subscriptionConnection.RemoveSubscription(streamingSubscription);
if (streamingSubscription != null)
streamingSubscription.Unsubscribe();
streamingSubscription = null;
if (subscriptionConnection != null)
subscriptionConnection.Close();
subscriptionConnection = null;
*/

if (subscriptionConnection != null)
{
subscriptionConnection.Close();
subscriptionConnection.RemoveSubscription(streamingSubscription);
var tmpStreamingSubscription = streamingSubscription;
streamingSubscription = null;
tmpStreamingSubscription.Unsubscribe();
}
subscriptionConnection = null;

if (streamingSubscription != null)
if (subscriptionConnection != null)
{
streamingSubscription.Unsubscribe();
if (subscriptionConnection.IsOpen)
subscriptionConnection.Close();
subscriptionConnection.Dispose();
subscriptionConnection = null;
Log(2, "Exchange subscription stopped");
}
streamingSubscription = null;


this.onReceive = null;
}
catch (Exception ex)
{
Log(1, String.Format("Exchange subscription stopping error: {0}", ex.Message));
}
}

public void RestartStreamingNotifications()
{
StopStreamingNotifications();
if (restartTimer.Interval != 0)
restartTimer.Start();
}

Log(2, "Exchange subscription stopped");
private void restartTimer_Elapsed(object source, ElapsedEventArgs e)
{
Log(2, "Restarting exchange streaming notification...");
StartStreamingNotifications();
}

private void OnEvent(object sender, NotificationEventArgs args)
Expand Down Expand Up @@ -226,44 +261,33 @@ private void OnEvent(object sender, NotificationEventArgs args)

private void OnError(object sender, SubscriptionErrorEventArgs args)
{
Log(3, String.Format("Exchange subscription error: {0} Resetting subscribtion...", args.Exception.Message));

/*
try
{
subscriptionConnection.Close();
//streamingSubscription.Unsubscribe();
//subscriptionConnection.RemoveSubscription(streamingSubscription);
}
catch (Exception ex)
{
Log(1, String.Format("Exchange subscription removing error: {0}", ex.Message));
}
*/
if (streamingSubscription == null)
return;

Log(3, String.Format("Exchange subscription error: {0} Restartting subscribtion...", args.Exception.Message));
RestartStreamingNotifications();
/*
try
{
subscriptionConnection.AddSubscription(streamingSubscription = service.SubscribeToStreamingNotifications(
new FolderId[] { WellKnownFolderName.Inbox },
EventType.NewMail,
EventType.Created,
EventType.Deleted));
if (service != null)
subscriptionConnection.AddSubscription(streamingSubscription = service.SubscribeToStreamingNotifications(
new FolderId[] { WellKnownFolderName.Inbox }, EventType.NewMail, EventType.Created, EventType.Deleted));
//subscriptionConnection.Open();
}
catch (Exception ex)
{
Log(1, String.Format("Exchange subscription creating error: {0}", ex.Message));
ClearStreamingNotifications();
return;
}
Log(2, "Exchange subscription started");
*/
}

private void OnDisconnect(object sender, SubscriptionErrorEventArgs args)
{
//if (streamingSubscription == null)
// return;
if (streamingSubscription == null)
return;

Log(3, String.Format("Exchange subscription disconnected. Reconnecting..."));

Expand All @@ -274,8 +298,8 @@ private void OnDisconnect(object sender, SubscriptionErrorEventArgs args)
}
catch (Exception ex)
{
Log(1, String.Format("Exchange subscription connection open error: {0}", ex.Message));
//ClearStreamingNotifications();
Log(1, String.Format("Exchange subscription connection open error: {0}", ex.Message));
RestartStreamingNotifications();
return;
}
}
Expand Down
Loading

0 comments on commit d595112

Please sign in to comment.