/// <summary>
        /// Executes a query and atomically applies a modifier operation to the first document returning the original document
        /// by default.
        /// </summary>
        /// <param name="document">The document.</param>
        /// <param name="spec"><see cref="Document"/> to find the document.</param>
        /// <param name="sort"><see cref="Document"/> containing the names of columns to sort on with the values being the
        /// <see cref="IndexOrder"/></param>
        /// <param name="fields">The fields.</param>
        /// <param name="remove">if set to <c>true</c> [remove].</param>
        /// <param name="returnNew">if set to <c>true</c> [return new].</param>
        /// <param name="upsert">if set to <c>true</c> [upsert].</param>
        /// <returns>A <see cref="Document"/></returns>
        public T FindAndModify(object document, object spec, object sort, object fields, bool remove, bool returnNew, bool upsert)
        {
            var command = new Document
            {
                { "findandmodify", Name },
                { "query", spec },
                { "update", EnsureUpdateDocument(document) },
                { "new", returnNew },
                { "remove", remove },
                { "upsert", upsert }
            };

            if (sort != null)
            {
                command.Add("sort", sort);
            }
            if (fields != null)
            {
                command.Add("fields", fields);
            }

            var response = _connection.SendCommand <FindAndModifyResult <T> >(_configuration.SerializationFactory,
                                                                              DatabaseName,
                                                                              typeof(T),
                                                                              command,
                                                                              false);

            return(response.Value);
        }
Example #2
0
        public void Connection_SendCommand_Test2()
        {
            using (var connection = new Connection(CreateClientFactory()))
            {
                Connect(connection);

                var  mre                = new ManualResetEvent(false);
                bool dataSentFired      = false;
                bool statusMessageFired = false;

                connection.DataSent += (sender, args) =>
                {
                    dataSentFired = true;
                    mre.Set();
                };
                connection.StatusMessage += (sender, args) => statusMessageFired = true;

                connection.SendCommand("command");
                mre.WaitOne();

                Assert.IsTrue(dataSentFired);
                Assert.IsTrue(statusMessageFired);
            }

            _tcpClient.VerifyAllExpectations();
            _stream.VerifyAllExpectations();
        }
Example #3
0
 public void Connection_SendCommand_Test1()
 {
     using (var connection = new Connection(CreateClientFactory()))
     {
         Assert.Throws <InvalidOperationException>(() => connection.SendCommand("command"));
     }
 }
Example #4
0
 void SendInit(int bus)
 {
     if (Connection.SrcpVersion >= ServerConnection.Version8)
     {
         Connection.SendCommand(string.Format("INIT {0} POWER", bus));
     }
 }
Example #5
0
        public void Connection_SendCommand_Test3()
        {
            using (var connection = new Connection(CreateClientFactory()))
            {
                Connect(connection);

                var  mre                   = new ManualResetEvent(false);
                bool dataSentFired         = false;
                bool statusMessageFired    = false;
                bool connectedChangedFired = false;

                connection.DataSent      += (sender, args) => dataSentFired = true;
                connection.StatusMessage += (sender, args) =>
                {
                    statusMessageFired = true;
                    mre.Set();
                };
                connection.ConnectedChanged += (sender, args) => connectedChangedFired = true;

                _stream.Expect(x => x.EndWrite(null)).IgnoreArguments().Throw(new IOException("Write failed."));
                _tcpClient.Expect(x => x.Close()).Do(new Action(() => _tcpClient.Client = null));

                connection.SendCommand("command");
                mre.WaitOne();

                Assert.IsFalse(dataSentFired);
                Assert.IsTrue(statusMessageFired);
                Assert.IsTrue(connectedChangedFired);
            }

            _tcpClient.VerifyAllExpectations();
            _stream.VerifyAllExpectations();
        }
Example #6
0
 public void SendCommandTest1()
 {
     using (var connection = new Connection(CreateClientFactory()))
     {
         connection.SendCommand("command");
     }
 }
Example #7
0
        protected override void DoTerm()
        {
            on = false;
            if (Connection.SrcpVersion >= ServerConnection.Version8)
            {
                string command = string.Format("TERM {0} POWER", Bus);
                try
                {
                    Connection.SendCommand(command);
                }
                catch (Exception)
                {
                    if (Connection.DDW)
                    {
                        ///WORKAROUND

                        // Ingnore errors and send power off
                        Update();
                    }
                    else
                    {
                        throw;
                    }
                }
            }
            else
            {
                Update();
            }
        }
Example #8
0
        protected override void DoTerm()
        {
            for (int i = 0; i < ports.Count; i++)
            {
                ports[i] = false;
            }
            if (Connection.SrcpVersion >= ServerConnection.Version8)
            {
                string command = string.Format("TERM {0} GA {1}", Bus, Address);
                try
                {
                    Connection.SendCommand(command);
                }
                catch (Exception)
                {
                    if (Connection.DDW)
                    {
                        ///WORKAROUND

                        // Ingnore errors and send power off
                        Update();
                    }
                    else
                    {
                        throw;
                    }
                }
            }
            else
            {
                Update();
            }
        }
Example #9
0
        /// <summary> Envoie la requette et appelle la fonction callback quand la reponse est recue </summary>
        public static void SendAsync(string parameters, Action <string> callback)
        {
            Connection.SendCommand(NextID + " " + new StackTrace().GetFrame(1).GetMethod().DeclaringType.Name + " " + parameters);

            WaitingForResponse.Enqueue(new Request(NextID, callback));
            NextID++;
        }
Example #10
0
 public void SendMessage(string message)
 {
     Connection.SendCommand(new Client_PRI_CharacterSendMessage {
         Character = Name,
         Message   = message
     });
 }
Example #11
0
        /// <summary>
        ///   Gets the databases.
        /// </summary>
        /// <returns></returns>
        public IEnumerable <IMongoDatabase> GetDatabases()
        {
            var result = _connection.SendCommand(_configuration.SerializationFactory, "admin", typeof(Document), new Document("listDatabases", 1));

            return(((IEnumerable <Document>)result["databases"])
                   .Select(database => (string)database["name"])
                   .Select(name => new MongoDatabase(_configuration, _connection, name))
                   .Cast <IMongoDatabase>());
        }
        private Task SendDisconnectCommand()
        {
            var command = new SignalCommand
            {
                Type         = CommandType.Disconnect,
                ExpiresAfter = TimeSpan.FromMinutes(30)
            };

            return(Connection.SendCommand(command));
        }
Example #13
0
 void SendInit(int bus, int address, string protocol, int steps, int numberOfFunctions)
 {
     protocol = GetProtocolIntern(Connection, protocol, address, steps);
     if (Connection.SrcpVersion >= ServerConnection.Version8)
     {
         string command = string.Format("INIT {0} GL {1} {2} {3} {4}", bus, address, protocol, steps, numberOfFunctions);
         Connection.SendCommand(command);
     }
     this.protocolIntern = protocol;
 }
        internal async Task Ack(string convId,
                                string msgId)
        {
            AckCommand ack = new AckCommand {
                Cid = convId,
                Mid = msgId
            };
            GenericCommand command = NewCommand(CommandType.Ack);

            command.AckMessage = ack;
            await Connection.SendCommand(command);
        }
Example #15
0
        void Update()
        {
            if (Initialized && Connection != null && Connection.Started)
            {
                StringBuilder commandBuilder = new StringBuilder();
                commandBuilder.Append("SET ");
                if (Connection.SrcpVersion < ServerConnection.Version8)
                {
                    commandBuilder.Append("GL ");
                    commandBuilder.Append(protocolIntern);
                    commandBuilder.Append(" ");
                }
                else
                {
                    commandBuilder.Append(Bus);
                    commandBuilder.Append(" GL ");
                }
                commandBuilder.Append(address);
                commandBuilder.Append(" ");
                commandBuilder.Append(direction);
                commandBuilder.Append(" ");
                commandBuilder.Append(step);
                commandBuilder.Append(" ");
                commandBuilder.Append(steps);



                for (int i = 0; i < functions.Length; i++)
                {
                    bool function = functions[i];
                    commandBuilder.Append(" ");
                    commandBuilder.Append(function ? "1" : "0");

                    if (i == 0 && Connection.SrcpVersion < ServerConnection.Version8)
                    {
                        commandBuilder.Append(" ");
                        commandBuilder.Append(functions.Length - 1);
                    }
                }
                // WORKAROUND:
                if (Connection.DDW && functions.Length < 5 && Connection.SrcpVersion >= ServerConnection.Version8)
                {
                    for (int i = functions.Length; i < 5; i++)
                    {
                        commandBuilder.Append(" 0");
                    }
                }
                string command = commandBuilder.ToString();
                Connection.SendCommand(command);
            }
        }
Example #16
0
 protected override void DoTerm()
 {
     step = 0;
     Array.Clear(functions, 0, functions.Length);
     if (Connection.SrcpVersion >= ServerConnection.Version8)
     {
         string command = string.Format("TERM {0} GL {1}", Bus, address);
         Connection.SendCommand(command);
     }
     else
     {
         Update();
     }
 }
Example #17
0
 void SendInit(int bus, int address, string protocol, string additionalParameters)
 {
     if (Connection.SrcpVersion >= ServerConnection.Version8)
     {
         if (additionalParameters == null || additionalParameters.Length == 0)
         {
             Connection.SendCommand(string.Format("INIT {0} GA {1} {2}", bus, address, protocol));
         }
         else
         {
             Connection.SendCommand(string.Format("INIT {0} GA {1} {2} {3}", bus, address, protocol, additionalParameters));
         }
     }
 }
Example #18
0
        void SendInit(int bus, string type, string parameters)
        {
            string command;

            if (Connection.SrcpVersion < ServerConnection.Version8)
            {
                command = string.Format("INIT FB {0} {1}", type, parameters);
            }
            else
            {
                command = string.Format("INIT {0} FB {1} {2}", bus, type, parameters);
            }
            Connection.Info += new InfoHandler(Connection_Info);
            Connection.SendCommand(command);
        }
Example #19
0
        protected override void DoTerm()
        {
            string command;

            if (Connection.SrcpVersion < ServerConnection.Version8)
            {
                command = string.Format("TERM FB {0}", type);
            }
            else
            {
                command = string.Format("TERM {0} FB", Bus);
            }
            Connection.SendCommand(command);

            Connection.Info -= new InfoHandler(Connection_Info);
        }
Example #20
0
        public void SendCommandWhitespaceTest()
        {
            using (var connection = new Connection(CreateClientFactory()))
            {
                Connect(connection);

                bool statusMessageFired = false;
                connection.StatusMessage += (sender, args) => statusMessageFired = true;
                connection.SendCommand("   ");

                Assert.IsTrue(statusMessageFired);
            }

            _tcpClient.VerifyAllExpectations();
            _stream.VerifyAllExpectations();
        }
Example #21
0
        /// <summary> Envoie la requette et bloque l'execution tant que la reponse n'est pas recue </summary>
        public static string SendBlocking(string parameters)
        {
            //Construit et envoie la commande
            Connection.SendCommand(NextID + " " + new StackTrace().GetFrame(1).GetMethod().DeclaringType.Name + " " + parameters);

            //Quand la reponse est recue on met a jour res, ce qui permet de sortir du while bloquant
            string res = null;

            WaitingForResponse.Enqueue(new Request(NextID, answer => res = answer));
            NextID++;
            while (res == null)
            {
                Connection.Update();
            }

            return(res);
        }
Example #22
0
        /// <summary>
        ///  Обработчик команд из очери команд
        /// </summary>
        /// <returns></returns>
        private async void ExecuteCommands()
        {
            // Берём очередную команду из очереди
            // Отправляем запрос на сервер
            // Читаем ответ
            // Разбираем ответ и заполняем данными
            IsRunning = true;
            bool terminating = _Terminating;

            while (!terminating)
            {
                MpdCommand command = null;
                lock (_Lock)
                {
                    terminating = _Terminating;
                    if (_CommandQueue.Count > 0)
                    { // Есть команды к выполнению. Забираем команду из очереди  и разморахиваем процесс
                        command = _CommandQueue.Dequeue();
                        _ThreadEvent.Reset();
                    }
                }
                if (!terminating)
                {
                    if (command == null)
                    { // Если нет команд к выполнению замораживаем процесс
                        _ThreadEvent.WaitOne();
                    }
                    else
                    {
                        try
                        {
                            await _Connection.SendCommand(command.FullSyntax);

                            _SentCommandQueue.Enqueue(command);
                            _Response += await _Connection.ReadResponse();;
                            _Response  = ParceResponse(_Response);
                        }
                        catch (Exception e)
                        {
                            NotifyCriticalError(_resldr.GetString("CommunicationError") + Utilities.GetExceptionMsg(e));
                        }
                    }
                }
            } // End while
            IsRunning = false;
        }
Example #23
0
        void Update()
        {
            if (Initialized && Connection != null && Connection.Started)
            {
                string command;
                string onCommand = on ? "ON" : "OFF";
                if (Connection.SrcpVersion < ServerConnection.Version8)
                {
                    command = string.Format("SET POWER {0}", onCommand);
                }
                else
                {
                    command = string.Format("SET {0} POWER {1}", Bus, onCommand);
                }

                Connection.SendCommand(command);
            }
        }
Example #24
0
        void Update(int port)
        {
            if (Initialized && Connection != null && Connection.Started)
            {
                int value = ports[port] ? 1 : 0;

                string command;
                if (Connection.SrcpVersion < ServerConnection.Version8)
                {
                    command = string.Format("SET GA {0} {1} {2} {3} -1", protocol, Address, port, value);
                }
                else
                {
                    command = string.Format("SET {0} GA {1} {2} {3} -1", Bus, Address, port, value);
                }

                Connection.SendCommand(command);
            }
        }
        internal async Task Read(string convId,
                                 LCIMMessage msg)
        {
            ReadCommand read  = new ReadCommand();
            ReadTuple   tuple = new ReadTuple {
                Cid = convId
            };

            // 当不传 msg 时,服务端将其收到的最后一条消息标记为已读,可能与客户端不一致
            if (msg != null)
            {
                tuple.Mid       = msg.Id;
                tuple.Timestamp = msg.SentTimestamp;
            }
            read.Convs.Add(tuple);
            GenericCommand command = NewCommand(CommandType.Read);

            command.ReadMessage = read;
            await Connection.SendCommand(command);
        }
Example #26
0
        public void SendCommandTest2()
        {
            using (var connection = new Connection(CreateClientFactory()))
            {
                Connect(connection);

                bool dataLengthSentFired = false;
                bool statusMessageFired  = false;
                connection.DataLengthSent += (sender, args) => dataLengthSentFired = true;
                connection.StatusMessage  += (sender, args) => statusMessageFired = true;
                var buffer = Encoding.ASCII.GetBytes("command\n");
                _stream.Expect(x => x.Write(buffer, 0, buffer.Length));
                connection.SendCommand("command");

                Assert.IsTrue(dataLengthSentFired);
                Assert.IsTrue(statusMessageFired);
            }

            _tcpClient.VerifyAllExpectations();
            _stream.VerifyAllExpectations();
        }
Example #27
0
 public void Ping()
 {
     AssertConnected();
     Connection.SendCommand(Commands.Ping);
     HandleOkPacket(Connection.ReadPacket());
 }
Example #28
0
 /// <summary>
 ///   Sends the command.
 /// </summary>
 /// <param name = "rootType">Type of serialization root.</param>
 /// <param name = "command">The CMD.</param>
 /// <returns></returns>
 public Document SendCommand(Type rootType, Document command)
 {
     return(_connection.SendCommand(_configuration.SerializationFactory, Name, rootType, command));
 }
Example #29
0
        private void ConfigureWirelessSettingsViaUSBToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ProgressDialog progress = new ProgressDialog
            {
                Text  = "Configuring NGIMU Wireless Settings",
                Style = ProgressBarStyle.Marquee,
                CancelButtonEnabled = true,
                ProgressMessage     = "",
                Progress            = 0,
                ProgressMaximum     = 1,
                DialogResult        = DialogResult.Cancel,
            };

            ManualResetEvent contiueResetEvent = new ManualResetEvent(false);

            bool hasBeenCanceled = false;

            progress.OnCancel += delegate(object s, FormClosingEventArgs fce)
            {
                hasBeenCanceled = true;
                contiueResetEvent.Set();
            };

            progress.FormClosed += delegate(object s, FormClosedEventArgs fce)
            {
                contiueResetEvent.Set();
            };

            Thread configureWirelessSettingsViaUSBThread = new Thread(() =>
            {
                progress.UpdateProgress(0, "Searching for USB connection.");

                bool found = false;
                ConnectionSearchResult foundConnectionSearchResult = null;

                // search for serial only connections
                using (SearchForConnections searchForConnections = new SearchForConnections(ConnectionSearchTypes.Serial))
                {
                    searchForConnections.DeviceDiscovered += delegate(ConnectionSearchResult connectionSearchResult)
                    {
                        found = true;
                        foundConnectionSearchResult = connectionSearchResult;
                        contiueResetEvent.Set();
                    };

                    contiueResetEvent.Reset();

                    searchForConnections.BeginSearch();

                    contiueResetEvent.WaitOne();

                    searchForConnections.EndSearch();
                }

                if (hasBeenCanceled == true)
                {
                    return;
                }

                if (foundConnectionSearchResult == null)
                {
                    return;
                }

                string deviceDescriptor = foundConnectionSearchResult.DeviceDescriptor;

                // open connection to first device found
                progress.UpdateProgress(0, $"Found device {deviceDescriptor}.");

                using (Connection connection = new Connection(foundConnectionSearchResult))
                {
                    connection.Connect();

                    progress.UpdateProgress(0, $"Restoring default settings.");
                    connection.SendCommand(Command.Default);

                    connection.Settings.WifiMode.Value                  = WifiMode.Client;
                    connection.Settings.WifiClientSSID.Value            = MainForm.DefaultWifiClientSSID;
                    connection.Settings.WifiClientKey.Value             = MainForm.DefaultWifiClientKey;
                    connection.Settings.WifiReceivePort.Value           = MainForm.SynchronisationMasterPort;
                    connection.Settings.SynchronisationMasterPort.Value = MainForm.SynchronisationMasterPort;
                    connection.Settings.SendRateRssi.Value              = MainForm.DefaultSendRateRssi;

                    progress.UpdateProgress(0, $"Writing wireless settings.");
                    this.WriteSettingsWithExistingProgress(progress, new List <ConnectionRow>(), true, new[] { connection.Settings });
                }

                progress.DialogResult = DialogResult.OK;

                Invoke(new MethodInvoker(() => { progress.Close(); }));
            });

            configureWirelessSettingsViaUSBThread.Name = "Configure Wireless Settings Via USB";
            configureWirelessSettingsViaUSBThread.Start();

            if (progress.ShowDialog(this) == DialogResult.OK)
            {
                this.ShowInformation($@"Configuration of device complete.");
            }
        }
Example #30
0
      public void Connection_SendCommand_Test3()
      {
         using (var connection = new Connection(CreateClientFactory()))
         {
            Connect(connection);

            var mre = new ManualResetEvent(false);
            bool dataSentFired = false;
            bool statusMessageFired = false;
            bool connectedChangedFired = false;

            connection.DataSent += (sender, args) => dataSentFired = true;
            connection.StatusMessage += (sender, args) =>
            {
               statusMessageFired = true;
               mre.Set();
            };
            connection.ConnectedChanged += (sender, args) => connectedChangedFired = true;

            _stream.Expect(x => x.EndWrite(null)).IgnoreArguments().Throw(new IOException("Write failed."));
            _tcpClient.Expect(x => x.Close()).Do(new Action(() => _tcpClient.Client = null));

            connection.SendCommand("command");
            mre.WaitOne();

            Assert.IsFalse(dataSentFired);
            Assert.IsTrue(statusMessageFired);
            Assert.IsTrue(connectedChangedFired);
         }

         _tcpClient.VerifyAllExpectations();
         _stream.VerifyAllExpectations();
      }
Example #31
0
 public void Connection_SendCommand_Test1()
 {
    using (var connection = new Connection(CreateClientFactory()))
    {
       Assert.Throws<InvalidOperationException>(() => connection.SendCommand("command"));
    }
 }
Example #32
0
      public void Connection_SendCommand_Test2()
      {
         using (var connection = new Connection(CreateClientFactory()))
         {
            Connect(connection);

            var mre = new ManualResetEvent(false);
            bool dataSentFired = false;
            bool statusMessageFired = false;

            connection.DataSent += (sender, args) =>
            {
               dataSentFired = true;
               mre.Set();
            };
            connection.StatusMessage += (sender, args) => statusMessageFired = true;

            connection.SendCommand("command");
            mre.WaitOne();

            Assert.IsTrue(dataSentFired);
            Assert.IsTrue(statusMessageFired);
         }

         _tcpClient.VerifyAllExpectations();
         _stream.VerifyAllExpectations();
      }
Example #33
0
        public void SendCommandWhitespaceTest()
        {
            using (var connection = new Connection(CreateClientFactory()))
             {
            Connect(connection);

            bool statusMessageFired = false;
            connection.StatusMessage += (sender, args) => statusMessageFired = true;
            connection.SendCommand("   ");

            Assert.IsTrue(statusMessageFired);
             }

             _tcpClient.VerifyAllExpectations();
             _stream.VerifyAllExpectations();
        }
Example #34
0
        public void SendCommandTest3()
        {
            using (var connection = new Connection(CreateClientFactory()))
             {
            Connect(connection);

            bool dataLengthSentFired = false;
            bool statusMessageFired = false;
            bool connectedChangedFired = false;
            connection.DataLengthSent += (sender, args) => dataLengthSentFired = true;
            connection.StatusMessage += (sender, args) => statusMessageFired = true;
            connection.ConnectedChanged += (sender, args) => connectedChangedFired = true;
            var buffer = Encoding.ASCII.GetBytes("command\n");
            _stream.Expect(x => x.Write(buffer, 0, buffer.Length)).Throw(new IOException("Write failed."));
            connection.SendCommand("command");

            Assert.IsFalse(dataLengthSentFired);
            Assert.IsTrue(statusMessageFired);
            Assert.IsTrue(connectedChangedFired);
             }

             _tcpClient.VerifyAllExpectations();
             _stream.VerifyAllExpectations();
        }
Example #35
0
 public void SendCommand(Command cmd)
 {
     Connection.SendCommand(cmd);
 }
Example #36
0
 public void SendCommandTest1()
 {
     using (var connection = new Connection(CreateClientFactory()))
      {
     connection.SendCommand("command");
      }
 }