Esempio n. 1
0
        private string ReadTcpStream()
        {
            StringBuilder readAsciiContent = new StringBuilder();

            try
            {
                if (_tcpClientInstance.Connected && _networkStreamInstance.CanRead)
                {
                    var buffer = new byte[4096];
                    while (_networkStreamInstance.DataAvailable)
                    {
                        int bytesRead = _networkStreamInstance.Read(buffer, 0, buffer.Length);
                        readAsciiContent.Append(Encoding.ASCII.GetString(buffer, 0, bytesRead));
                    }
                }
                else
                    throw new ApplicationException("TcpClient instance not connected or NetworkStream instance not readable.");
            }
            catch
            {
                String ErrMsg = "Unable to read the stream. Check if socket is connected.";
                PreBootLogger.LogError($"ReadStream: {ErrMsg}. Throwing exception.");
                throw new ParserException(ErrMsg);
            }
            if (0 != readAsciiContent.Length)
                PreBootLogger.LogDebug($"ReadStream: Called/Exited after reading {readAsciiContent.Length} bytes.");

            return (readAsciiContent.ToString());
        }
Esempio n. 2
0
 public void DeviceCanConnect(IPAddress ipAddress, int port)
 {
     DateTime start = DateTime.Now;
     DateTime finish = start.AddMinutes(10);
     using (TcpClient tcpClientInstance = new TcpClient())
     {
         do
         {
             if (PingDevice(ipAddress, 2000))
             {
                 try
                 {
                     // Validate we can connect
                     tcpClientInstance.Connect(ipAddress, port);
                     if (tcpClientInstance.Connected)
                     {
                         PreBootLogger.LogDebug($"{ClassName}: DeviceCanConnect: Connection succeeded to " + ipAddress + ":" + port);
                         return;
                     }
                     PreBootLogger.LogDebug($"{ClassName}: DeviceCanConnect: Connection failed to " + ipAddress + ":" + port);
                 }
                 //To Do: catch a specific exception
                 catch (Exception e)
                 {
                     PreBootLogger.LogError($"{ClassName}: DeviceCanConnect: Failed to connect to " + ipAddress + ":" + port + " Error: " + e.Message);
                 }
                 Thread.Sleep(5000);
             }
         } while (DateTime.Now < finish);
     }//end: using (TcpClient TcpClientInstance = new System.Net.Sockets.TcpClient())
     PreBootLogger.LogError($"{ClassName}: DeviceCanConnect(string, int): Unable to verify " + ipAddress + " is connected after 10 minutes. Threw an Exception");
     throw new ParserException("Unable to verify " + ipAddress + " is connected after 10 minutes.");
 }
Esempio n. 3
0
 private void WriteTcpStream(byte[] data)
 {
     PreBootLogger.LogDebug($"WriteStream: Writing {data.Length} bytes of data to stream...");
     if (_tcpClientInstance.Connected && _networkStreamInstance.CanWrite)
     {
         _networkStreamInstance.Write(data, 0, data.Length);
     }
     else
     {
         PreBootLogger.LogError("WriteStream: Unable to write to the stream. Check if socket is connected. Threw an exception");
         throw new ParserException("Unable to write to the stream. Check if socket is connected");
     }
 }
Esempio n. 4
0
        public Boolean PingDevice(IPAddress ipAddress, int timeMs)
        {
            Ping pingSender = new Ping();
            PingReply reply = pingSender.Send(ipAddress, timeMs);

            if (reply?.Status == IPStatus.Success)
            {
                PreBootLogger.LogDebug($"{ClassName}: pingDevice: Pinging the Emulator for " + timeMs + " milliseconds. Status = " + reply.Status);
                return true;
            }
            PreBootLogger.LogDebug($"{ClassName}: pingDevice: Pinging the Emulator for " + timeMs + " milliseconds. Status = " + reply?.Status);
            return false;
        }
Esempio n. 5
0
 public void WriteTcpStream(string command)
 {
     PreBootLogger.LogDebug($"WriteStream: Writing {command} to stream...");
     if (_tcpClientInstance.Connected && _networkStreamInstance.CanWrite)
     {
         byte[] buffer = Encoding.ASCII.GetBytes(command);
         _networkStreamInstance.Write(buffer, 0, buffer.Length);
         WriteStream(bCR);
         WriteStream(bLF);
     }
     else
     {
         PreBootLogger.LogError($"WriteStream: Unable to send {command}. Unable to write to the stream. Check if socket is connected. Threw an exception");
         throw new ParserException("Unable to write to the stream. Check if socket is connected");
     }
 }
Esempio n. 6
0
        private void CloseTcp()
        {
            PreBootLogger.LogDebug($"Close: Called. Closing NetworkStream and TcpClient instances, {_ipAddress}: {_port}");
            try
            {
                if (null != _networkStreamInstance)
                {
                    _networkStreamInstance.Close();
                    _networkStreamInstance.Dispose();
                    _networkStreamInstance = null;
                }
            }
            catch
            {
                // ignored
            }

            try
            {
                if (_tcpClientInstance?.Client != null)
                {
                    _tcpClientInstance.Client.Shutdown(SocketShutdown.Both);
                    _tcpClientInstance.Client.Close();
                    _tcpClientInstance.Client = null;
                }
            }
            catch
            {
                // ignored
            }

            try
            {
                if (null != _tcpClientInstance)
                {
                    _tcpClientInstance.Close();
                    _tcpClientInstance = null;
                }
            }
            catch
            {
                // ignored
            }
           

        }
Esempio n. 7
0
        /// <summary>
        /// Opens a TcpClient socket with a Networkstream wrapper
        /// </summary>
        /// <param name="ipAddress">Opens connection to this IP address</param>
        /// <param name="port">Opens connection to this port</param>
        public void Open(IPAddress ipAddress, Int32 port)
        {
            PreBootLogger.LogDebug("Connecting to " + ipAddress + ':' + port);
            _tcpClientInstance = new TcpClient();

            TimeSpan timeout = TimeSpan.FromMinutes(6);
            TimeSpan retrySleep = TimeSpan.FromSeconds(10);
            Stopwatch timer = new Stopwatch();
            int attempts = 0;
            timer.Start();
            do
            {
                try
                {
                    attempts++;
                    _tcpClientInstance.Connect(ipAddress, port);
                    _networkStreamInstance = new NetworkStream(_tcpClientInstance.Client) { ReadTimeout = 180000 };
                }
                catch (Exception ex)
                {
                    if (timer.Elapsed < timeout)
                    {
                        //Log as a warning, then wait a bit before retrying.
                        PreBootLogger.LogWarn($"TcpClient instance unable to connect after attempt {attempts}: {ex.Message}");
                        Thread.Sleep(retrySleep);
                    }
                    else
                    {
                        //We hit our timeout. Log as an error and give up.
                        string message =
                            $"Unable to connect to {_hostName} on port {port} after {timer.Elapsed:c} ({attempts} attempts).";
                        PreBootLogger.LogError(message + "\n\n" + ex);
                        this.Close();
                        throw new TimeoutException(message, ex);
                    }
                }
            }
            while (!_tcpClientInstance.Connected);

            //If we got out here, the TCP client connected.
            ClearStream();
            PreBootLogger.LogDebug($"Connection established with {ipAddress}:{port}.");
        }
Esempio n. 8
0
        private void WriteToTcpEfiShell(string command)
        {
            PreBootLogger.LogDebug("WriteToEfiShell: Writing \"" + command + "\" to efi shell...");
            if (_tcpClientInstance.Connected && _networkStreamInstance.CanWrite)
            {
                //clear any data that might be on the stream
                ClearStream();

                byte[] buffer = Encoding.ASCII.GetBytes(command);
                _networkStreamInstance.Write(buffer, 0, buffer.Length);
                _StringWaitFor(command);
                WriteStream(bCR);
                WriteStream(bLF);
            }
            else
            {
                PreBootLogger.LogError("WriteToEfiShell: Unable to send " + command + ". Unable to write to the stream. Check if socket is connected. Threw an exception");
                throw new ParserException("Unable to write to the stream. Check if socket is connected");
            }
        }
Esempio n. 9
0
 private string ReadTcpBufferedStream()
 {
     PreBootLogger.LogDebug("ReadBufferedStream: Reading buffer stream...");
     StringBuilder content = new StringBuilder();
     if (_tcpClientInstance.Connected && _networkStreamInstance.CanRead)
     {
         byte[] Buffer = new byte[1000];
         if (_networkStreamInstance.DataAvailable)
         {
             int bytesRead = _networkStreamInstance.Read(Buffer, 0, Buffer.Length);
             content.Append(Encoding.ASCII.GetString(Buffer, 0, bytesRead));
             //Console.WriteLine("bytesRead = {0},  {1}", bytesRead, Normalize(content));
         }
     }
     else
     {
         PreBootLogger.LogError("ReadBufferedStream: Unable to read the stream. Check if socket is connected. Threw an exception");
         throw new ParserException("Unable to read the stream. Check if socket is connected");
     }
     return content.ToString();
     //  return Normalize(content);
 }