Changeset 1616


Ignore:
Timestamp:
Jun 10, 2010, 1:39:21 PM (11 years ago)
Author:
Paul Lelgemann
Message:

o CrypP2P: Code cleanup
o P2PEditor: job list will be reloaded in a BackgroundWorker

Location:
trunk
Files:
3 added
14 edited

Legend:

Unmodified
Added
Removed
  • trunk/CrypP2P/CrypP2P.csproj

    r1528 r1616  
    189189  </ItemGroup>
    190190  <ItemGroup>
     191    <Compile Include="Helper\SettingsHelper.cs" />
     192    <Compile Include="Internal\ConnectionManager.cs" />
    191193    <Compile Include="Internal\NotConnectedException.cs" />
    192194    <Compile Include="P2PSettings.Designer.cs">
  • trunk/CrypP2P/Helper/PAPCertificate.cs

    r1458 r1616  
    414414            string applicationDir = System.IO.Path.GetDirectoryName(assemb.Location);
    415415            // check if all necessary certs are installed
    416             P2PManager.Instance.GuiLogMessage("Check installation of all certificates, which are necessary to run the p2p system", NotificationLevel.Info);
     416            P2PManager.GuiLogMessage("Validating installation of P2P certificates.", NotificationLevel.Info);
    417417            List<PAPCertificate.PAP_Certificates> lstMissingCerts = PAPCertificate.CheckAvailabilityOfPAPCertificates(applicationDir);
    418418            if (lstMissingCerts.Count == 0)
     
    428428                    sbMissingCerts.AppendLine(Enum.GetName(typeof(PAPCertificate.PAP_Certificates), lstMissingCerts[i]));
    429429                }
    430                 P2PManager.Instance.GuiLogMessage("Following certificates are missing. They will be installed now.\n" + sbMissingCerts.ToString(), NotificationLevel.Info);
     430                P2PManager.GuiLogMessage("Following certificates are missing. They will be installed now.\n" + sbMissingCerts.ToString(), NotificationLevel.Info);
    431431
    432432                // try/catch neccessary because the CT-Editor doesn't support the whole exception display process (e.g. shows only "unknown error.")
     
    435435                    if (PAPCertificate.InstallMissingCertificates(lstMissingCerts, applicationDir))
    436436                    {
    437                         P2PManager.Instance.GuiLogMessage("Installation of all missing certificates was successful.", NotificationLevel.Info);
     437                        P2PManager.GuiLogMessage("Installation of all missing certificates was successful.", NotificationLevel.Info);
    438438                        retValue = true;
    439439                    }
    440440                    else
    441441                    {
    442                         P2PManager.Instance.GuiLogMessage("No/not all missing certificates were installed successful.", NotificationLevel.Error);
     442                        P2PManager.GuiLogMessage("No/not all missing certificates were installed successful.", NotificationLevel.Error);
    443443                    }
    444444                }
    445445                catch (Exception ex)
    446446                {
    447                     P2PManager.Instance.GuiLogMessage("Error occured while installing certificates. Exception: " + ex.ToString(), NotificationLevel.Error);
     447                    P2PManager.GuiLogMessage("Error occured while installing certificates. Exception: " + ex.ToString(), NotificationLevel.Error);
    448448                }
    449449            }
  • trunk/CrypP2P/Internal/P2PBase.cs

    r1604 r1616  
    11/*
    2    Copyright 2010 Paul Lelgemann, University of Duisburg-Essen
     2   Copyright 2010 Paul Lelgemann and Christian Arnold,
     3                  University of Duisburg-Essen
    34
    45   Licensed under the Apache License, Version 2.0 (the "License");
     
    4748    public class P2PBase
    4849    {
    49         private readonly P2PManager _p2PManager;
    50 
    5150        #region Variables
    5251
    53         private readonly object _connectLock = new object();
    5452        private readonly AutoResetEvent _systemJoined;
    5553        private readonly AutoResetEvent _systemLeft;
     
    6361        ///   True if system was successfully joined, false if system is COMPLETELY left
    6462        /// </summary>
    65         public bool Started { get; private set; }
     63        public bool IsConnected { get; private set; }
    6664
    6765        /// <summary>
    6866        ///   True if the underlying peer to peer system has been fully initialized
    6967        /// </summary>
    70         public bool Initialized { get; private set; }
     68        public bool IsInitialized { get; private set; }
    7169
    7270        #endregion
     
    8583        #endregion
    8684
    87         public P2PBase(P2PManager p2PManager)
    88         {
    89             Started = false;
    90             Initialized = false;
    91 
    92             _p2PManager = p2PManager;
     85        public P2PBase()
     86        {
     87            IsConnected = false;
     88            IsInitialized = false;
     89
    9390            _systemJoined = new AutoResetEvent(false);
    9491            _systemLeft = new AutoResetEvent(false);
     
    10299        public void Initialize()
    103100        {
    104             lock (_connectLock)
    105             {
    106                 Scheduler scheduler = new STAScheduler("pap");
    107 
    108                 switch (P2PSettings.Default.LinkManager)
    109                 {
    110                     case P2PLinkManagerType.Snal:
    111                         LogToMonitor("Init LinkMgr: Using NAT Traversal stuff");
    112 
    113                         // NAT-Traversal stuff needs a different Snal-Version
    114                         _linkmanager = new Snal(scheduler);
    115 
    116                         var settings = new PeersAtPlay.P2PLink.SnalNG.Settings();
    117                         settings.LoadDefaults();
    118                         settings.ConnectInternal = true;
    119                         settings.LocalReceivingPort = P2PSettings.Default.LocalReceivingPort;
    120                         settings.UseLocalAddressDetection = P2PSettings.Default.UseLocalAddressDetection;
    121                         settings.AutoReconnect = false;
    122                         settings.NoDelay = false;
    123                         settings.ReuseAddress = false;
    124                         settings.UseNetworkMonitorServer = true;
    125                         settings.CloseConnectionAfterPingTimeout = false;
     101            Scheduler scheduler = new STAScheduler("pap");
     102
     103            switch (P2PSettings.Default.LinkManager)
     104            {
     105                case P2PLinkManagerType.Snal:
     106                    LogToMonitor("Init LinkMgr: Using NAT Traversal stuff");
     107
     108                    // NAT-Traversal stuff needs a different Snal-Version
     109                    _linkmanager = new Snal(scheduler);
     110
     111                    var settings = new PeersAtPlay.P2PLink.SnalNG.Settings();
     112                    settings.LoadDefaults();
     113                    settings.ConnectInternal = true;
     114                    settings.LocalReceivingPort = P2PSettings.Default.LocalReceivingPort;
     115                    settings.UseLocalAddressDetection = P2PSettings.Default.UseLocalAddressDetection;
     116                    settings.AutoReconnect = false;
     117                    settings.NoDelay = false;
     118                    settings.ReuseAddress = false;
     119                    settings.UseNetworkMonitorServer = true;
     120                    settings.CloseConnectionAfterPingTimeout = false;
    126121                       
    127                         switch(P2PSettings.Default.TransportProtocol)
    128                         {
    129                             case P2PTransportProtocol.UDP:
    130                                 settings.TransportProtocol = TransportProtocol.UDP;
    131                                 break;
    132                             case P2PTransportProtocol.TCP_UDP:
    133                                 settings.TransportProtocol = TransportProtocol.TCP_UDP;
    134                                 break;
    135                             default:
    136                                 settings.TransportProtocol = TransportProtocol.TCP;
    137                                 break;
    138                         }
    139 
    140                         _linkmanager.Settings = settings;
    141                         _linkmanager.ApplicationType = ApplicationType.CrypTool;
    142 
    143                         break;
    144                     default:
    145                         throw (new NotImplementedException());
    146                 }
    147 
    148                 switch (P2PSettings.Default.Bootstrapper)
    149                 {
    150                     case P2PBootstrapperType.LocalMachineBootstrapper:
    151                         // LocalMachineBootstrapper = only local connection (runs only on one machine)
    152                         _bootstrapper = new LocalMachineBootstrapper();
    153                         break;
    154                     case P2PBootstrapperType.IrcBootstrapper:
    155                         // setup nat traversal stuff
    156                         LogToMonitor("Init Bootstrapper: Using NAT Traversal stuff");
    157                         PeersAtPlay.P2POverlay.Bootstrapper.IrcBootstrapper.Settings.DelaySymmetricResponse = true;
    158                         PeersAtPlay.P2POverlay.Bootstrapper.IrcBootstrapper.Settings.IncludeSymmetricInResponse = false;
    159                         PeersAtPlay.P2POverlay.Bootstrapper.IrcBootstrapper.Settings.SymmetricResponseDelay = 6000;
    160 
    161                         PeersAtPlay.P2POverlay.Bootstrapper.IrcBootstrapperV2.Settings.DelaySymmetricResponse = true;
    162                         PeersAtPlay.P2POverlay.Bootstrapper.IrcBootstrapperV2.Settings.IncludeSymmetricResponse = false;
    163 
    164                         _bootstrapper = new IrcBootstrapper(scheduler);
    165                         break;
    166                     default:
    167                         throw (new NotImplementedException());
    168                 }
    169 
    170                 switch (P2PSettings.Default.Overlay)
    171                 {
    172                     case P2POverlayType.FullMeshOverlay:
    173                         // changing overlay example: this.overlay = new ChordOverlay();
    174                         _overlay = new FullMeshOverlay(scheduler);
    175                         break;
    176                     default:
    177                         throw (new NotImplementedException());
    178                 }
    179 
    180                 switch (P2PSettings.Default.Dht)
    181                 {
    182                     case P2PDHTType.FullMeshDHT:
    183                         Dht = new FullMeshDHT(scheduler);
    184                         break;
    185                     default:
    186                         throw (new NotImplementedException());
    187                 }
    188 
    189                 _overlay.MessageReceived += OverlayMessageReceived;
    190                 Dht.SystemJoined += OnDhtSystemJoined;
    191                 Dht.SystemLeft += OnDhtSystemLeft;
    192 
    193                 VersionedDht = (IVersionedDHT) Dht;
    194 
    195                 _p2PManager.GuiLogMessage("Initializing DHT with world name " + P2PSettings.Default.WorldName,
    196                                                   NotificationLevel.Info);
    197                 Dht.Initialize(P2PSettings.Default.PeerName, string.Empty, P2PSettings.Default.WorldName, _overlay,
    198                                _bootstrapper,
    199                                _linkmanager, null);
    200 
    201                 Initialized = true;
    202             }
     122                    switch(P2PSettings.Default.TransportProtocol)
     123                    {
     124                        case P2PTransportProtocol.UDP:
     125                            settings.TransportProtocol = TransportProtocol.UDP;
     126                            break;
     127                        case P2PTransportProtocol.TCP_UDP:
     128                            settings.TransportProtocol = TransportProtocol.TCP_UDP;
     129                            break;
     130                        default:
     131                            settings.TransportProtocol = TransportProtocol.TCP;
     132                            break;
     133                    }
     134
     135                    _linkmanager.Settings = settings;
     136                    _linkmanager.ApplicationType = ApplicationType.CrypTool;
     137
     138                    break;
     139                default:
     140                    throw (new NotImplementedException());
     141            }
     142
     143            switch (P2PSettings.Default.Bootstrapper)
     144            {
     145                case P2PBootstrapperType.LocalMachineBootstrapper:
     146                    // LocalMachineBootstrapper = only local connection (runs only on one machine)
     147                    _bootstrapper = new LocalMachineBootstrapper();
     148                    break;
     149                case P2PBootstrapperType.IrcBootstrapper:
     150                    // setup nat traversal stuff
     151                    LogToMonitor("Init Bootstrapper: Using NAT Traversal stuff");
     152                    PeersAtPlay.P2POverlay.Bootstrapper.IrcBootstrapper.Settings.DelaySymmetricResponse = true;
     153                    PeersAtPlay.P2POverlay.Bootstrapper.IrcBootstrapper.Settings.IncludeSymmetricInResponse = false;
     154                    PeersAtPlay.P2POverlay.Bootstrapper.IrcBootstrapper.Settings.SymmetricResponseDelay = 6000;
     155
     156                    PeersAtPlay.P2POverlay.Bootstrapper.IrcBootstrapperV2.Settings.DelaySymmetricResponse = true;
     157                    PeersAtPlay.P2POverlay.Bootstrapper.IrcBootstrapperV2.Settings.IncludeSymmetricResponse = false;
     158
     159                    _bootstrapper = new IrcBootstrapper(scheduler);
     160                    break;
     161                default:
     162                    throw (new NotImplementedException());
     163            }
     164
     165            switch (P2PSettings.Default.Overlay)
     166            {
     167                case P2POverlayType.FullMeshOverlay:
     168                    // changing overlay example: this.overlay = new ChordOverlay();
     169                    _overlay = new FullMeshOverlay(scheduler);
     170                    break;
     171                default:
     172                    throw (new NotImplementedException());
     173            }
     174
     175            switch (P2PSettings.Default.Dht)
     176            {
     177                case P2PDHTType.FullMeshDHT:
     178                    Dht = new FullMeshDHT(scheduler);
     179                    break;
     180                default:
     181                    throw (new NotImplementedException());
     182            }
     183
     184            _overlay.MessageReceived += OverlayMessageReceived;
     185            Dht.SystemJoined += OnDhtSystemJoined;
     186            Dht.SystemLeft += OnDhtSystemLeft;
     187
     188            VersionedDht = (IVersionedDHT) Dht;
     189
     190            P2PManager.GuiLogMessage("Initializing DHT with world name " + P2PSettings.Default.WorldName,
     191                                                NotificationLevel.Info);
     192            Dht.Initialize(P2PSettings.Default.PeerName, string.Empty, P2PSettings.Default.WorldName, _overlay,
     193                            _bootstrapper,
     194                            _linkmanager, null);
     195
     196            IsInitialized = true;
    203197        }
    204198
     
    215209        public bool SynchStart()
    216210        {
    217             lock (_connectLock)
    218             {
    219                 if (!Initialized)
    220                 {
    221                     throw new InvalidOperationException("Peer-to-peer is not initialized.");
    222                 }
    223 
    224                 if (Started)
    225                 {
    226                     return true;
    227                 }
    228 
    229                 Dht.BeginStart(BeginStartEventHandler);
    230 
    231                 // Wait for event SystemJoined. When it's invoked, the peer completely joined the P2P system
    232                 _systemJoined.WaitOne();
    233                 _p2PManager.GuiLogMessage("System join process ended.", NotificationLevel.Debug);
    234 
     211            if (!IsInitialized)
     212            {
     213                throw new InvalidOperationException("Peer-to-peer is not initialized.");
     214            }
     215
     216            if (IsConnected)
     217            {
    235218                return true;
    236219            }
     220
     221            Dht.BeginStart(BeginStartEventHandler);
     222
     223            // Wait for event SystemJoined. When it's invoked, the peer completely joined the P2P system
     224            _systemJoined.WaitOne();
     225            P2PManager.GuiLogMessage("System join process ended.", NotificationLevel.Debug);
     226
     227            return true;
    237228        }
    238229
    239230        private void BeginStartEventHandler(DHTEventArgs eventArgs)
    240231        {
    241             _p2PManager.GuiLogMessage("Received DHTEventArgs: " + eventArgs + ", state: " + eventArgs.State, NotificationLevel.Debug);
     232            P2PManager.GuiLogMessage("Received DHTEventArgs: " + eventArgs + ", state: " + eventArgs.State, NotificationLevel.Debug);
    242233        }
    243234
     
    248239        public bool SynchStop()
    249240        {
    250             lock (_connectLock)
    251             {
    252                 if (Dht == null) return false;
    253 
    254                 Dht.BeginStop(null);
    255 
    256                 // wait till systemLeft Event is invoked
    257                 _systemLeft.WaitOne();
    258 
     241            if (Dht == null) return false;
     242
     243            Dht.BeginStop(null);
     244
     245            if (!IsConnected)
     246            {
    259247                return true;
    260248            }
     249
     250            // wait till systemLeft Event is invoked
     251            _systemLeft.WaitOne();
     252
     253            return true;
    261254        }
    262255
     
    334327
    335328            _systemJoined.Set();
    336             Started = true;
     329            IsConnected = true;
    337330        }
    338331
     
    342335                OnSystemLeft();
    343336
    344             Started = false;
    345             Initialized = false;
     337            IsConnected = false;
     338            IsInitialized = false;
    346339
    347340            // Allow new connection to start and check for waiting / blocked tasks
    348             _p2PManager.IsP2PConnecting = false;
     341            // TODO reset running ConnectionWorkers?
    349342            _systemLeft.Set();
    350343            _systemJoined.Set();
  • trunk/CrypP2P/P2PManager.cs

    r1611 r1616  
    1616
    1717using System;
    18 using System.IO;
     18using Cryptool.P2P.Helper;
    1919using Cryptool.P2P.Internal;
    20 using Cryptool.P2P.Worker;
    2120using Cryptool.PluginBase;
    2221using Cryptool.PluginBase.Miscellaneous;
    23 using Cryptool.Plugins.PeerToPeer.Internal;
    2422using PeersAtPlay.P2PStorage.DHT;
    2523using PeersAtPlay.Util.Threading;
     
    3533        private P2PManager()
    3634        {
    37             P2PBase = new P2PBase(this);
    38             ValidateSettings();
    39 
    40             // to forward event from overlay/dht MessageReceived-Event from P2PBase
    41             P2PBase.OnP2PMessageReceived += OnP2PMessageReceived;
     35            P2PBase = new P2PBase();
     36            ConnectionManager = new ConnectionManager(P2PBase);
     37
     38            SettingsHelper.ValidateSettings();
    4239        }
    4340
     
    4643        #region Variables
    4744
    48         public P2PBase P2PBase { get; private set; }
    49         public bool IsP2PConnecting { get; internal set; }
    50         public bool IsAutoconnectConsoleOptionSet { get; set; }
     45        public static ConnectionManager ConnectionManager { get; private set; }
     46        public static P2PBase P2PBase { get; private set; }
     47        public static bool IsAutoconnectConsoleOptionSet { get; set; }
    5148
    5249        #endregion
     
    5653        public static event GuiLogNotificationEventHandler OnGuiLogNotificationOccured;
    5754
    58         public delegate void P2PConnectionStateChangeEventHandler(object sender, bool newState);
    59         public static event P2PConnectionStateChangeEventHandler OnP2PConnectionStateChangeOccurred;
    60 
    61         public event P2PBase.P2PMessageReceived OnPeerMessageReceived;
    62 
    6355        #endregion Events
    6456
    65         internal void FireConnectionStatusChange()
    66         {
    67             if (OnP2PConnectionStateChangeOccurred != null)
    68             {
    69                 OnP2PConnectionStateChangeOccurred(this, IsP2PConnected());
    70             }
    71         }
    72 
    73         public bool IsP2PConnected()
    74         {
    75             return P2PBase.Started;
    76         }
    77 
    78         public string UserInfo()
    79         {
    80             if (!IsP2PConnected())
    81             {
    82                 return null;
    83             }
    84 
    85             string userName;
    86             var userInfo = P2PBase.GetPeerId(out userName);
    87             return userInfo + " (" + userName + ")";
    88         }
    89 
    90         public void HandleConnectOnStartup()
     57        #region CrypWin helper methods
     58
     59        public static void HandleConnectOnStartup()
    9160        {
    9261            var isAutoconnectConfiguredOrRequested = P2PSettings.Default.ConnectOnStartup || IsAutoconnectConsoleOptionSet;
    93             var isReadyToConnect = IsReadyToConnect();
     62            var isReadyToConnect = ConnectionManager.IsReadyToConnect();
    9463
    9564            if (isReadyToConnect && isAutoconnectConfiguredOrRequested)
    9665            {
    9766                GuiLogMessage("Connect on startup enabled. Establishing connection...", NotificationLevel.Info);
    98                 new ConnectionWorker(P2PBase).Start();
     67                ConnectionManager.Connect();
    9968            }
    10069        }
    10170
    102         private bool IsReadyToConnect()
    103         {
    104             if (String.IsNullOrEmpty(P2PSettings.Default.PeerName))
    105             {
    106                 GuiLogMessage("Peer-to-peer not fully configured: username missing.", NotificationLevel.Error);
    107                 return false;
    108             }
    109 
    110             if (String.IsNullOrEmpty(P2PSettings.Default.PeerName))
    111             {
    112                 GuiLogMessage("Peer-to-peer not fully configured: world name missing.", NotificationLevel.Error);
    113                 return false;
    114             }
    115 
    116             return true;
    117         }
    118 
    119         public PeerId GetPeerId(out string userName)
    120         {
    121             return P2PBase.GetPeerId(out userName);
    122         }
    123 
    124         // to forward event from overlay/dht MessageReceived-Event from P2PBase
    125         private void OnP2PMessageReceived(PeerId sourceAddr, byte[] data)
    126         {
    127             if (OnPeerMessageReceived != null)
    128                 OnPeerMessageReceived(sourceAddr, data);
    129         }
    130 
    131         private static void ValidateSettings()
    132         {
    133             if (String.IsNullOrEmpty(P2PSettings.Default.WorkspacePath))
    134             {
    135                 var tempForUser = Path.Combine(Path.GetTempPath(), "CrypTool2");
    136                 Directory.CreateDirectory(tempForUser);
    137                 P2PSettings.Default.WorkspacePath = tempForUser;
    138                 P2PSettings.Default.Save();
    139             }
    140         }
     71        public static void HandleDisconnectOnShutdown()
     72        {
     73            Disconnect();
     74        }
     75
     76        #endregion
    14177
    14278        #region Framework methods
    14379
    144         public void GuiLogMessage(string message, NotificationLevel logLevel)
     80        public static void GuiLogMessage(string message, NotificationLevel logLevel)
    14581        {
    14682            EventsHelper.GuiLogMessage(OnGuiLogNotificationOccured, null, new GuiLogEventArgs(message, null, logLevel));
     
    16298        public static bool Store(string key, byte[] data)
    16399        {
    164             if (!Instance.IsP2PConnected())
    165                 throw new NotConnectedException();
    166 
    167             return Instance.P2PBase.SynchStore(key, data);
     100            if (!IsConnected)
     101                throw new NotConnectedException();
     102
     103            return P2PBase.SynchStore(key, data);
    168104        }
    169105
     
    179115        public static bool Store(string key, string data)
    180116        {
    181             if (!Instance.IsP2PConnected())
     117            if (!IsConnected)
    182118                throw new NotConnectedException();
    183119           
    184             return Instance.P2PBase.SynchStore(key, data);
     120            return P2PBase.SynchStore(key, data);
    185121        }
    186122
     
    193129        public static byte[] Retrieve(string key)
    194130        {
    195             if (!Instance.IsP2PConnected())
     131            if (!IsConnected)
    196132                throw new NotConnectedException();
    197133           
    198             return Instance.P2PBase.SynchRetrieve(key);
     134            return P2PBase.SynchRetrieve(key);
    199135        }
    200136
     
    209145        public static bool Remove(string key)
    210146        {
    211             if (!Instance.IsP2PConnected())
    212                 throw new NotConnectedException();
    213 
    214             return Instance.P2PBase.SynchRemove(key);
     147            if (!IsConnected)
     148                throw new NotConnectedException();
     149
     150            return P2PBase.SynchRemove(key);
    215151        }
    216152
     
    232168        public static Guid Store(AsyncCallback<StoreResult> callback, string key, byte[] data, object asyncState)
    233169        {
    234             if (!Instance.IsP2PConnected())
    235                 throw new NotConnectedException();
    236 
    237             return Instance.P2PBase.VersionedDht.Store(callback, key, data, asyncState);
     170            if (!IsConnected)
     171                throw new NotConnectedException();
     172
     173            return P2PBase.VersionedDht.Store(callback, key, data, asyncState);
    238174        }
    239175
     
    248184        public static Guid Retrieve(AsyncCallback<RetrieveResult> callback, string key, object asyncState)
    249185        {
    250             if (!Instance.IsP2PConnected())
    251                 throw new NotConnectedException();
    252 
    253             return Instance.P2PBase.Dht.Retrieve(callback, key, asyncState);
     186            if (!IsConnected)
     187                throw new NotConnectedException();
     188
     189            return P2PBase.Dht.Retrieve(callback, key, asyncState);
    254190        }
    255191
     
    266202        public static Guid Remove(AsyncCallback<RemoveResult> callback, string key, object asyncState)
    267203        {
    268             if (!Instance.IsP2PConnected())
    269                 throw new NotConnectedException();
    270 
    271             return Instance.P2PBase.VersionedDht.Remove(callback, key, asyncState);
     204            if (!IsConnected)
     205                throw new NotConnectedException();
     206
     207            return P2PBase.VersionedDht.Remove(callback, key, asyncState);
    272208        }
    273209
    274210        #endregion DHT operations (non-blocking)
    275211
    276         public void HandleShutdown()
    277         {
    278             if (IsP2PConnected())
    279             {
    280                 new ConnectionWorker(P2PBase).Start();
    281             }
    282         }
     212        #region Connection methods
     213
     214        /// <summary>
     215        /// Connect to the peer-to-peer network.
     216        /// <see cref="ConnectionManager">OnP2PConnectionStateChangeOccurred will be fired when the connection state changes.</see>
     217        /// </summary>
     218        public static void Connect()
     219        {
     220            ConnectionManager.Connect();
     221        }
     222
     223        /// <summary>
     224        /// Disconnect from the peer-to-peer network.
     225        /// <see cref="ConnectionManager">OnP2PConnectionStateChangeOccurred will be fired when the connection state changes.</see>
     226        /// </summary>
     227        public static void Disconnect()
     228        {
     229            ConnectionManager.Disconnect();
     230        }
     231
     232        /// <summary>
     233        /// Boolean which indicates, if the peer-to-peer network is currently connected and not in a connect/disconnect attempt.
     234        /// </summary>
     235        public static bool IsConnected
     236        {
     237            get { return P2PBase.IsConnected && !IsConnecting; }
     238        }
     239
     240        /// <summary>
     241        /// Boolean which indicates, if the peer-to-peer network is currently in a connect/disconnect attempt.
     242        /// </summary>
     243        public static bool IsConnecting
     244        {
     245            get { return ConnectionManager.IsConnecting; }
     246        }
     247
     248        #endregion
    283249    }
    284 
    285    
    286250}
  • trunk/CrypP2P/Worker/ConnectionWorker.cs

    r1545 r1616  
    1515*/
    1616
     17using System;
    1718using System.ComponentModel;
    1819using Cryptool.P2P.Helper;
     
    2223namespace Cryptool.P2P.Worker
    2324{
    24     public class ConnectionWorker : WorkerBase
     25    internal class ConnectionWorker : WorkerBase
    2526    {
    2627        private readonly P2PBase _p2PBase;
     28        private readonly ConnectionManager _connectionManager;
    2729
    28         public ConnectionWorker(P2PBase p2PBase)
     30        public ConnectionWorker(P2PBase p2PBase, ConnectionManager connectionManager)
    2931        {
    3032            _p2PBase = p2PBase;
     33            _connectionManager = connectionManager;
    3134        }
    3235
    3336        protected override void WorkComplete(object sender, RunWorkerCompletedEventArgs e)
    3437        {
    35             P2PManager.Instance.GuiLogMessage(
    36                 P2PManager.Instance.IsP2PConnected()
     38            P2PManager.GuiLogMessage(
     39                _p2PBase.IsConnected
    3740                    ? "Connection to P2P network established."
    3841                    : "Connection to P2P network terminated.", NotificationLevel.Info);
    39             P2PManager.Instance.IsP2PConnecting = false;
    40             P2PManager.Instance.FireConnectionStatusChange();
     42            _connectionManager.IsConnecting = false;
     43            _connectionManager.FireConnectionStatusChange();
    4144        }
    4245
    4346        protected override void PerformWork(object sender, DoWorkEventArgs e)
    4447        {
    45             if (!_p2PBase.Started)
     48            if (!_p2PBase.IsConnected)
    4649            {
    47                 P2PManager.Instance.GuiLogMessage("Connecting to P2P network...", NotificationLevel.Info);
     50                P2PManager.GuiLogMessage("Connecting to P2P network...", NotificationLevel.Info);
    4851
    4952                // Validate certificats
    5053                if (!PAPCertificate.CheckAndInstallPAPCertificates())
    5154                {
    52                     P2PManager.Instance.GuiLogMessage("Certificates not validated, P2P might not be working!",
     55                    P2PManager.GuiLogMessage("Certificates not validated, P2P might not be working!",
    5356                                                      NotificationLevel.Error);
    5457                    return;
     
    6063            else
    6164            {
    62                 P2PManager.Instance.GuiLogMessage("Disconnecting from P2P network...", NotificationLevel.Info);
     65                P2PManager.GuiLogMessage("Disconnecting from P2P network...", NotificationLevel.Info);
    6366                _p2PBase.SynchStop();
    6467            }
     
    6770        protected override void PrePerformWork()
    6871        {
    69             P2PManager.Instance.IsP2PConnecting = true;
    7072        }
    7173    }
  • trunk/CrypPlugins/P2PEditor/Distributed/JobListManager.cs

    r1602 r1616  
    2222            _p2PEditor.GuiLogMessage("Fetching DHT job list...", NotificationLevel.Debug);
    2323
    24             if (!P2PManager.Instance.IsP2PConnected())
     24            if (!P2PManager.IsConnected)
    2525            {
    2626                _p2PEditor.GuiLogMessage("P2P not connected, cannot fetch job list.", NotificationLevel.Error);
     
    4848            _p2PEditor.GuiLogMessage("Distributing new job...", NotificationLevel.Debug);
    4949
    50             if (!P2PManager.Instance.IsP2PConnected())
     50            if (!P2PManager.IsConnected)
    5151            {
    5252                _p2PEditor.GuiLogMessage("P2P not connected, cannot distribute job.", NotificationLevel.Error);
     
    7777            _p2PEditor.GuiLogMessage("Deleting job...", NotificationLevel.Debug);
    7878
    79             if (!P2PManager.Instance.IsP2PConnected())
     79            if (!P2PManager.IsConnected)
    8080            {
    8181                _p2PEditor.GuiLogMessage("P2P not connected, cannot distribute job.", NotificationLevel.Error);
  • trunk/CrypPlugins/P2PEditor/GUI/Controls/JobDisplay.xaml.cs

    r1579 r1616  
    2727        {
    2828            InitializeComponent();
    29             UpdateRefreshTimerSettings(P2PManager.Instance.IsP2PConnected());
     29            UpdateRefreshTimerSettings(P2PManager.IsConnected);
    3030
    31             P2PManager.OnP2PConnectionStateChangeOccurred += P2PManager_OnP2PConnectionStateChangeOccurred;
     31            P2PManager.ConnectionManager.OnP2PConnectionStateChangeOccurred += P2PManager_OnP2PConnectionStateChangeOccurred;
    3232        }
    3333
     
    7373        private void RefreshButton_Click(object sender, RoutedEventArgs e)
    7474        {
    75             var updateListWorker = new BackgroundWorker();
    76             updateListWorker.DoWork += UpdateJobListInWorker;
    77             updateListWorker.RunWorkerAsync();
    78         }
    79 
    80         void UpdateJobListInWorker(object sender, DoWorkEventArgs e)
    81         {
    82             Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(UpdateJobList));
     75            UpdateJobList();
    8376        }
    8477
    8578        public void UpdateJobList()
    8679        {
    87             Jobs = JobListManager.JobList();
     80            if (!P2PManager.IsConnected)
     81            {
     82                return;
     83            }
     84
     85            P2PEditor.GuiLogMessage("Requesting new job list...", NotificationLevel.Debug);
     86            var updateWorker = new JobListUpdateWorker(JobListManager);
     87            updateWorker.RunWorkerCompleted += HandleRefreshedJobList;
     88            updateWorker.RunWorkerAsync();
     89        }
     90
     91        void HandleRefreshedJobList(object sender, RunWorkerCompletedEventArgs e)
     92        {
     93            var updateWorker = sender as JobListUpdateWorker;
     94            if (updateWorker == null)
     95            {
     96                return;
     97            }
     98
     99            P2PEditor.GuiLogMessage("Received new job list...", NotificationLevel.Debug);
     100            Jobs = updateWorker.RefreshedJobList;
    88101            Jobs.Reverse();
    89102        }
  • trunk/CrypPlugins/P2PEditor/GUI/P2PEditorPresentation.xaml.cs

    r1579 r1616  
    4949            P2PEditorPresentation = this;
    5050
    51             P2PManager.OnP2PConnectionStateChangeOccurred += HandleChangedPeerToPeerConnectionState;
     51            P2PManager.ConnectionManager.OnP2PConnectionStateChangeOccurred += HandleChangedPeerToPeerConnectionState;
    5252
    5353            InitializeComponent();
     
    7474
    7575
    76         internal void ConnectionWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
     76        internal void ConnectionWorkerCompleted(object sender, bool newState)
    7777        {
    78             Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(UpdateDisplay));
     78            UpdateDisplay();
    7979        }
    8080
     
    8787        private void UpdateConnectionState()
    8888        {
    89             IsP2PConnected = P2PManager.Instance.IsP2PConnected();
     89            IsP2PConnected = P2PManager.IsConnected;
    9090        }
    9191
  • trunk/CrypPlugins/P2PEditor/P2PEditor.csproj

    r1582 r1616  
    9393      <DesignTime>True</DesignTime>
    9494    </Compile>
     95    <Compile Include="Worker\JobListUpdateWorker.cs">
     96      <SubType>Component</SubType>
     97    </Compile>
    9598    <Compile Include="Worker\JobDeletionWorker.cs">
    9699      <SubType>Component</SubType>
  • trunk/CrypPlugins/P2PEditor/P2PEditorSettings.cs

    r1611 r1616  
    9999        public void ButtonStart()
    100100        {
    101             if (!P2PManager.Instance.IsP2PConnected() && !P2PManager.Instance.IsP2PConnecting)
    102             {
    103                 RunConnectionWorker();
     101            if (!P2PManager.IsConnected)
     102            {
     103                P2PManager.ConnectionManager.OnP2PConnectionStateChangeOccurred += ((P2PEditorPresentation)_p2PEditor.Presentation).ConnectionWorkerCompleted;
     104                P2PManager.Connect();
    104105                OnPropertyChanged("ButtonStart");
    105106                _p2PEditor.GuiLogMessage(Resources.Attributes.start_launched, NotificationLevel.Info);
     
    113114        public void ButtonStop()
    114115        {
    115             if (P2PManager.Instance.IsP2PConnected() && !P2PManager.Instance.IsP2PConnecting)
    116             {
    117                 RunConnectionWorker();
     116            if (P2PManager.IsConnected)
     117            {
     118                P2PManager.ConnectionManager.OnP2PConnectionStateChangeOccurred += ((P2PEditorPresentation)_p2PEditor.Presentation).ConnectionWorkerCompleted;
     119                P2PManager.Disconnect();
    118120                OnPropertyChanged("ButtonStop");
    119121                _p2PEditor.GuiLogMessage(Resources.Attributes.stop_launched, NotificationLevel.Info);
     
    296298            P2PSettings.Default.Save();
    297299        }
    298 
    299         private void RunConnectionWorker()
    300         {
    301             var connectionWorker = new ConnectionWorker(P2PManager.Instance.P2PBase);
    302             connectionWorker.BackgroundWorker.RunWorkerCompleted += ((P2PEditorPresentation)_p2PEditor.Presentation).ConnectionWorkerCompleted;
    303             connectionWorker.Start();
    304         }
    305300    }
    306301}
  • trunk/CrypPlugins/PeerToPeerBaseProxy/P2PPeer.cs

    r1611 r1616  
    8282        public bool PeerStarted()
    8383        {
    84             return P2PManager.Instance.IsP2PConnected() && !P2PManager.Instance.IsP2PConnecting;
     84            return P2PManager.IsConnected && !P2PManager.IsConnecting;
    8585        }
    8686
     
    8888        {
    8989            _settings.PeerStatusChanged(P2PPeerSettings.PeerStatus.Connecting);
    90             P2PManager.Instance.P2PBase.OnP2PMessageReceived += P2PBaseOnP2PMessageReceived;
    91 
    92             if (P2PManager.Instance.IsP2PConnected())
     90            P2PManager.P2PBase.OnP2PMessageReceived += P2PBaseOnP2PMessageReceived;
     91
     92            if (P2PManager.IsConnected)
    9393            {
    9494                GuiLogMessage("P2P connected.", NotificationLevel.Info);
    9595                _settings.PeerStatusChanged(P2PPeerSettings.PeerStatus.Online);
    9696            }
    97             else if (!P2PManager.Instance.IsP2PConnected() && P2PManager.Instance.IsP2PConnecting)
     97            else if (!P2PManager.IsConnected && P2PManager.IsConnecting)
    9898            {
    9999                HandleAlreadyConnecting();
     
    117117        private void HandleAlreadyConnecting()
    118118        {
    119             P2PManager.OnP2PConnectionStateChangeOccurred += HandleConnectionStateChange;
     119            P2PManager.ConnectionManager.OnP2PConnectionStateChangeOccurred += HandleConnectionStateChange;
    120120            _connectResetEvent = new AutoResetEvent(false);
    121121            _connectResetEvent.WaitOne();
    122122
    123             if (P2PManager.Instance.IsP2PConnected())
     123            if (P2PManager.IsConnected)
    124124            {
    125125                GuiLogMessage("P2P connected.", NotificationLevel.Info);
     
    137137        private void HandleAutoconnect()
    138138        {
    139             P2PManager.OnP2PConnectionStateChangeOccurred += HandleConnectionStateChange;
     139            P2PManager.ConnectionManager.OnP2PConnectionStateChangeOccurred += HandleConnectionStateChange;
    140140            _connectResetEvent = new AutoResetEvent(false);
    141141
    142             new ConnectionWorker(P2PManager.Instance.P2PBase).Start();
     142            P2PManager.Connect();
    143143
    144144            _connectResetEvent.WaitOne();
    145145
    146             if (P2PManager.Instance.IsP2PConnected())
     146            if (P2PManager.IsConnected)
    147147            {
    148148                GuiLogMessage("P2P network was connected due to plugin setting.",
     
    166166        public void StopPeer()
    167167        {
    168             P2PManager.Instance.P2PBase.OnP2PMessageReceived -= P2PBaseOnP2PMessageReceived;
     168            P2PManager.P2PBase.OnP2PMessageReceived -= P2PBaseOnP2PMessageReceived;
    169169            GuiLogMessage("Removed event registration, but peer cannot be stopped, it is running in CrypTool!", NotificationLevel.Info);
    170170        }
     
    271271            _systemJoined = new AutoResetEvent(false);
    272272
    273             P2PManager.Instance.P2PBase.OnSystemJoined += P2PBaseOnSystemJoined;
    274             P2PManager.Instance.OnPeerMessageReceived += P2PPeerOnPeerMessageReceived;
     273            P2PManager.P2PBase.OnSystemJoined += P2PBaseOnSystemJoined;
     274            P2PManager.P2PBase.OnP2PMessageReceived += P2PPeerOnPeerMessageReceived;
    275275            OnStatusChanged += P2PPeerMaster_OnStatusChanged;
    276276        }
     
    333333        public bool DHTstore(string sKey, byte[] byteValue)
    334334        {
    335             return P2PManager.Instance.IsP2PConnected() && P2PManager.Store(sKey, byteValue);
     335            return P2PManager.IsConnected && P2PManager.Store(sKey, byteValue);
    336336        }
    337337
    338338        public bool DHTstore(string sKey, string sValue)
    339339        {
    340             return P2PManager.Instance.IsP2PConnected() && P2PManager.Store(sKey, sValue);
     340            return P2PManager.IsConnected && P2PManager.Store(sKey, sValue);
    341341        }
    342342
    343343        public byte[] DHTload(string sKey)
    344344        {
    345             return P2PManager.Instance.IsP2PConnected() ? P2PManager.Retrieve(sKey) : null;
     345            return P2PManager.IsConnected ? P2PManager.Retrieve(sKey) : null;
    346346        }
    347347
    348348        public bool DHTremove(string sKey)
    349349        {
    350             return P2PManager.Instance.IsP2PConnected() && P2PManager.Remove(sKey);
     350            return P2PManager.IsConnected && P2PManager.Remove(sKey);
    351351        }
    352352
     
    362362                if (_peerId == null)
    363363                {
    364                     _peerId = P2PManager.Instance.P2PBase.GetPeerId(out _sPeerName);
     364                    _peerId = P2PManager.P2PBase.GetPeerId(out _sPeerName);
    365365                }
    366366                sPeerName = _sPeerName;
     
    374374        public PeerId GetPeerID(byte[] byteId)
    375375        {
    376             return P2PManager.Instance.P2PBase.GetPeerId(byteId);
     376            return P2PManager.P2PBase.GetPeerId(byteId);
    377377        }
    378378
     
    480480        private static bool SystemJoinedCompletely()
    481481        {
    482             return P2PManager.Instance.IsP2PConnected() && !P2PManager.Instance.IsP2PConnecting;
     482            return P2PManager.IsConnected && !P2PManager.IsConnecting;
    483483        }
    484484
     
    486486        {
    487487            if (SystemJoinedCompletely())
    488                 P2PManager.Instance.P2PBase.SendToPeer(data, destinationAddress.ToByteArray());
     488                P2PManager.P2PBase.SendToPeer(data, destinationAddress.ToByteArray());
    489489        }
    490490
  • trunk/CrypPlugins/QuadraticSieve/QuadraticSieve.cs

    r1614 r1616  
    156156            {
    157157                usePeer2Peer = settings.UsePeer2Peer;
    158                 if (usePeer2Peer && !P2PManager.Instance.IsP2PConnected())
     158                if (usePeer2Peer && !P2PManager.IsConnected)
    159159                {
    160160                    GuiLogMessage("No connection to Peer2Peer network. Sieving locally now!", NotificationLevel.Warning);
Note: See TracChangeset for help on using the changeset viewer.