예제 #1
0
        public void Execute_ReturnsVersionString()
        {
            var command = new VersionCommand();
            var result = command.Execute(new VersionArgs());

            StringAssert.Contains("grep", result);
        }
예제 #2
0
        public void Execute_ReturnsVersionString()
        {
            var command = new VersionCommand();
            var result  = command.Execute(new VersionArgs());

            StringAssert.Contains("grep", result);
        }
예제 #3
0
        static void Main(string[] args)
        {
            if (args.Length == 0)
            {
                PrintUsageHeader();
                PrintUsage();
                Environment.Exit(-1);
            }

            ICommand command = null;

            switch (args[0])
            {
            case StartElectronCommand.COMMAND_NAME:
                command = new StartElectronCommand(args.Skip(1).ToArray());
                break;

            case BuildCommand.COMMAND_NAME:
                command = new BuildCommand(args.Skip(1).ToArray());
                break;

            case InitCommand.COMMAND_NAME:
                command = new InitCommand(args.Skip(1).ToArray());
                break;

            case VersionCommand.COMMAND_NAME:
                command = new VersionCommand(args.Skip(1).ToArray());
                break;

            case "--help":
            case "--h":
            case "help":
                PrintUsageHeader();

                if (args.Length > 1)
                {
                    PrintUsage(args[1]);
                }
                else
                {
                    PrintUsage();
                }
                break;

            default:
                Console.Error.WriteLine($"Unknown command {args[0]}");
                PrintUsage();
                Environment.Exit(-1);
                break;
            }

            if (command != null)
            {
                var success = command.ExecuteAsync().Result;
                if (!success)
                {
                    Environment.Exit(-1);
                }
            }
        }
예제 #4
0
        public void RefreshActiveSerialNexstarDevices()
        {
            _logger.LogInformation("Clearing old devices.");
            ActiveNexStarDevicePortNames.Clear();

            _logger.LogInformation("Starting probe for NexStar devices.");

            string[] portNames = SerialPort.GetPortNames();
            foreach (string portName in portNames)
            {
                SerialPortController testController        = new SerialPortController(portName);
                VersionCommand       versionCommandCommand = new VersionCommand();
                try
                {
                    testController.RunCommand(versionCommandCommand);

                    if (versionCommandCommand.RawResultBytes != null)
                    {
                        ActiveNexStarDevicePortNames.Add(portName);
                        _logger.LogInformation($"NexStar device found on port '{portName}'.");
                    }
                }
                catch (TimeoutException)
                {
                    _logger.LogInformation($"Probe timeout for port '{portName}'.");
                    //ignore timeouts here, we are expecting some devices to not respond.
                }
                finally
                {
                    testController.CloseSerialConnection();
                }
            }

            _logger.LogInformation($"Probe finished found {ActiveNexStarDevicePortNames.Count} devices.");
        }
예제 #5
0
        public void Run()
        {
            while (true)
            {
                string   input = Console.ReadLine();
                ICommand Command;
                switch (input.ToUpper())
                {
                case "CLEAR":
                    Command = new ClearCommand();
                    Command.Execute();
                    break;

                case "VERSION":
                    Command = new VersionCommand();
                    Command.Execute();
                    break;

                default:
                    Command = new NullCommand();
                    Command.Execute();
                    break;
                }
            }
        }
예제 #6
0
        public static string Parse(List <string> args)
        {
            try
            {
                string result;

                var command = args.First();

                if (command == Statics.Commands.Help)
                {
                    var helpCommand  = new HelpCommand();
                    var numberOfArgs = helpCommand.GetNumberOfArgs();
                    if (numberOfArgs == args.Count - 1)
                    {
                        result = helpCommand.Execute(new List <string>());
                    }
                    else
                    {
                        throw new Exception("Command not recognized. Please use 'WixXmlGenerator -help' to see command the usages.");
                    }
                }
                else if (command == Statics.Commands.Version)
                {
                    var versionCommand = new VersionCommand();
                    var numberOfArgs   = versionCommand.GetNumberOfArgs();
                    if (numberOfArgs == args.Count - 1)
                    {
                        result = versionCommand.Execute(new List <string>());
                    }
                    else
                    {
                        throw new Exception("Command not recognized. Please use 'WixXmlGenerator -help' to see command the usages.");
                    }
                }
                else if (command == Statics.Commands.Generate)
                {
                    var generateCommand = new GenerateCommand();
                    var numberOfArgs    = generateCommand.GetNumberOfArgs();
                    if (numberOfArgs == args.Count - 1)
                    {
                        result = generateCommand.Execute(args);
                    }
                    else
                    {
                        throw new Exception("Command not recognized. Please use 'WixXmlGenerator -help' to see command the usages.");
                    }
                }
                else
                {
                    throw new Exception("Command not recognized. Please use 'WixXmlGenerator -help' to see command the usages.");
                }

                return(result);
            }
            catch (Exception e)
            {
                throw e;
            }
        }
예제 #7
0
 public void Setup()
 {
     _mockLog            = new MockLog1();
     _mockMigrationDir   = new Mock <IMigrationDirectory>();
     _versionCommand     = new VersionCommand(_mockMigrationDir.Object);
     _versionCommand.Log = _mockLog;
     CreateDatabase();
 }
예제 #8
0
        public void VersionIsSet()
        {
            var version = VersionCommand.GetVersion();

            Assert.False(string.IsNullOrEmpty(version));
            Assert.NotEqual("1.0.0", version);
            Assert.NotEqual("0.0.0", version);
        }
예제 #9
0
 private void OnCasparCgConnectionStatusChanged(object sender, ConnectionEventArgs e)
 {
     RaisePropertyChanged(nameof(IsConnected));
     ConnectCommand?.RaiseCanExecuteChanged();
     DisconnectCommand?.RaiseCanExecuteChanged();
     PlayCommand?.RaiseCanExecuteChanged();
     VersionCommand?.RaiseCanExecuteChanged();
 }
예제 #10
0
        public void ProcessRawResponseAsync_Invalid_Raw_Data_Should_Throw_exception(string rawData)
        {
            VersionCommand versionCommand = new VersionCommand();

            byte[] rawBytes = rawData == null ? null : Encoding.UTF8.GetBytes(rawData);

            Assert.Throws <ClamAvException>(() => versionCommand.ProcessRawResponse(rawBytes));
        }
예제 #11
0
        public void Cannot_pass_arguments_to_version()
        {
            var stream = new MemoryStream();
            var cmd    = new VersionCommand();

            cmd.SetContext(stream);
            cmd.Init("a");
            Assert.AreEqual("CLIENT_ERROR Version accepts no paramters\r\n", ReadAll(stream));
        }
예제 #12
0
        public void Calling_init_with_no_params_succeed()
        {
            var stream = new MemoryStream();
            var cmd    = new VersionCommand();

            cmd.SetContext(stream);

            Assert.IsTrue(cmd.Init());
        }
예제 #13
0
        public void SetUp()
        {
            originalOutput = Console.Out;
            output         = new StringWriter();
            Console.SetOut(output);

            commandOutputProvider = new CommandOutputProvider("Octo", "1.0.0", logger);
            versionCommand        = new VersionCommand(commandOutputProvider);
            logger = new LoggerConfiguration().WriteTo.TextWriter(output).CreateLogger();
        }
예제 #14
0
        private void CreateVersionCommand(string arguments)
        {
            if (!string.IsNullOrEmpty(arguments))
            {
                CreateInvalidCommand();
                return;
            }

            _command   = new VersionCommand();
            this.State = ParserState.ReadyToDispatch;
        }
예제 #15
0
        public static byte[] BuildVersionResponse(VersionCommand command)
        {
            byte[] value = null;

            if (command.OperationResult.ReturnResult == Result.SUCCESS)
            {
                string version = command.OperationResult.Value as string;
                value = MemcachedEncoding.BinaryConverter.GetBytes(version);
            }
            return(BuildResposne(command.Opcode, BinaryResponseStatus.no_error, command.Opaque, 0, null, value, null));
        }
예제 #16
0
        public void Will_return_assembly_version_as_memcached_version()
        {
            var stream = new MemoryStream();
            var cmd    = new VersionCommand();

            cmd.SetContext(stream);

            cmd.Execute();
            Assert.AreEqual("VERSION " + typeof(VersionCommand).Assembly.GetName().Version
                            + "\r\n", ReadAll(stream));
        }
        public async Task ShouldStartWithProperArguments()
        {
            var starterMock = new Mock <IProcessStarter>();

            starterMock.Setup(starter => starter.Start("--version", It.IsAny <TimeSpan>()))
            .Returns(Task.FromResult(0));
            var command = new VersionCommand(starterMock.Object);
            await command.Execute();

            starterMock.Verify(starter => starter.Start("--version", It.IsAny <TimeSpan>()), Times.Once());
        }
        public async Task ShouldStartWithProperTimeout()
        {
            var starterMock = new Mock <IProcessStarter>();

            starterMock.Setup(starter => starter.Start(It.IsAny <string>(), TimeSpan.FromHours(1)))
            .Returns(Task.FromResult(0));
            var command = new VersionCommand(starterMock.Object, string.Empty);
            await command.Execute(TimeSpan.FromHours(1));

            starterMock.Verify(starter => starter.Start(It.IsAny <string>(), TimeSpan.FromHours(1)), Times.Once());
        }
예제 #19
0
        public void Version_Execute_ReturnString()
        {
            var command = new VersionCommand(_console, LoggerMock.GetLogger <VersionCommand>().Object, _versionService.Object);

            var resultMessage = command.Execute();

            Assert.Contains("API Version: 1.0", resultMessage);
            Assert.Contains("CLI Version:", resultMessage);
            Assert.Contains("- Engine01: 1.0", resultMessage);
            Assert.Contains("- AspNetMvc: 1.0", resultMessage);
        }
        public void ShouldExecuteDockerComposeWithNoArgumentsWithoutExceptions()
        {
            var starterMock = new Mock <IProcessStarter>();

            starterMock.Setup(starter => starter.Start(It.IsAny <string>(), It.IsAny <TimeSpan>()))
            .Returns(Task.FromResult(0));
            var         command = new VersionCommand(starterMock.Object, string.Empty);
            Func <Task> execute = async() => await command.Execute();

            execute.Should().NotThrow(
                "При условии установленного Docker Compose получение его версии всегда допустим.");
        }
예제 #21
0
        public void Execute_WhenCalled_ReturnsViewWithVersionAsModel()
        {
            var command     = new VersionCommand();
            var versionArgs = new VersionArgs {
                Version = true
            };

            var result = (CommandResult)command.Execute(versionArgs);
            var model  = (VersionViewModel)result.Model;

            result.ViewName.ShouldEqual("Version");
            model.Version.ShouldEqual("2.4.2");
        }
예제 #22
0
        public void ProcessRawResponseAsync_Valid_Raw_Data_Should_Return_PONG()
        {
            VersionCommand versionCommand = new VersionCommand();

            const string expectedProgramVersion = "ClamAv 1.17.219";
            string       expectedVirusDbVersion = (DateTime.Now.Ticks % 11177).ToString();

            byte[] rawBytes = Encoding.UTF8.GetBytes($"{expectedProgramVersion}/{expectedVirusDbVersion}/{DateTime.Now}");

            VersionResult actual = versionCommand.ProcessRawResponse(rawBytes);

            actual.ProgramVersion.Should().Be(expectedProgramVersion);
            actual.VirusDbVersion.Should().Be(expectedVirusDbVersion);
        }
        public override async void OnRun()
        {
            try
            {
                var releases = await Program.Instance.ghClient.Repository.Release.GetAll(Program.config.GitHubUpdateUsername, Program.config.GitHubUpdateRepository);

                var latest = VersionCommand.GetLatestVersion(releases);
                if (!Program.VERSION.Equals(latest))
                {
                    UpdateCommand.Update();
                }
            }
            catch { } // quietly fail
        }
예제 #24
0
        public async Task WriteCommandAsync_Should_Write_CommandName()
        {
            VersionCommand versionCommand = new VersionCommand();

            await using MemoryStream memoryStream = new MemoryStream();

            await versionCommand.WriteCommandAsync(memoryStream).ConfigureAwait(false);

            byte[] commandData = memoryStream.ToArray();

            string actual = Encoding.UTF8.GetString(commandData);

            actual.Should()
            .Be($"{Consts.COMMAND_PREFIX_CHARACTER}{versionCommand.Name}{(char)Consts.TERMINATION_BYTE}");
        }
        public void ShouldCopyStandardOutputAndStandardErrorFromProcessStarterOnSuccessfulExecution()
        {
            var starterMock = new Mock <IProcessStarter>();

            starterMock.Setup(starter => starter.Start(It.IsAny <string>(), It.IsAny <TimeSpan>()))
            .Returns(Task.FromResult(0));
            starterMock.Setup(starter => starter.StandardOutput).Returns(() => new StringBuilder("stdout"));
            starterMock.Setup(starter => starter.StandardError).Returns(() => new StringBuilder("stderr"));
            var         command = new VersionCommand(starterMock.Object, string.Empty);
            Func <Task> execute = async() => await command.Execute();

            execute.Should().NotThrow();
            command.StandardOutput.ToString().Should().Be("stdout");
            command.StandardError.ToString().Should().Be("stderr");
        }
예제 #26
0
        public ICommand Build(string command)
        {
            string[] commandSplit = command?.Split(' ');

            ICommand createdCommand;

            switch (commandSplit[0])
            {
            case "/help":
            case "/h":
                createdCommand = new HelpCommand();
                break;

            case "/version":
            case "/v":
                createdCommand = new VersionCommand();
                break;

            case "/clear":
                createdCommand = new ClearCommand();
                break;

            case "/quit":
            case "/q":
                createdCommand = new QuitCommand();
                break;

            case "/post":
            case "/p":
                createdCommand = new PostCommand(commandSplit);
                break;

            case "/retrieve":
            case "/r":
                createdCommand = new RetrieveCommand(commandSplit);
                break;

            case "/settings":
                createdCommand = new SettingsCommand(commandSplit);
                break;

            default:
                createdCommand = new DefaultCommand();
                break;
            }

            return(createdCommand);
        }
        public void ShouldThrowIfCommandExecutionExceededTimeout()
        {
            var starterMock = new Mock <IProcessStarter>();

            starterMock.Setup(starter => starter.Start(It.IsAny <string>(), It.IsAny <TimeSpan>()))
            .Throws <TimeoutException>();
            starterMock.Setup(starter => starter.StandardOutput).Returns(() => new StringBuilder());
            starterMock.Setup(starter => starter.StandardError).Returns(() => new StringBuilder());
            var         command = new VersionCommand(starterMock.Object, string.Empty);
            Func <Task> execute = async() => await command.Execute();

            execute.Should()
            .ThrowExactly <CommandExecutionException>()
            .WithMessage("*timeout*")
            .WithInnerExceptionExactly <TimeoutException>();
        }
예제 #28
0
        public ICommand Build(string command)
        {
            string[] commandSplit = command?.Split(' ');

            ICommand createdCommand;

            switch (commandSplit[0])
            {
            case "/help":
            case "/h":
                createdCommand = new HelpCommand();
                break;

            case "/version":
            case "/v":
                createdCommand = new VersionCommand();
                break;

            case "/clear":
            case "/c":
                createdCommand = new ClearCommand();
                break;

            case "/quit":
            case "/q":
                createdCommand = new QuitCommand();
                break;

            case "/list":
            case "/l":
                createdCommand = new ListCommand();
                break;

            case "/run":
            case "/r":
                createdCommand = new RunCommand(commandSplit);
                break;

            default:
                createdCommand = new DefaultCommand();
                break;
            }

            return(createdCommand);
        }
예제 #29
0
        public void VersionPacketTest()
        {
            var versionCommand = new VersionCommand();

            byte[] packetBytes = versionCommand.GetPacketBytes();

            Assert.Equal(0x00, packetBytes[0]);
            Assert.Equal(0x00, packetBytes[1]);
            Assert.Equal(0x00, packetBytes[2]);
            Assert.Equal(0x0b, packetBytes[3]);
            Assert.Equal(0x00, packetBytes[4]);
            Assert.Equal(0x00, packetBytes[5]);
            Assert.Equal(0x00, packetBytes[6]);
            Assert.Equal(0x01, packetBytes[7]);
            Assert.Equal(0x00, packetBytes[8]);
            Assert.Equal(0x01, packetBytes[9]);
            Assert.Equal(0x01, packetBytes[10]);
        }
        protected override void Initialize()
        {
            GlobalContext.Properties["package"] = this;
            CheckCommandLine();
            Logger.Initialise(IsCommandLine);
            SettingsCommand.Initialize(this);
            VersionCommand.Initialize(this);

            _buildVersionIncrementor = new BuildVersionIncrementor(this);
            _buildEvents             = DTE.Events.BuildEvents;
            _buildVersionIncrementor.InitializeIncrementors();

            _buildEvents.OnBuildBegin += _buildVersionIncrementor.OnBuildBegin;
            _buildEvents.OnBuildDone  += _buildVersionIncrementor.OnBuildDone;



            base.Initialize();
        }
예제 #31
0
        protected override async System.Threading.Tasks.Task InitializeAsync(CancellationToken cancellationToken, IProgress <ServiceProgressData> progress)
        {
            await base.InitializeAsync(cancellationToken, progress);

            await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken);

            GlobalContext.Properties["package"] = this;
            CheckCommandLine();
            Logger.Initialise(IsCommandLine);
            SettingsCommand.Initialize(this);
            VersionCommand.Initialize(this);

            _buildVersionIncrementor = new BuildVersionIncrementor(this);
            _buildEvents             = DTE.Events.BuildEvents;
            _buildVersionIncrementor.InitializeIncrementors();

#pragma warning disable VSTHRD101 // Avoid unsupported async delegates
            _buildEvents.OnBuildBegin += async(s, e) => await _buildVersionIncrementor.OnBuildBeginAsync(s, e);

            _buildEvents.OnBuildDone += async(s, e) => await _buildVersionIncrementor.OnBuildDoneAsync(s, e);

#pragma warning restore VSTHRD101 // Avoid unsupported async delegates
        }
예제 #32
0
파일: JDbg.cs 프로젝트: lsgxeva/MIEngine
        /// <summary>
        /// Get the version string of the VM
        /// </summary>
        /// <returns></returns>
        private async Task<VersionCommand.Reply> Version()
        {
            VersionCommand command = new VersionCommand();

            await _jdwp.SendCommandAsync(command);

            var reply = command.GetReply();
            return reply;
        }
예제 #33
0
        public async Task LoginAsync(UserStatus initialStatus = UserStatus.Online)
        {

            await @lock.WriterLockAsync();

            try
            {

                if (IsLoggedIn)
                    return;

                IConnection connection = null;
                ConnectionStream stream = null;
                CommandReader reader = null;
                CommandWriter writer = null;
                ResponseTracker responseTracker = null;
                IConnectableObservable<Command> commands = null;
                IDisposable commandsDisposable = null;

                int transferCount = 0;

                SocketEndPoint endPoint = SocketEndPoint.Parse("messenger.hotmail.com:1863");

                string authTicket = null;

                while (authTicket == null)
                {

                    connection = new SocketConnection();

                    await connection.ConnectAsync(endPoint);

                    stream = new ConnectionStream(connection);

                    writer = new CommandWriter(stream);
                    reader = new CommandReader(stream, new Dictionary<string, Type> {
                        { "VER", typeof(VersionCommand) },
                        { "CVR", typeof(ClientVersionCommand) },
                        { "USR", typeof(AuthenticateCommand) },
                        { "XFR", typeof(TransferCommand) },
                        { "SYN", typeof(SynchronizeCommand) },
                        { "SBS", typeof(SbsCommand) },
                        { "MSG", typeof(MessageCommand) },
                        { "LST", typeof(UserCommand) },
                        { "LSG", typeof(GroupCommand) },
                        { "BPR", typeof(UserPropertyCommand) },
                        { "BLP", typeof(PrivacySettingCommand) },
                        { "GTC", typeof(PrivacySettingCommand) },
                        { "CHG", typeof(ChangeStatusCommand) },
                        { "UBX", typeof(BroadcastCommand) },
                        { "PRP", typeof(LocalPropertyCommand) },
                        { "NLN", typeof(UserOnlineCommand) },
                        { "ILN", typeof(InitialUserOnlineCommand) },
                        { "FLN", typeof(UserOfflineCommand) },
                        { "UUX", typeof(SendBroadcastCommand) },
                        { "NOT", typeof(NotificationCommand) },
                        { "QNG", typeof(PingCommand) },
                        { "CHL", typeof(ChallengeCommand) },
                        { "ADC", typeof(AddContactCommand) },
                        { "REM", typeof(RemoveContactCommand) },
                        { "ADG", typeof(AddGroupCommand) },
                        { "RMG", typeof(RemoveGroupCommand) },
                        { "REG", typeof(RenameGroupCommand) },  
                        { "QRY", typeof(AcceptChallengeCommand) },  
                        { "RNG", typeof(RingCommand) },
                        { "SBP", typeof(ChangeUserPropertyCommand) },
                        { "IMS", typeof(EnableIMCommand) },
                    });
                    
                    commands = reader.GetReadObservable().Publish();
                    responseTracker = new ResponseTracker(writer, commands);

                    commandsDisposable = commands.Connect();

                    var versionCommand = new VersionCommand("MSNP12");
                    var versionResponse = await responseTracker.GetResponseAsync<VersionCommand>(versionCommand, defaultTimeout);

                    if (versionResponse.Versions.Length == 0)
                        throw new ProtocolNotAcceptedException();

                    var clientVersionCommand = new ClientVersionCommand
                    {
                        LocaleId = "0x0409",
                        OsType = "winnt",
                        OsVersion = "5.0",
                        Architecture = "1386",
                        LibraryName = "MSMSGS",
                        ClientVersion = "5.0.0482",
                        ClientName = "WindowsMessenger",
                        LoginName = credentials.LoginName,
                    };

                    await responseTracker.GetResponseAsync<ClientVersionCommand>(clientVersionCommand, defaultTimeout);

                    var userCommand = new AuthenticateCommand("TWN", "I", credentials.LoginName);
                    var userResponse = await responseTracker.GetResponseAsync(userCommand, new Type[] { typeof(AuthenticateCommand), typeof(TransferCommand) }, defaultTimeout);

                    if (userResponse is AuthenticateCommand)
                    {
                        authTicket = (userResponse as AuthenticateCommand).Argument;
                    }

                    else if (userResponse is TransferCommand)
                    {
                        
                        TransferCommand transferResponse = userResponse as TransferCommand;

                        if (transferCount > 3)
                            throw new InvalidOperationException("The maximum number of redirects has been reached.");

                        transferCount++;

                        endPoint = SocketEndPoint.Parse(transferResponse.Host);

                        commandsDisposable.Dispose();

                        reader.Close();
                        writer.Close();
                        connection.Dispose();

                    }

                }

                PassportAuthentication auth = new PassportAuthentication();

                string authToken = await auth.GetToken(credentials.LoginName, credentials.Password, authTicket);

                var authCommand = new AuthenticateCommand("TWN", "S", authToken);
                var authResponse = await responseTracker.GetResponseAsync<AuthenticateCommand>(authCommand, defaultTimeout);

                var synCommand = new SynchronizeCommand(syncTimeStamp1 ?? "0", syncTimeStamp2 ?? "0");
                var synResponse = await responseTracker.GetResponseAsync<SynchronizeCommand>(synCommand, defaultTimeout);

                IDisposable syncCommandsSubscription = null;
                List<Command> syncCommands = null;

                if (synResponse.TimeStamp1 != syncTimeStamp1 || synResponse.TimeStamp2 != syncTimeStamp2)
                {

                    syncCommands = new List<Command>();

                    Type[] syncTypes = new Type[] { 
                        typeof(MessageCommand), 
                        typeof(UserCommand), 
                        typeof(GroupCommand), 
                        typeof(LocalPropertyCommand), 
                        typeof(PrivacySettingCommand),
                    };

                    syncCommandsSubscription = commands
                        .Where(c => syncTypes.Contains(c.GetType()))
                        .Catch(Observable.Empty<Command>())
                        .Subscribe(c => syncCommands.Add(c));

                    //if we're expecting users/groups, wait for them before we proceed
                    if (synResponse.UserCount + synResponse.GroupCount > 0)
                    {

                        await commands
                            .Where(c => c is UserCommand || c is GroupCommand)
                            .Take(synResponse.UserCount + synResponse.GroupCount)
                            .Timeout(defaultTimeout);

                    }

                }

                UserCapabilities capabilities = 0;
                MSNObject displayPicture = MSNObject.Empty;

                if (LocalUser != null)
                {
                    capabilities = LocalUser.Capabilities;
                    displayPicture = LocalUser.DisplayPicture;
                }

                Command changeStatusCommand = new ChangeStatusCommand(User.StatusToString(UserStatus.Online), (uint)capabilities, displayPicture != MSNObject.Empty ? displayPicture.ToString() : "0");
                await responseTracker.GetResponseAsync(changeStatusCommand, defaultTimeout);

                if (syncCommandsSubscription != null)
                    syncCommandsSubscription.Dispose();

                this.writer = writer;
                this.reader = reader;
                this.stream = stream;
                this.connection = connection;
                this.responseTracker = responseTracker;
                this.commands = commands;
                this.commandsDisposable = commandsDisposable;

                if (LocalUser == null)
                {
                    LocalUser = new LocalUser(this, credentials.LoginName);
                    userCache.Add(credentials.LoginName, new WeakReference(LocalUser));
                }

                LocalUser.Status = initialStatus;

                SyncEvents syncEvents = null;

                if (syncCommands != null)
                {
                    syncTimeStamp1 = synResponse.TimeStamp1;
                    syncTimeStamp2 = synResponse.TimeStamp2;

                    syncEvents = ProcessSyncCommands(syncCommands);
                }

                var commandsSafe = commands
                    .Catch<Command, ConnectionErrorException>(tx => Observable.Empty<Command>());

                commandsSafe.OfType<MessageCommand>().Subscribe(cmd => HandleMessages(cmd, connection));
                commandsSafe.OfType<RingCommand>().Subscribe(cmd => HandleRings(cmd, connection));
                commandsSafe.OfType<BroadcastCommand>().Subscribe(cmd => HandleBroadcasts(cmd, connection));
                commandsSafe.OfType<NotificationCommand>().Subscribe(cmd => HandleNotifications(cmd, connection));
                commandsSafe.OfType<AddContactCommand>().Subscribe(cmd => HandleNewUsers(cmd, connection));
                commandsSafe.OfType<OutCommand>().Subscribe(cmd => HandleOut(cmd, connection));
                commandsSafe.OfType<ChallengeCommand>().Subscribe(cmd => HandleChallenges(cmd, connection));
                commandsSafe.OfType<UserOnlineCommand>().Subscribe(cmd => HandleOnlineUsers(cmd, connection));
                commandsSafe.OfType<InitialUserOnlineCommand>().Subscribe(cmd => HandleOnlineUsers(cmd, connection));
                commandsSafe.OfType<UserOfflineCommand>().Subscribe(cmd => HandleOfflineUsers(cmd, connection));

                connection.Error += connection_Error;

                IsLoggedIn = true;

                OnLoggedIn();

                OnUserStatusChanged(new UserStatusEventArgs(LocalUser, initialStatus, UserStatus.Offline, true));

                if (syncEvents != null)
                    RaiseSyncEvents(syncEvents);


            }
            finally
            {
                @lock.WriterRelease();
            }

        }
        public static Version GetVersion()
        {
            LazyInitialize();
            var command = new VersionCommand();
            NonPersistentClient.Execute(command);
            string firstLine = command.Result.Split(
                new[]
                {
                    '\n', '\r'
                }, StringSplitOptions.RemoveEmptyEntries).First();
            var re = new Regex(@"\(version\s+(?<version>[0-9.]+)(-rc)?(\+\d+-[a-f0-9]+)?\)", RegexOptions.IgnoreCase);
            Match ma = re.Match(firstLine);
            if (!ma.Success)
                throw new InvalidOperationException(
                    string.Format(CultureInfo.InvariantCulture, "Unable to locate Mercurial version number in '{0}'", firstLine));

            string versionString = ma.Groups["version"].Value;
            switch (versionString.Split('.').Length)
            {
                case 1:
                    return new Version(string.Format(CultureInfo.InvariantCulture, "{0}.0.0.0", versionString));

                case 2:
                    return new Version(string.Format(CultureInfo.InvariantCulture, "{0}.0.0", versionString));

                case 3:
                    return new Version(string.Format(CultureInfo.InvariantCulture, "{0}.0", versionString));

                case 4:
                    return new Version(versionString);

                default:
                    throw new InvalidOperationException(
                        string.Format(CultureInfo.InvariantCulture, "Incorrect version number length, too many or too few parts: {0}", versionString));
            }
        }