If you are building an OOB application with Silverlight that relies on web services, you may have some interesting challenges on you hands. You probably want to have some fallback for certain operations when the network is down. You can do some fun stuff with caches and message queuing, but there still may be certain operations that you just don’t want to be available when the network is down. Here’s a solution you can build using Caliburn’s filters that will automatically disable UI attached to decorated actions when the network becomes unavailable:
public interface INetwork : INotifyPropertyChanged
{
bool IsAvailable { get; }
}
public class Network : PropertyChangedBase, INetwork
{
private bool _isAvailable;
public Network()
{
IsAvailable = NetworkInterface.GetIsNetworkAvailable();
NetworkChange.NetworkAddressChanged += NetworkAddressChanged;
}
public bool IsAvailable
{
get { return _isAvailable; }
private set
{
_isAvailable = value;
NotifyOfPropertyChange("IsAvailable");
}
}
private void NetworkAddressChanged(object sender, EventArgs e)
{
IsAvailable = NetworkInterface.GetIsNetworkAvailable();
}
}
public class NotAvailableOfflineAttribute : Attribute, IPreProcessor, IHandlerAware
{
private static readonly INetwork _network = ServiceLocator.Current.GetInstance<INetwork>();
private IMessageTrigger _trigger;
public int Priority
{
get { return 100; }
}
public bool AffectsTriggers
{
get { return true; }
}
public bool Execute(IRoutedMessage message, IInteractionNode handlingNode, object[] parameters)
{
return _network.IsAvailable;
}
public void MakeAwareOf(IRoutedMessageHandler messageHandler)
{
_network.PropertyChanged += (s, e) =>{
if(e.PropertyName == "IsAvailable" && _trigger != null)
messageHandler.UpdateAvailability(_trigger);
};
}
public void MakeAwareOf(IRoutedMessageHandler messageHandler, IMessageTrigger trigger)
{
_trigger = trigger;
}
}
And you use it like this:
public class MyViewModel
{
[NotAvailableOffline]
public void AccessNetwork()
{
//Do something networky here...
}
}
Posted
11-24-2009 11:11 PM
by
Rob Eisenberg