#region File and License Information
/*
<File>
<Copyright>Copyright © 2007, Daniel Vaughan. All rights reserved.</Copyright>
<License>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the <organization> nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY <copyright holder> ''AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
</License>
<Owner Name="Daniel Vaughan" Email="dbvaughan@gmail.com"/>
<CreationDate>2009-05-17 19:08:35Z</CreationDate>
</File>
*/
#endregion
using System;
using System.Net.NetworkInformation;
using System.Threading;
using System.Timers;
using System.Windows.Threading;
using DanielVaughan.Calcium.Client.Communication;
using DanielVaughan.Calcium.ClientServices;
using DanielVaughan.ServiceModel;
using Microsoft.Practices.Composite.Events;
using Microsoft.Practices.Composite.Modularity;
using Timer=System.Timers.Timer;
namespace DanielVaughan.Calcium.Client.Modules.Communication
{
/* TODO: [DV] Comment. */
[Module(ModuleName = ModuleNames.Communication)]
public class CommunicationModule : IModule
{
Timer timer;
int timerIntervalMs = 10000;
bool connecting;
readonly object connectingLock = new object();
readonly CommunicationCallback callback = new CommunicationCallback();
ConnectionEvent connectionEvent;
bool connected;
public bool Connected
{
get
{
return connected;
}
}
/// <summary>
/// Gets or sets the timer interval in milliseconds.
/// This is the time between notifying the server
/// that the client is still alive.
/// TODO: Make configurable either in config or user options.
/// </summary>
/// <value>The timer interval in milliseconds.</value>
public int TimerIntervalMs
{
get
{
return timerIntervalMs;
}
set
{
if (timerIntervalMs != value)
{
timerIntervalMs = value;
timer.Interval = value;
}
}
}
public void Initialize()
{
NetworkChange.NetworkAvailabilityChanged += OnNetworkAvailabilityChanged;
timer = new Timer(timerIntervalMs);
timer.Elapsed += TimerTick;
timer.Start();
var eventAggregator = UnitySingleton.Container.Resolve<IEventAggregator>();
var updateRequestedEvent = eventAggregator.GetEvent<UsersUpdateRequestedEvent>();
updateRequestedEvent.Subscribe(OnUsersUpdateRequested);
connectionEvent = eventAggregator.GetEvent<ConnectionEvent>();
}
void OnUsersUpdateRequested(object obj)
{
ThreadPool.QueueUserWorkItem(delegate
{
var channelManager = UnitySingleton.Container.Resolve<IChannelManager>();
var communicationService = channelManager.GetDuplexChannel<ICommunicationService>(callback);
var eventAggregator = UnitySingleton.Container.Resolve<IEventAggregator>();
var updateRequestedEvent = eventAggregator.GetEvent<UsersUpdateEvent>();
var users = communicationService.GetConnectedUsers();
var dispatcher = UnitySingleton.Container.Resolve<Dispatcher>();
dispatcher.InvokeIfRequired(() => updateRequestedEvent.Publish(users));
});
}
void OnNetworkAvailabilityChanged(object sender, NetworkAvailabilityEventArgs e)
{
timer.Enabled = e.IsAvailable;
}
void TimerTick(Object notused, ElapsedEventArgs e)
{
NotifyAlive();
}
void NotifyAlive()
{
if (!connecting)
{
lock (connectingLock)
{
if (!connecting)
{
connecting = true;
ThreadPool.QueueUserWorkItem(NotifyAliveAux);
}
}
}
}
Type lastExceptionType;
/// <summary>
/// Notifies the server communication service that the client is still alive.
/// Occurs on a ThreadPool thread. <see cref="NotifyAlive"/>
/// </summary>
/// <param name="state">The unused state.</param>
void NotifyAliveAux(object state)
{
try
{
if (!NetworkInterface.GetIsNetworkAvailable())
{
return;
}
var channelManager = UnitySingleton.Container.Resolve<IChannelManager>();
var communicationService = channelManager.GetDuplexChannel<ICommunicationService>(callback);
communicationService.NotifyAlive();
if (!connected)
{
connected = true;
connectionEvent.Publish(ConnectionState.Connected);
}
lastExceptionType = null;
}
catch (Exception ex)
{
Type exceptionType = ex.GetType();
if (exceptionType != lastExceptionType)
{
Log.Warn("Unable to connect to communication service.", ex);
}
lastExceptionType = exceptionType;
if (connected)
{
connected = false;
connectionEvent.Publish(ConnectionState.Disconnected);
}
}
finally
{
connecting = false;
}
}
}
}