Beispiel #1
0
        public async Task RunAsync(CancellationToken token = default(CancellationToken))
        {
            var request = CreateRequest();

            if (OnWriteAsync != null)
            {
                await OnWriteAsync.Invoke(request, token);
            }
            else
            {
                OnWrite?.Invoke(request);
            }

            using (token.Register(() => request.Abort(), false))
                using (var response = (HttpWebResponse)await request.GetResponseAsync()) {
                    token.ThrowIfCancellationRequested();

                    if (OnReadAsync != null)
                    {
                        await OnReadAsync.Invoke(response, token);
                    }
                    else
                    {
                        OnRead?.Invoke(response);
                    }
                }
        }
Beispiel #2
0
        /// <summary>
        /// The internal read handler.
        /// </summary>
        /// <param name="sourcePtr">The underlying pointer to the source.</param>
        /// <param name="buffer">A pointer to an array of bytes.</param>
        /// <param name="length">The maximum number of bytes to be read.</param>
        /// <param name="userDataPtr">User data associated with the source.</param>
        /// <returns>The total number of bytes read into the buffer.</returns>
        internal long ReadHandler(IntPtr sourcePtr, IntPtr buffer, long length, IntPtr userDataPtr)
        {
            if (length <= 0)
            {
                return(0);
            }

            var tempArray = ArrayPool <byte> .Shared.Rent((int)length);

            try
            {
                var readLength = OnRead?.Invoke(tempArray, (int)length);
                if (!readLength.HasValue)
                {
                    return(-1);
                }

                if (readLength.Value > 0)
                {
                    Marshal.Copy(tempArray, 0, buffer, readLength.Value);
                }

                return(readLength.Value);
            }
            catch
            {
                return(-1);
            }
            finally
            {
                ArrayPool <byte> .Shared.Return(tempArray);
            }
        }
Beispiel #3
0
        public string ReadLine()
        {
            string result = this.In.ReadLine();

            OnRead?.Invoke(this, new EventArgs());
            return(result);
        }
Beispiel #4
0
        public Reader(Settings settings, OnRead onRead)
        {
            m_settings = settings;
            m_onRead   = onRead;

            ReConnect();
        }
Beispiel #5
0
        public int Read()
        {
            int result = this.In.Read();

            OnRead?.Invoke(this, new EventArgs());
            return(result);
        }
Beispiel #6
0
        public void Menu()
        {
            bool exit = false;

            while (!exit)
            {
                Console.WriteLine($"\n\t\t\t {typeof(T).Name} Menu" +
                                  $"\n\t1.Create {typeof(T).Name}" +
                                  $"\n\t2.Read {typeof(T).Name}" +
                                  $"\n\t3.Update {typeof(T).Name}" +
                                  $"\n\t4.Delete {typeof(T).Name}" +
                                  $"\n\t5.GetCollection of {typeof(T).Name}" +
                                  $"\n\t6.ReadFromFile" +
                                  $"\n\t7.WriteInFile" +
                                  $"\n\tanother.Exit\n");

                ConsoleKeyInfo consoleKey = Console.ReadKey();

                Console.WriteLine();

                switch (consoleKey.Key)
                {
                case ConsoleKey.D1:
                    OnCreate?.Invoke(this, EventArgs.Empty);
                    break;

                case ConsoleKey.D2:
                    OnRead?.Invoke(this, EventArgs.Empty);
                    break;

                case ConsoleKey.D3:
                    OnUpdate?.Invoke(this, EventArgs.Empty);
                    break;

                case ConsoleKey.D4:
                    OnDelete?.Invoke(this, EventArgs.Empty);
                    break;

                case ConsoleKey.D5:
                    OnReadCollection?.Invoke(this, EventArgs.Empty);
                    break;

                case ConsoleKey.D6:
                    OnReadFromFile?.Invoke(this, EventArgs.Empty);
                    break;

                case ConsoleKey.D7:
                    OnWriteInFile?.Invoke(this, EventArgs.Empty);
                    break;

                default:
                    exit = true;
                    break;
                }

                Console.ReadKey();
                Console.Clear();
            }
        }
Beispiel #7
0
        public byte ReadByte(int address)
        {
            byte datax = data.Span[address];

            OnRead?.Invoke(this, new BasicRegisterEvent(address, datax));

            return(datax);
        }
Beispiel #8
0
 public override int Read(byte[] buffer, int offset, int count)
 {
     if (!CanRead)
     {
         throw new InvalidOperationException("Cannot read from a read-only stream.");
     }
     OnRead?.Invoke(this, buffer, offset, count);
     return(baseStream_.Read(buffer, offset, count));
 }
Beispiel #9
0
        object Read(string prompt, int DataType)
        {
            ReadEventArgs tmpArgs = new ReadEventArgs {
                Prompt = prompt, DataType = DataType
            };

            OnRead?.Invoke(this, tmpArgs);
            return(tmpArgs.Result);
        }
        public void Run()
        {
            var request = CreateRequest();

            OnWrite?.Invoke(request);

            using (var response = (HttpWebResponse)request.GetResponse()) {
                OnRead?.Invoke(response);
            }
        }
Beispiel #11
0
 private void ProcessedRead(IAsyncResult ar)
 {
     try
     {
         OnRead.EndInvoke(ar);
     }
     catch (Exception e)
     {
         Console.WriteLine(e);
     }
 }
Beispiel #12
0
        public virtual TValue Read(int address)
        {
            var value = _memory[address];

            OnRead?.Invoke(this, new MemoryReadEventArgs <TValue>()
            {
                Address = address,
                Value   = value
            });

            return(value);
        }
Beispiel #13
0
                public virtual void OnCharacteristicRead(Android.Bluetooth.BluetoothDevice device, int requestId, int offset)
                {
                    CharacteristicReadRequest readRequest = new CharacteristicReadRequest
                    {
                        SourceDevice         = BluetoothManager.BluetoothDeviceWrapper.GetBluetoothDeviceFromDroidDevice((Service.Server as GattServer).BluetoothManager, device),
                        TargetCharacteristic = this,
                        Offset    = offset,
                        RequestId = requestId,
                    };

                    OnRead?.Invoke(this, readRequest);
                    //Service.Server.SendResponse(BluetoothManager.BluetoothDeviceWrapper.GetBluetoothDeviceFromDroidDevice((Service.Server as GattServer).BluetoothManager, device), requestId, null);
                }
Beispiel #14
0
                    public virtual void OnReadRequest(BluetoothDevice droidDevice, int requestId, int offset)
                    {
                        var bluetoothManager = (Characteristic.Service.Server as GattServer).BluetoothManager;
                        var device           = BluetoothManager.BluetoothDeviceWrapper.GetBluetoothDeviceFromDroidDevice(bluetoothManager, droidDevice);
                        DescriptorReadRequest readRequest = new DescriptorReadRequest
                        {
                            Device           = device,
                            RequestId        = requestId,
                            TargetDescriptor = this,
                            Offset           = offset,
                        };

                        OnRead?.Invoke(this, readRequest);
                    }
Beispiel #15
0
        public void Add(byte data)
        {
            switch (data)
            {
            case (byte)Protocol.ProtocolEnd:
                var dataArray = mBuffer.DequeueAll();
                var blockData = RawDataToBlockData(dataArray);
                OnRead.Invoke(blockData);
                break;

            default:
                mBuffer.Enqueue(data);
                break;
            }
        }
Beispiel #16
0
 public TerminalService()
 {
     _process = new Process
     {
         StartInfo =
         {
             FileName               = "cmd.exe",
             //Arguments = "/k",
             UseShellExecute        = false,
             RedirectStandardOutput = true,
             RedirectStandardInput  = true,
             RedirectStandardError  = true
         }
     };
     _process.OutputDataReceived += (sender, e) => OnRead?.Invoke(e.Data);
     _process.ErrorDataReceived  += (sender, e) => OnError?.Invoke(e.Data);
 }
Beispiel #17
0
 public Trigger(ClientTcp client)
 {
     visionClient = client;
     visionClient.OnReceiveEvent += (ip, b, s) =>
     {
         CamHelper.ParsingCamData(s, (cam, sid, str, data) =>
         {
             Task.Run(() =>
             {
                 TimeoutObject.Set();
                 LogRead.Log.Info($"读码结果:{str}");
                 OnLog?.Invoke(str);
                 OnRead?.Invoke(cam, sid, data);
             });
         });
     };
 }
Beispiel #18
0
        public void WaitMessage()
        {
            if (_connection is null || _connection.IsConnected == false)
            {
                return;
            }

            _cancellationTokenSource = new CancellationTokenSource();
            var token         = _cancellationTokenSource.Token;
            var networkStream = _connection.GetStream();

            _streamReader = new StreamReader(networkStream);

            Task.Run(() =>
            {
                try
                {
                    while (_connection != null && _connection.IsConnected && !token.IsCancellationRequested)
                    {
                        var read = _streamReader.ReadLine();

                        if (read != null)
                        {
                            OnRead?.Invoke(this, read);
                        }

                        Task.Delay(10).Wait();
                    }
                }
                catch (Exception ex)
                {
                    if (!token.IsCancellationRequested)
                    {
                        OnException?.Invoke(this, new MessageSenderReadException(ex));
                    }
                }
                finally
                {
                    DisposeClient();
                    OnDisconnected?.Invoke(this, null);
                }
            });
        }
Beispiel #19
0
        /// <summary>
        /// Считывает массив данных
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public T[] ReadArray <T>() where T : struct
        {
            if (!CheckStructType(typeof(T)))
            {
                throw new ByteException("Method assepts only primitive CLR types as <T> parameter, e.g. int, char, double...");
            }

            List <T> array = new List <T>();

            int sizeBytes = GetByteCount(typeof(T));

            long len = BaseStream.Length / sizeBytes;

            try
            {
                for (int i = 0; i < len; i++)
                {
                    // BaseStream.Seek(i * sizeBytes, SeekOrigin.Begin);

                    dynamic value = ReadValue <T>();
                    OnRead?.Invoke(value);
                    array.Add(value);
                }
            }
            catch (IOException)
            {
                Console.Error.WriteLine("io: Unable to create file stream due to an i/o error, exiting...");
            }
            catch (System.Security.SecurityException)
            {
                Console.Error.WriteLine("security: Not enough permissions to open stream on this file, exiting...");
            }
            catch (ArgumentException)
            {
                Console.Error.WriteLine("env: Output file path given incorrectly, exiting...");
            }
            catch (Exception e)
            {
                Console.Error.WriteLine($"error: {e.Message}");
            }

            return(array.ToArray());
        }
Beispiel #20
0
        public byte ReadByte(int addr)
        {
            byte data = 0;

            if (addr == SDCARD_DATA)
            {
                data = outData.PeekLeft();
                outData.PopLeft();
            }

            if (addr == SDCARD_CMD)
            {
                data = (byte)interruptState;
            }

            OnRead?.Invoke(this, new SDCardReadEvent(addr, data));

            return(data);
        }
Beispiel #21
0
        private void ReadHandler(IAsyncResult ar)
        {
            var clientObject = ar.AsyncState as ClientObject;

            if (clientObject == null)
            {
                StateChanged.Invoke("", ClientState.UnknownReceiveError);
                return;
            }

            var tcp = clientObject.Tcp;

            if (!tcp.Connected)
            {
                StateChanged.Invoke(clientObject.Address, ClientState.ReceiveError);
                return;
            }

            if (!ar.IsCompleted)
            {
                StateChanged.Invoke(clientObject.Address, ClientState.Disconnected);
                return;
            }

            int countRead = 0;

            try
            {
                countRead = tcp.GetStream().EndRead(ar);
            }
            catch
            {
            }

            if (countRead > 0)
            {
                clientObject.CopyRawBufferToBuffer(countRead);
                OnRead.Invoke(clientObject.Address, clientObject.Buffer);
            }

            StartRead(clientObject, tcp);
        }
Beispiel #22
0
        /// <summary>
        /// Keeps readings states from device
        /// </summary>
        private void ReadThreadLoop()
        {
            InsureMillisecondPassed();
            try
            {
                while (IsReading)
                {
                    OnRead?.Invoke(ReadingState(Device, LastTime));
                    InsureMillisecondPassed();
                }
            }
            catch (Exception e)
            {
                OnStop?.Invoke(e.ToString());
                ExceptionHandler?.Invoke(new Exception("Something went wrong while reading. ", e));
                return;
            }

            OnStop?.Invoke("Normal");
        }
Beispiel #23
0
        public async Task Read()
        {
            try
            {
                string str  = "data.encry";
                var    file = await EncryCodeFolder.GetFileAsync(str);

                str = await FileIO.ReadTextAsync(file);

                var json = JsonSerializer.Create();
                EncryCodeSecretScribe encryCodeSecretScribe =
                    json.Deserialize <EncryCodeSecretScribe>(new JsonTextReader(new StringReader(str)));
                //EncryCodeSecretScribe = encryCodeSecretScribe;
                Name       = encryCodeSecretScribe.Name;
                ComfirmKey = encryCodeSecretScribe.ComfirmKey;
                Str        = encryCodeSecretScribe.Str;
                OnRead?.Invoke(this, true);
            }
            catch (Exception)
            {
                OnRead?.Invoke(this, false);
            }
        }
        public OutgoMailQueue(TKey key)
        {
            Key             = key;
            _mailChannel    = Channel.CreateUnbounded <MailPacket>();
            _totalMailCount = 0;

            _ = Task.Run(async() =>
            {
                await foreach (var mail in _mailChannel.Reader.ReadAllAsync())
                {
                    Interlocked.Decrement(ref _totalMailCount);

                    if (OnRead != null)
                    {
                        await OnRead.Invoke(mail);
                    }
                }

                //Console.ForegroundColor = ConsoleColor.Green;
                //Console.WriteLine("OutgoMailQueue !!!end");
                //Console.ResetColor();
            });
        }
Beispiel #25
0
 public void ExecQuery(string query)
 {
     using (SqlConnection connection = new SqlConnection(connectionString))
     {
         using (SqlCommand command = new SqlCommand())
         {
             command.Connection  = connection;
             command.CommandText = query;
             connection.Open();
             command.CommandType = System.Data.CommandType.Text;
             using (SqlDataReader reader = command.ExecuteReader())
             {
                 if (reader.HasRows)
                 {
                     while (reader.Read())
                     {
                         OnRead.Invoke(this, reader);
                     }
                 }
             }
         }
     }
 }
 private void ReadBytes(int bytesRead, byte[] content)
 {
     if (bytesRead > 0)
     {
         // Check the integrity of the message
         if (content[0] == MessageStart)
         {
             if (content[content.Length - 1] == MessageEnd)
             {
                 if (Checksum(content, ChecksumPosition))
                 {
                     OnRead?.Invoke(this, new ReadEventArgs(bytesRead, content));
                 }
                 else
                 {
                     OnError?.Invoke(this, new ErrorEventArgs(ErrorType.InvalidChecksum,
                                                              string.Format("Invalid checksum. Received: {0}", SIMOCModel.Helpers.ByteArray.ToString(content))));
                 }
             }
             else
             {
                 OnError?.Invoke(this, new ErrorEventArgs(ErrorType.InvalidEndOfMessage,
                                                          string.Format("Invalid end of message. Expected: {0}. Received: {1}", (byte)MessageEnd, content[content.Length - 1])));
             }
         }
         else
         {
             OnError?.Invoke(this, new ErrorEventArgs(ErrorType.InvalidStartOfMessage,
                                                      string.Format("Invalid start of message. Expected: {0}. Received: {1}", (byte)MessageStart, content[0])));
         }
     }
     else
     {
         OnError?.Invoke(this, new ErrorEventArgs(ErrorType.EmptyMessag,
                                                  string.Format("The message was empty. Received: {0}", SIMOCModel.Helpers.ByteArray.ToString(content))));
     }
 }
        public override int Read(byte[] buffer, int offset, int count)
        {
            OnRead?.Invoke(buffer, offset, count);
            var read = _innerStream.Read(buffer, offset, count);

            try
            {
                var expectedDelayInMs = DelayPerByte.TotalMilliseconds * read;
                if (ReadTimeout > expectedDelayInMs)
                {
                    Task.Delay(new TimeSpan(DelayPerByte.Ticks * read)).Wait(_cancellationToken);
                }
                else
                {
                    Task.Delay(ReadTimeout).Wait(_cancellationToken);
                    throw new IOException($"..timed out because no data was received for {ReadTimeout}ms.", new TimeoutException());
                }
            }
            catch (OperationCanceledException)
            {
            }

            return(read);
        }
Beispiel #28
0
        public void Run()
        {
            var request = CreateRequest();

            if (OnWrite != null)
            {
                OnWrite.Invoke(request);
            }
            else
            {
                OnWriteAsync?.Invoke(request, CancellationToken.None).GetAwaiter().GetResult();
            }

            using (var response = (HttpWebResponse)request.GetResponse()) {
                if (OnRead != null)
                {
                    OnRead?.Invoke(response);
                }
                else
                {
                    OnReadAsync?.Invoke(response, CancellationToken.None).GetAwaiter().GetResult();
                }
            }
        }
Beispiel #29
0
        public async Task RunAsync()
        {
            var request = CreateRequest();

            if (OnWriteAsync != null)
            {
                await OnWriteAsync.Invoke(request);
            }
            else if (OnWrite != null)
            {
                OnWrite.Invoke(request);
            }

            using (var response = (HttpWebResponse)await request.GetResponseAsync()) {
                if (OnReadAsync != null)
                {
                    await OnReadAsync.Invoke(response);
                }
                else if (OnRead != null)
                {
                    OnRead?.Invoke(response);
                }
            }
        }
Beispiel #30
0
 private void ProcessPayload(BytesSegment bs)
 {
     OnRead?.Invoke(this, bs);
 }