/// <summary> /// Initializes a new instance of the <see cref="DelegateDataReader"/> class. /// </summary> /// <param name="name">The name of the value type read.</param> /// <param name="length">The length of the binary buffer in bytes.</param> /// <param name="type">The <see cref="Type" /> of the read values.</param> /// <param name="func">The delegate used to read from the buffer file.</param> internal DelegateDataReader(string name, int length, Type type, ReadDelegate func) { _Name = name; _Length = length; _Type = type; _Func = func; }
public override int EndRead(IAsyncResult asyncResult) { if (asyncResult == null) { throw new ArgumentNullException("asyncResult"); } if (!async) { return(base.EndRead(asyncResult)); } AsyncResult ares = asyncResult as AsyncResult; if (ares == null) { throw new ArgumentException("Invalid IAsyncResult", "asyncResult"); } ReadDelegate r = ares.AsyncDelegate as ReadDelegate; if (r == null) { throw new ArgumentException("Invalid IAsyncResult", "asyncResult"); } return(r.EndInvoke(asyncResult)); }
private static void ReadBitsFinal( byte slaveAddress, IDictionary <ushort, bool> bitsData, ReadDelegate readDel, string dataName, int readStart, int length, IEnumerable <ushort> addresses) { int byteLength = length / 8; if (length % 8 != 0) { ++byteLength; } var bytes = readDel.Invoke(slaveAddress, readStart, byteLength, length); if (bytes == null || bytes.Count != byteLength) { throw new Exception( string.Format("Error when reading {0}. SlaveAddress: {1}, Address {2}, Length {3}", dataName, slaveAddress, readStart, length)); } foreach (ushort address in addresses) { int index = address - readStart; bitsData.Add(address, GetBitFromByte(bytes[index / 8], index % 8)); } }
// Dispose(bool disposing) executes in two distinct scenarios. // If disposing equals true, the method has been called directly // or indirectly by a user's code. Managed and unmanaged resources // can be disposed. // If disposing equals false, the method has been called by the // runtime from inside the finalizer and you should not reference // other objects. Only unmanaged resources can be disposed. private void Dispose(bool disposing) { // Check to see if Dispose has already been called. if (_disposed) { return; } // If disposing equals true, dispose all managed // and unmanaged resources. if (disposing) { // Dispose managed resources. _dllhandle = IntPtr.Zero; _open = null; _close = null; _start = null; _reset = null; _config = null; _read = null; _write = null; _checkTx = null; _getDeviceList = null; } // Dispose native ( unmanaged ) resources, if exits // Note disposing has been done. _disposed = true; }
public override int EndRead(IAsyncResult asyncResult) { if (asyncResult == null) { throw new ArgumentNullException("asyncResult"); } AsyncResult ar = asyncResult as AsyncResult; if (ar == null) { throw new ArgumentException("Invalid asyncResult", "asyncResult"); } ReadDelegate del = ar.AsyncDelegate as ReadDelegate; if (del == null) { throw new ArgumentException("Invalid asyncResult", "asyncResult"); } #if SSHARP return(del.EndInvokeEx <int> (asyncResult)); #else return(del.EndInvoke(asyncResult)); #endif }
public override IAsyncResult BeginRead(byte [] buffer, int offset, int size, AsyncCallback cb, object state) { CheckDisposed(); if (!isRead) { throw new NotSupportedException(); } if (buffer == null) { throw new ArgumentNullException("buffer"); } if (offset < 0 || offset > buffer.Length) { throw new ArgumentOutOfRangeException("offset"); } if (size < 0 || size > buffer.Length - offset) { throw new ArgumentOutOfRangeException("offset+size"); } ReadDelegate del = ReadInternal; return(del.BeginInvoke(buffer, offset, size, cb, state)); }
public static void Initialize() { if (Initialized) return; Core.Log(LogSeverity.Minor, "initializing stream hooks.."); _memStreamReadOff = Utility.FindPattern("blue", "55 8b ec 56 8b 75 0c 57 8b f9 85 f6 78 ? 8b 47 18 8d 0c 30 3b 4f 10 76 ? 8b 47 18 8b 77 10"); _memStreamWriteOff = Utility.FindPattern("blue", "55 8b ec 53 8b 5d 0c 56 8b f1 57 8b 7e 18 03 fb 3b 7e 10 76 ? 56 8b c7 e8 ? ? ? ? 84 c0 75 ? 5f 5e"); if (_memStreamReadOff != 0 && _memStreamWriteOff != 0) { Core.Log(LogSeverity.Minor, "stream functions: Read: 0x" + (_memStreamReadOff - BlueOS.Library.ToInt64()).ToString("X") + " Write: 0x" + (_memStreamWriteOff - BlueOS.Library.ToInt64()).ToString("X")); _memStreamReadOrig = Utility.Magic.RegisterDelegate<ReadDelegate>(_memStreamReadOff); _memStreamWriteOrig = Utility.Magic.RegisterDelegate<WriteDelegate>(_memStreamWriteOff); _memStreamReadFake = HandleRead; _memStreamWriteFake = HandleWrite; _memStreamReadDetour = Utility.Magic.Detours.Create(_memStreamReadOrig, _memStreamReadFake, "MemStream::Read"); _memStreamWriteDetour = Utility.Magic.Detours.Create(_memStreamWriteOrig, _memStreamWriteFake, "MemStream::Write"); Core.Log(LogSeverity.Minor, "stream functions hooked"); } else Core.Log(LogSeverity.Minor, "pattern failed to find Read/Write stream functions"); Initialized = true; }
private void Mainform_Load(object sender, EventArgs e) { /* Create delegate for reading data */ this.mySerialDelegate = new ReadDelegate(ProcessInData); /* Create Splash Screen Form */ Splashform = new MaximSplashScreenForm(3); Splashform.disableCheckBoxValue = Properties.Settings.Default.DisableSplashValue; Splashform.showOK_Click(false); Splashform.ShowDialog(); /* Setup SerialUSB Form */ USBform = new SerialUSBForm(serialPort1); USBform.ShowDialog(); /* Subscribe to event DataReceived with the onDataReceived Function */ serialPort1.DataReceived += this.SerialPort1_DataReceived; Pullup_Indicator.Visible = false; textBox1.Visible = false; /* Initial Communication between GUI & FW */ try { serialPort1.WriteLine("INIT"); } catch (System.InvalidOperationException) { MessageBox.Show("You are not connected to a Serial Port!", "Serial Error"); return; } }
public override IAsyncResult BeginRead(byte [] buffer, int offset, int count, AsyncCallback cback, object state) { if (!CanRead) { throw new NotSupportedException("This stream does not support reading"); } if (buffer == null) { throw new ArgumentNullException("buffer"); } if (count < 0) { throw new ArgumentOutOfRangeException("count", "Must be >= 0"); } if (offset < 0) { throw new ArgumentOutOfRangeException("offset", "Must be >= 0"); } ReadDelegate d = new ReadDelegate(this.Read); return(d.BeginInvoke(buffer, offset, count, cback, state)); }
public void FastRead(ReadCallback callback, int timeout) { var readDelegate = new ReadDelegate(FastRead); var asyncState = new HidAsyncState(readDelegate, callback); readDelegate.BeginInvoke(timeout, EndRead, asyncState); }
public Format(string name, IsValidDelegate isValid, ReadDelegate read, WriteDelegate write) { Name = name; IsValid = isValid; Read = read; Write = write; }
public static void Initialize() { if (Initialized) { return; } Core.Log(LogSeverity.Minor, "initializing stream hooks.."); _memStreamReadOff = Utility.FindPattern("blue", "55 8b ec 56 8b 75 0c 57 8b f9 85 f6 78 ? 8b 47 18 8d 0c 30 3b 4f 10 76 ? 8b 47 18 8b 77 10"); _memStreamWriteOff = Utility.FindPattern("blue", "55 8b ec 53 8b 5d 0c 56 8b f1 57 8b 7e 18 03 fb 3b 7e 10 76 ? 56 8b c7 e8 ? ? ? ? 84 c0 75 ? 5f 5e"); if (_memStreamReadOff != 0 && _memStreamWriteOff != 0) { Core.Log(LogSeverity.Minor, "stream functions: Read: 0x" + (_memStreamReadOff - BlueOS.Library.ToInt64()).ToString("X") + " Write: 0x" + (_memStreamWriteOff - BlueOS.Library.ToInt64()).ToString("X")); _memStreamReadOrig = Utility.Magic.RegisterDelegate <ReadDelegate>(_memStreamReadOff); _memStreamWriteOrig = Utility.Magic.RegisterDelegate <WriteDelegate>(_memStreamWriteOff); _memStreamReadFake = HandleRead; _memStreamWriteFake = HandleWrite; _memStreamReadDetour = Utility.Magic.Detours.Create(_memStreamReadOrig, _memStreamReadFake, "MemStream::Read"); _memStreamWriteDetour = Utility.Magic.Detours.Create(_memStreamWriteOrig, _memStreamWriteFake, "MemStream::Write"); Core.Log(LogSeverity.Minor, "stream functions hooked"); } else { Core.Log(LogSeverity.Minor, "pattern failed to find Read/Write stream functions"); } Initialized = true; }
public void ShouldReadFileMultithreadedCorrectly() { ReadDelegate action = () => { using (var image = new MagickImage()) { image.Read(Files.Coders.CartoonNetworkStudiosLogoAI); Assert.AreEqual(765, image.Width); Assert.AreEqual(361, image.Height); Assert.AreEqual(MagickFormat.Ai, image.Format); } }; var results = new IAsyncResult[3]; for (int i = 0; i < results.Length; ++i) { results[i] = action.BeginInvoke(null, null); } for (int i = 0; i < results.Length; ++i) { action.EndInvoke(results[i]); } }
/** * Mainform_Load(Object sender, EventArgs e) draws the main window. The code in this * method sets up the form appropriately. The splash screen form and the serial port * connection form both get instantiated here. Also, the serial port delegate function * (callback) gets setup here -- this.mySerialDelegate = new ReadDelegate(ProcessInData);<br> * * The application's state shall be read from Properties.Settings.Default and restored to * the main Window's GUI controls. In this case it is the disable Check Box state for the * Splash Screen.<br> * @code * maximSplashScreenForm.disableCheckBoxValue = Properties.Settings.Default.disableSplashValue; * @endcode <br> * * Finally, the code sets the application's title and version in the main Windows's title * bar and in the middle text region of the status bar. It also shows (or hides) the * splash screen based on state of "Disable" checkbox. * * @param sender The sender of the event. * @param e The arguments for the event. * <br> ****************************************************************************/ private void Mainform_Load(object sender, EventArgs e) { /* Create delegate for reading data */ this.mySerialDelegate = new ReadDelegate(ProcessInData); /* Create Splash Screen Form */ maximSplashScreenForm = new SplashScreen("DS18B20 Config Custom", "Version 1.0", "Copyright Maxim Integrated Products", "", 3); maximSplashScreenForm.disableCheckBoxValue = Properties.Settings.Default.disableSplashValue; maximSplashScreenForm.showOKButton(false); if (!maximSplashScreenForm.disableCheckBoxValue) { maximSplashScreenForm.ShowDialog(); } /* Setup SerialUSB Form */ USBform = new SerialUSBForm(serialPort1); USBform.ShowDialog(); /* Subscribe to event DataReceived with the onDataReceived Function */ serialPort1.DataReceived += this.SerialPort1_DataReceived; /* Initial Communication between GUI & FW */ try { serialPort1.WriteLine("INIT"); } catch (System.InvalidOperationException) { MessageBox.Show("You are not connected to a Serial Port!", "Serial Error"); return; } }
/// <summary> /// Adds a map reader to the memory /// </summary> /// <param name="start">The start address</param> /// <param name="end">The end address</param> /// <param name="action">The method to implement</param> public void MapReadHandler(uint start, uint end, ReadDelegate action) { for (var i = start; i <= end; i++) { ReadMap[i] = action; } }
override public void Read(ReadCallback callback, int timeout) { if (!IsConnected) { return; } if (IsReadInProgress) { //UnityEngine.Debug.Log("Clone paket"); __lastHIDReport.Status = HIDReport.ReadStatus.Buffered; callback.BeginInvoke(__lastHIDReport, EndReadCallback, callback); // callback.Invoke(__lastHIDReport); return; } IsReadInProgress = true; //TODO make this fields or use pool var readDelegate = new ReadDelegate(Read); var asyncState = new HidAsyncState(readDelegate, callback); readDelegate.BeginInvoke(timeout, EndRead, asyncState); }
public static ReadDelegate <T> CreateDelegate() { DynamicMethod dm = new DynamicMethod("Read", null, new Type[] { typeof(byte[]), typeof(int), typeof(T).MakeByRefType() }, Assembly.GetExecutingAssembly().ManifestModule); dm.DefineParameter(1, ParameterAttributes.None, "data"); dm.DefineParameter(2, ParameterAttributes.None, "offset"); dm.DefineParameter(3, ParameterAttributes.Out, "value"); ILGenerator generator = dm.GetILGenerator(); generator.DeclareLocal(typeof(byte).MakePointerType(), pinned: true); generator.Emit(OpCodes.Ldarg_0); generator.Emit(OpCodes.Ldarg_1); generator.Emit(OpCodes.Ldelema, typeof(byte)); generator.Emit(OpCodes.Stloc_0); generator.Emit(OpCodes.Ldarg_2); generator.Emit(OpCodes.Ldloc_0); generator.Emit(OpCodes.Conv_I); generator.Emit(OpCodes.Ldobj, typeof(T)); generator.Emit(OpCodes.Stobj, typeof(T)); generator.Emit(OpCodes.Ldc_I4_0); generator.Emit(OpCodes.Conv_U); generator.Emit(OpCodes.Stloc_0); generator.Emit(OpCodes.Ret); Value = (ReadDelegate <T>)dm.CreateDelegate(typeof(ReadDelegate <T>)); return(Value); }
public FileAsset(String filename, XMLMethod method, object obj, ReadDelegate readDelegate) { Filename = filename; Method = method; Object = obj; ReadMethod = readDelegate; }
public override int EndRead(IAsyncResult asyncResult) { AsyncResult result = (AsyncResult)asyncResult; ReadDelegate caller = (ReadDelegate)result.AsyncDelegate; return(caller.EndInvoke(asyncResult)); }
public BinaryReader EndRead(IAsyncResult ar) { AsyncResult a = (AsyncResult)ar; ReadDelegate d = (ReadDelegate)a.AsyncDelegate; return(d.EndInvoke(ar)); }
private static Type ReadDictionaryType(IBinaryReader reader, out ReadDelegate keyReadDelegate, out ReadDelegate valueReadDelegate) { Type clrArrayType; Type type4; GpType gpType = (GpType)reader.ReadByte(); GpType type2 = (GpType)reader.ReadByte(); if (gpType == GpType.Unknown) { clrArrayType = typeof(object); keyReadDelegate = new ReadDelegate(GpBinaryByteReader.Read); } else { clrArrayType = GpBinaryByteTypeConverter.GetClrArrayType(gpType); keyReadDelegate = GetReadDelegate(gpType); } if (type2 == GpType.Unknown) { type4 = typeof(object); valueReadDelegate = new ReadDelegate(GpBinaryByteReader.Read); } else { type4 = GpBinaryByteTypeConverter.GetClrArrayType(type2); valueReadDelegate = GetReadDelegate(type2); } return(typeof(Dictionary <,>).MakeGenericType(new Type[] { clrArrayType, type4 })); }
static EnumBitStreamer() { var generation_args = new MethodGenerationArgs(); MethodInfo read_method_info, write_method_info, swap_method; #region Get read/write method info if (generation_args.UseUnderlyingType) { // Since we use a type-parameter hack to imply we want to use the underlying type // for the TStreamType, we have to use reflection to instantiate StreamType<> // using kUnderlyingType, which kStreamType is set to up above var stream_type_gen_class = typeof(StreamType <>); var stream_type_class = stream_type_gen_class.MakeGenericType(generation_args.StreamType); read_method_info = stream_type_class.GetField("kRead").GetValue(null) as MethodInfo; write_method_info = stream_type_class.GetField("kWrite").GetValue(null) as MethodInfo; swap_method = stream_type_class.GetField("kBitSwap").GetValue(null) as MethodInfo; } else { // If we don't use the type-parameter hack and instead are explicitly given the // integer type, we can safely instantiate StreamType<> without reflection read_method_info = StreamType <TStreamType> .kRead; write_method_info = StreamType <TStreamType> .kWrite; swap_method = StreamType <TStreamType> .kBitSwap; } #endregion kRead = GenerateReadMethod(generation_args, read_method_info, swap_method); kWrite = GenerateWriteMethod(generation_args, write_method_info, swap_method); Instance = new EnumBitStreamer <TEnum, TStreamType, TOptions>(); }
public void Read(ReadCallback callback) { ReadDelegate readDelegate = Read; HidAsyncState @object = new HidAsyncState(readDelegate, callback); readDelegate.BeginInvoke(EndRead, @object); }
public virtual int EndRead(IAsyncResult asyncResult) { if (asyncResult == null) { throw new ArgumentNullException("asyncResult"); } // Ideally we want to throw InvalidOperationException but for ECMA conformance we need to throw ArgExc instead. if (_readDelegate == null) { throw new ArgumentException(Environment.GetResourceString("InvalidOperation_WrongAsyncResultOrEndReadCalledMultiple")); } int numRead = -1; try { numRead = _readDelegate.EndInvoke(asyncResult); } finally { _readDelegate = null; _asyncActiveEvent.Set(); // Decrement the count to account for this async operation // and close the handle if no other IO is pending _CloseAsyncActiveEvent(Interlocked.Decrement(ref _asyncActiveCount)); } return(numRead); }
public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state) { ReadDelegate read = this.Read; return(read.BeginInvoke(buffer, offset, count, callback, state)); }
public Teacher[] SelectAggregatedTeachers() { string selectAggregatedTeachersQuery = @"SELECT t.name AS Name, COUNT(1) AS LessonsCount, t.fixed_salary AS Salary, t.hour_rate AS HourRate, t.fixed_salary + COALESCE(SUM(t.hour_rate * 2 * c.coefficient), 0) AS TotalPayment FROM Lessons AS l JOIN Courses AS c ON c.id = l.course_id JOIN Teachers AS t ON t.id = l.teacher_id GROUP BY l.teacher_id, t.name, t.fixed_salary, t.hour_rate"; var teachersList = new List <Teacher>(); ReadDelegate teacherReader = (reader) => { var teacher = new Teacher { Name = reader.GetString(0), LessonsCount = reader.GetInt32(1), FixedSalary = reader.GetDouble(2), HourRate = reader.GetInt32(3), TotalPayment = reader.GetDouble(4) }; teachersList.Add(teacher); }; Read(selectAggregatedTeachersQuery, teacherReader); return(teachersList.ToArray()); }
public void Read(ReadCallback callback) { var readDelegate = new ReadDelegate(Read); var asyncState = new HidAsyncState(readDelegate, callback); readDelegate.BeginInvoke(EndRead, asyncState); }
private static extern IntPtr ManagedRandomAccessFile_Create( ReadDelegate read, CloseDelegate close, GetSizeDelegate getSize, TellDelegate tell, SeekDelegate seek, ClosedDelegate closed, out IntPtr randomAccessFile);
/* ----------------------------------------------------------------- */ /// /// PdfiumReader /// /// <summary> /// Initializes a new instance of the PdfiumReader class with the /// specified arguments. /// </summary> /// /// <param name="src">Path of the source PDF file.</param> /// <param name="io">I/O handler.</param> /// /* ----------------------------------------------------------------- */ private PdfiumReader(string src, IO io) { Source = src; IO = io; _stream = IO.OpenRead(src); _delegate = new ReadDelegate(Read); }
protected internal static T ReadStoredObject <T>(T obj, ReadDelegate <T> readDelegate) { if (null == obj) { obj = readDelegate(); } return(obj); }
public int EndRead(IAsyncResult result) { AsyncResult art = result as AsyncResult; ReadDelegate del = art.AsyncDelegate as ReadDelegate; int i = del.EndInvoke(result); return(i); }
/// <summary> /// Begin asynchronous reading of data /// </summary> /// <param name="callback">The function to be called when data is done being read</param> public void ReadAsync(ReadCallback callback) { ReadDelegate del = new ReadDelegate(Read); del.BeginInvoke(AsyncReadEnd, new object[2] { del, callback }); }
// // Starts an asynchronous read operation. // public virtual IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback userCallback, object userState) { // Blocks if an asynchronous read is taking place. asyncActiveEvent.WaitOne(); readDelegate = new ReadDelegate(Read); return readDelegate.BeginInvoke(buffer, offset, count, userCallback, userState); }
// // Returns the result of an asynchronous read operation. // public virtual int EndRead(IAsyncResult ar) { if (ar == null) throw new ArgumentNullException("ar"); if (readDelegate == null) throw new InvalidOperationException("Wrong AsyncResult or EndRead called multiple times"); int result = -1; try { result = readDelegate.EndInvoke(ar); } finally { readDelegate = null; asyncActiveEvent.Set(); } return result; }
public virtual IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state) { if (!this.CanRead) { __Error.ReadNotSupported(); } Interlocked.Increment(ref this._asyncActiveCount); ReadDelegate delegate2 = new ReadDelegate(this.Read); if (this._asyncActiveEvent == null) { lock (this) { if (this._asyncActiveEvent == null) { this._asyncActiveEvent = new AutoResetEvent(true); } } } this._asyncActiveEvent.WaitOne(); this._readDelegate = delegate2; return delegate2.BeginInvoke(buffer, offset, count, callback, state); }
static void RunOnce() { if (bloggers == null || File.GetLastWriteTime (bloggersFile) > lastReadOfBloggersFile) { lastReadOfBloggersFile = File.GetLastWriteTime (bloggersFile); bloggers = BloggerCollection.LoadFromFile (bloggersFile); } disable_load = false; all = (Blogger []) bloggers.Bloggers.ToArray (typeof (Blogger)); lock (all) { next = 10; for (int i = 0; i < 10 && i < all.Length; i++) { Blogger b = all [i]; ReadDelegate d = new ReadDelegate (FeedCache.Read); d.BeginInvoke (b.Name, b.RssUrl, feed_done, b); } } wait_handle.WaitOne (300000, false); disable_load = true; for (int i = 0; i < (int) UpdateStatus.MAX; i++) { Console.WriteLine ("{0}: {1}", (UpdateStatus) i, counters [i]); } int error = counters [(int) UpdateStatus.Error]; int downloaded = counters [(int) UpdateStatus.Downloaded]; int updated = counters [(int) UpdateStatus.Updated]; if (error == 0 && downloaded == 0 && updated == 0) return; outFeed = new RssFeed (); RssChannel ch = new RssChannel (); ch.Title = "Monologue"; ch.Generator = "Monologue worker: b-diddy powered"; ch.Description = "The voices of Mono"; ch.Link = new Uri ("http://www.go-mono.com/monologue/"); ArrayList stories = new ArrayList (); DateTime minPubDate = DateTime.Now.AddDays (-14); foreach (Blogger b in bloggers.BloggersByUrl) { if (b.Channel == null) continue; foreach (RssItem i in b.Channel.Items) { if (i.PubDate == DateTime.MinValue) { b.DateError = true; } else if (i.PubDate >= minPubDate) { i.Title = b.Name + ": " + i.Title; i.PubDate = i.PubDate.ToUniversalTime (); stories.Add (i); } } } stories.Sort (new ReverseRssItemComparer ()); foreach (RssItem itm in stories) ch.Items.Add (itm); if (ch.Items.Count == 0) { Settings.Log ("No feeds to store."); return; } outFeed.Channels.Add (ch); outFeed.Write (rssOutFile); Render (); }
static void FeedDone(IAsyncResult ares) { AsyncResult a = (AsyncResult) ares; ReadResult res = null; try { res = ((ReadDelegate) a.AsyncDelegate).EndInvoke (ares); } catch { res = new ReadResult (UpdateStatus.Error); } if (disable_load) return; Blogger blogger = (Blogger) ares.AsyncState; blogger.Feed = res.Feed; blogger.UpdateFeed (); if (res.Status == UpdateStatus.CachedButError) blogger.Error = true; Settings.Log ("DONE {0}", blogger.RssUrl); lock (all) { loaded++; counters [(int) res.Status]++; if (loaded >= all.Length) wait_handle.Set (); if (next >= all.Length) return; Blogger b = all [next++]; ReadDelegate d = new ReadDelegate (FeedCache.Read); d.BeginInvoke (b.Name, b.RssUrl, feed_done, b); } }
public override IAsyncResult BeginRead( byte[] buffer, int offset, int count, AsyncCallback callback, object state) { this.checkDisposed (); if (buffer == null) { throw new ArgumentNullException("buffer is a null reference."); } if (offset < 0) { throw new ArgumentOutOfRangeException("offset is less than 0."); } if (offset > buffer.Length) { throw new ArgumentOutOfRangeException("offset is greater than the length of buffer."); } if (count < 0) { throw new ArgumentOutOfRangeException("count is less than 0."); } if (count > (buffer.Length - offset)) { throw new ArgumentOutOfRangeException("count is less than the length of buffer minus the value of the offset parameter."); } if (this.context.HandshakeState == HandshakeState.None) { // Note: Async code may have problem if they can't ensure that // the Negotiate phase isn't done during a read operation. // System.Net.HttpWebRequest protects itself from that problem lock (this.negotiate) { if (this.context.HandshakeState == HandshakeState.None) { this.NegotiateHandshake(); } } } IAsyncResult asyncResult = null; lock (this.read) { try { // If actual buffer is full readed reset it if (this.inputBuffer.Position == this.inputBuffer.Length && this.inputBuffer.Length > 0) { this.resetBuffer(); } if (!this.context.ConnectionEnd) { if ((this.inputBuffer.Length == this.inputBuffer.Position) && (count > 0)) { // bigger than max record length for SSL/TLS byte[] recbuf = new byte[16384]; // this will read data from the network until we have (at least) one // record to send back to the caller this.innerStream.BeginRead (recbuf, 0, recbuf.Length, new AsyncCallback (NetworkReadCallback), recbuf); if (!recordEvent.WaitOne (300000, false)) // 5 minutes { // FAILSAFE DebugHelper.WriteLine ("TIMEOUT length {0}, position {1}, count {2} - {3}\n{4}", this.inputBuffer.Length, this.inputBuffer.Position, count, GetHashCode (), Environment.StackTrace); throw new TlsException (AlertDescription.InternalError); } } } // return the record(s) to the caller rd = new ReadDelegate (this.inputBuffer.Read); asyncResult = rd.BeginInvoke (buffer, offset, count, callback, state); } catch (TlsException ex) { this.protocol.SendAlert(ex.Alert); this.Close(); throw new IOException("The authentication or decryption has failed."); } catch (Exception) { throw new IOException("IO exception during read."); } } return asyncResult; }
protected DataTable ReadDataTable() { int numCols = ReadInt32(); int numRows = ReadInt32(); ReadDelegate[] colReaders = new ReadDelegate[numCols]; Variant.EnumType[] colTypes = new Variant.EnumType[numCols]; for (int i = 0; i < numCols; ++i) { colTypes[i] = (Variant.EnumType)ReadInt32(); switch (colTypes[i]) { case VariantBase.EnumType.Float: colReaders[i] = () => ReadFloat(); break; case VariantBase.EnumType.Double: colReaders[i] = () => ReadDouble(); break; case VariantBase.EnumType.Boolean: colReaders[i] = () => ReadBoolean(); break; case VariantBase.EnumType.String: colReaders[i] = () => ReadString(); break; case VariantBase.EnumType.Int32: colReaders[i] = () => ReadInt32(); break; case VariantBase.EnumType.UInt32: colReaders[i] = () => ReadUInt32(); break; case VariantBase.EnumType.Int64: colReaders[i] = () => ReadInt64(); break; case VariantBase.EnumType.UInt64: colReaders[i] = () => ReadUInt64(); break; case VariantBase.EnumType.Time: colReaders[i] = () => ReadTime(); break; case VariantBase.EnumType.DateTime: colReaders[i] = () => ReadDateTime(); break; default: throw new VariantException("Case exhaustion: " + colTypes[i]); } } string[] colNames = new string[numCols]; for (int i = 0; i < numCols; ++i) { colNames[i] = ReadString(); } DataTable dt = new DataTable(); for (int i = 0; i < numCols; ++i) { dt.Columns.Add(new DataColumn(colNames[i], VariantPrimitiveBase.EnumToType(colTypes[i]))); }; // Write number of rows for (int i=0; i<numRows; ++i) { DataRow dr = dt.NewRow(); for (int j = 0; j < numCols; ++j) { dr[j] = colReaders[j](); } dt.Rows.Add(dr); } return dt; }
public SSLHelperStream(ReadDelegate Read, WriteDelegate Send) { ReadFromDevice = Read; SendToDevice = Send; }
private void ReadRegistersFinal( byte slaveAddress, IDictionary<KeyValuePair<ushort, int>, byte[]> registersData, ReadDelegate readDel, string dataName, int readStart, int length, IEnumerable<KeyValuePair<ushort, int>> addresses) { var byteLength = length * 2; var bytes = readDel.Invoke(slaveAddress, readStart, byteLength, length); if (bytes == null || bytes.Count != byteLength) { throw new Exception( string.Format("Error when reading {0}. SlaveAddress: {1}, Address {2}, Length {3}", dataName, slaveAddress, readStart, length)); } foreach (var address in addresses) { var index = (address.Key - readStart) * 2; registersData.Add(address, _bytesToRegistersConverter.GetBytes(bytes, index, address.Value)); } }
public async Task<HidDeviceData> FastReadAsync(int timeout = 0) { var readDelegate = new ReadDelegate(FastRead); return await Task<HidDeviceData>.Factory.FromAsync(readDelegate.BeginInvoke, readDelegate.EndInvoke, timeout, null); }
public virtual int EndRead(IAsyncResult asyncResult) { if (asyncResult == null) throw new ArgumentNullException("asyncResult"); // Ideally we want to throw InvalidOperationException but for ECMA conformance we need to throw ArgExc instead. if (_readDelegate == null) throw new ArgumentException(Environment.GetResourceString("InvalidOperation_WrongAsyncResultOrEndReadCalledMultiple")); int numRead = -1; try { numRead = _readDelegate.EndInvoke(asyncResult); } finally { _readDelegate = null; _asyncActiveEvent.Set(); // Decrement the count to account for this async operation // and close the handle if no other IO is pending _CloseAsyncActiveEvent(Interlocked.Decrement(ref _asyncActiveCount)); } return numRead; }
public virtual IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, Object state) { if (!CanRead) __Error.ReadNotSupported(); // Increment the count to account for this async operation BCLDebug.Assert(_asyncActiveCount >= 1, "ref counting mismatch, possible race in the code"); Interlocked.Increment(ref _asyncActiveCount); ReadDelegate d = new ReadDelegate(Read); // To avoid a race with a stream's position pointer & generating race // conditions with internal buffer indexes in our own streams that // don't natively support async IO operations when there are multiple // async requests outstanding, we will block the application's main // thread if it does a second IO request until the first one completes. if (_asyncActiveEvent == null) { lock(this) { if (_asyncActiveEvent == null) _asyncActiveEvent = new AutoResetEvent(true); } } bool r = _asyncActiveEvent.WaitOne(); BCLDebug.Assert(r, "AutoResetEvent didn't get a signal when we called WaitOne!"); BCLDebug.Assert(_readDelegate == null && _writeDelegate == null, "Expected no other readers or writers!"); // Set delegate before we call BeginInvoke, to avoid a race _readDelegate = d; IAsyncResult asyncResult = d.BeginInvoke(buffer, offset, count, callback, state); return asyncResult; }
public override IAsyncResult BeginRead (byte [] buffer, int offset, int count, AsyncCallback cback, object state) { if (!CanRead) throw new NotSupportedException ("This stream does not support reading"); if (buffer == null) throw new ArgumentNullException ("buffer"); if (count < 0) throw new ArgumentOutOfRangeException ("count", "Must be >= 0"); if (offset < 0) throw new ArgumentOutOfRangeException ("offset", "Must be >= 0"); ReadDelegate d = new ReadDelegate (this.Read); return d.BeginInvoke (buffer, offset, count, cback, state); }
void Test(WriteDelegate writeProc, ReadDelegate readProc, byte[] expectedBytes) { byte[] raw; using (MemoryStream ms = new MemoryStream ()) { MsgPackWriter writer = new MsgPackWriter (ms); writeProc (writer); raw = ms.ToArray (); } Assert.AreEqual (expectedBytes, raw, "pack failed"); using (MemoryStream ms = new MemoryStream (raw)) { MsgPackReader reader = new MsgPackReader (ms); readProc (reader); } }
public void Inicializar(TablaBase objetoDTO, CreateDelegate create, ReadDelegate read, UpdateDelegate update, DeleteDelegate delete, params ABMControl[] controls) { ObjetoDTO = objetoDTO; this.create = create; this.ReadMethod = read; this.update = update; this.delete = delete; BuildControls(controls); }
override public void Read(ReadCallback callback,int timeout) { if (!IsConnected) return; if (IsReadInProgress) { //UnityEngine.Debug.Log("Clone paket"); __lastHIDReport.Status = HIDReport.ReadStatus.Buffered; callback.BeginInvoke(__lastHIDReport, EndReadCallback, callback); // callback.Invoke(__lastHIDReport); return; } IsReadInProgress = true; //TODO make this fields or use pool var readDelegate = new ReadDelegate(Read); var asyncState = new HidAsyncState(readDelegate, callback); readDelegate.BeginInvoke(timeout,EndRead, asyncState); }
private void ReadRegisters( IEnumerable<KeyValuePair<ushort, int>> registersAddresses, byte slaveAddress, IDictionary<KeyValuePair<ushort, int>, byte[]> registersData, ReadDelegate readDel, string dataName) { var readStart = 0; var length = 0; const int maxLength = MaxReadBytesLength/2; var addresses = new List<KeyValuePair<ushort, int>>(maxLength); foreach (var regAddress in registersAddresses) { var address = regAddress.Key; if (length == 0) { readStart = address; length = regAddress.Value; addresses.Add(regAddress); } else { if (address >= readStart && address + regAddress.Value <= readStart + length) { addresses.Add(regAddress); continue; } var newLength = address - readStart + regAddress.Value; if (newLength > maxLength) { ReadRegistersFinal( slaveAddress, registersData, readDel, dataName, readStart, length, addresses); readStart = address; length = regAddress.Value; addresses.Clear(); } else { if (length < newLength) length = newLength; } addresses.Add(regAddress); } } if (length > 0) ReadRegistersFinal( slaveAddress, registersData, readDel, dataName, readStart, length, addresses); }
private static void ReadBitsFinal( byte slaveAddress, IDictionary<ushort, bool> bitsData, ReadDelegate readDel, string dataName, int readStart, int length, IEnumerable<ushort> addresses) { var byteLength = length / 8; if (length % 8 != 0) ++byteLength; var bytes = readDel.Invoke(slaveAddress, readStart, byteLength, length); if (bytes == null || bytes.Count != byteLength) { throw new Exception( string.Format("Error when reading {0}. SlaveAddress: {1}, Address {2}, Length {3}", dataName, slaveAddress, readStart, length)); } foreach (var address in addresses) { var index = address - readStart; bitsData.Add(address, GetBitFromByte(bytes[index / 8], index % 8)); } }
override public HIDReport ReadBuffered() { if (!IsConnected) return null; if (IsReadInProgress) { __lastHIDReport.Status = HIDReport.ReadStatus.Buffered; return __lastHIDReport; } IsReadInProgress = true; //TODO make this fields or use pool var readDelegate = new ReadDelegate(Read); readDelegate.BeginInvoke(0, EndReadBuffered, readDelegate); return __lastHIDReport; }
private static void ReadBits( IEnumerable<ushort> bitsAddresses, byte slaveAddress, IDictionary<ushort, bool> bitsData, ReadDelegate readDel, string dataName) { var readStart = 0; var length = 0; const int maxLength = MaxReadBitsLength; var addresses = new List<ushort>(maxLength); foreach (var address in bitsAddresses) { if (length == 0) { readStart = address; length = 1; addresses.Add(address); } else { if (address >= readStart && address < readStart + length) { addresses.Add(address); continue; } var newLength = address - readStart + 1; if (newLength > maxLength) { ReadBitsFinal( slaveAddress, bitsData, readDel, dataName, readStart, length, addresses); readStart = address; length = 1; addresses.Clear(); } else { if (length < newLength) length = newLength; } addresses.Add(address); } } if (length > 0) ReadBitsFinal(slaveAddress, bitsData, readDel, dataName, readStart, length, addresses); }
public IAsyncResult BeginRead (byte [] buffer, int offset, int count, AsyncCallback cb, object state) { ReadDelegate del = new ReadDelegate (Read); return del.BeginInvoke (buffer, offset, count, cb, state); }
public override IAsyncResult BeginRead (byte [] array, int offset, int numBytes, AsyncCallback userCallback, object stateObject) { if (handle == MonoIO.InvalidHandle) throw new ObjectDisposedException ("Stream has been closed"); if (!CanRead) throw new NotSupportedException ("This stream does not support reading"); if (array == null) throw new ArgumentNullException ("array"); if (numBytes < 0) throw new ArgumentOutOfRangeException ("numBytes", "Must be >= 0"); if (offset < 0) throw new ArgumentOutOfRangeException ("offset", "Must be >= 0"); // reordered to avoid possible integer overflow if (numBytes > array.Length - offset) throw new ArgumentException ("Buffer too small. numBytes/offset wrong."); if (!async) return base.BeginRead (array, offset, numBytes, userCallback, stateObject); ReadDelegate r = new ReadDelegate (ReadInternal); return r.BeginInvoke (array, offset, numBytes, userCallback, stateObject); }
public virtual int EndRead(IAsyncResult asyncResult) { if (asyncResult == null) { throw new ArgumentNullException("asyncResult"); } if (this._readDelegate == null) { throw new ArgumentException(Environment.GetResourceString("InvalidOperation_WrongAsyncResultOrEndReadCalledMultiple")); } int num = -1; try { num = this._readDelegate.EndInvoke(asyncResult); } finally { this._readDelegate = null; this._asyncActiveEvent.Set(); this._CloseAsyncActiveEvent(Interlocked.Decrement(ref this._asyncActiveCount)); } return num; }
public string ExecuteReadDelegate(ReadDelegate del) { lastDel = del; myThread = null; Execute(); return myStringFromDel; }
public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state) { ReadDelegate r = new ReadDelegate(Read); return r.BeginInvoke(buffer, offset, count, callback, state); }