ConnectionChecker.cs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. namespace Wayne.Lib
  5. {
  6. /// <summary>
  7. /// Handles a collection of IConnectable items, and checks them all so they are connected.
  8. /// </summary>
  9. public class ConnectionChecker
  10. {
  11. private readonly IList<ConnectableItem> connectableItems = new List<ConnectableItem>();
  12. private readonly object connectableItemsLock=new object();
  13. /// <summary>
  14. /// Is all connectable items connected?
  15. /// </summary>
  16. /// <returns></returns>
  17. public bool IsConnectedToAll()
  18. {
  19. lock (connectableItemsLock)
  20. {
  21. foreach (var connectableItem in connectableItems)
  22. {
  23. if (connectableItem.Connectable.ConnectionState != DeviceConnectionState.Connected)
  24. return false;
  25. }
  26. }
  27. return true;
  28. }
  29. /// <summary>
  30. /// Adds a connectable entity to the check.
  31. /// </summary>
  32. /// <param name="connectable"></param>
  33. /// <param name="connectableDisplayName"></param>
  34. public void AddConnectableToCheck(IConnectable connectable, string connectableDisplayName)
  35. {
  36. if(connectable == null)
  37. throw new ArgumentNullException("connectable", "A instance of IConnectable is required.");
  38. connectableItems.Add(new ConnectableItem() { Connectable = connectable, DisplayName = connectableDisplayName});
  39. }
  40. /// <summary>
  41. /// Gets a list of strings containingt those items that are not connected, and their current connection state.
  42. /// </summary>
  43. /// <returns></returns>
  44. public IList<string> GetUnconnectedAsText()
  45. {
  46. IList<string> reasons = new List<string>();
  47. foreach (var connectableItem in connectableItems)
  48. {
  49. if (connectableItem.Connectable.ConnectionState != DeviceConnectionState.Connected)
  50. reasons.Add(connectableItem.DisplayName + ".ConnectionState = " + connectableItem.Connectable.ConnectionState);
  51. }
  52. return reasons;
  53. }
  54. class ConnectableItem
  55. {
  56. public IConnectable Connectable { get; set; }
  57. public string DisplayName { get; set; }
  58. }
  59. }
  60. }