private void Replicate()
 {
     lock (_lock)
     {
         try
         {
             if (ConnectToHQ())
             {
                 SendPackageToHQ();
                 GetPackageFormHQ();
             }
         }
         catch (Exception ex)
         {
             _log.Error(ex);
         }
         finally
         {
             if (_client != null)
             {
                 _client.Close();
                 _client = null;
             }
         }
     }
 }
        private bool ConnectToHQ()
        {

            if (_client == null)
            {
                _client = new NetworkClient(_config.ServerAddress, _config.ServerReplicationPort);
            }
            // authenticate and get branch config
            ReplicationPacket p = createpacket();
            p.command = "getbranchconfig";

            ReturnPacket ret = (ReturnPacket)_client.Send(p);
            if (ret.OK)
            {
                ClientWhatWhenConfig c = (ClientWhatWhenConfig)ret.Data;

                _clientConfig.what = c.what;

                _clientConfig.isConfigured = true;

                if (_clientConfig.whencron != c.whencron)
                {
                    _cron.Stop();
                    _clientConfig.whencron = c.whencron;
                    _cron = new CronDaemon();
                    _cron.AddJob(_clientConfig.whencron, Replicate);
                }

                SaveConfig();
            }
            return ret.OK;
        }