static void Main(string[] args) { //Instantiation WriterDelegate writerDelegate = new WriterDelegate(Write); //Invocation writerDelegate("Welcome"); // Delegetes have 2 built in // 1- Func<T> takes up to 16 parameters and return value not void Func <int, int, int> sumDelegate = Sum; Console.WriteLine(sumDelegate(10, 20)); Console.WriteLine(sumDelegate(10, 20)); // 2- Action<T> takes up to 16 parameters and not return any thing Action <string> writeDelegate = Write; writeDelegate("String Action"); var executionManager = new ExecutionManager(); var opManager = new OperationManager(20, 10, executionManager); var result = opManager.Execute(Operation.Sum); Console.WriteLine(result); Console.WriteLine(opManager.Execute(Operation.Multiply)); Console.Read(); }
public void TakePictureTo(WriterDelegate action) { FreezeFrame(); var frameAddress = 0; var frameLength = GetFrameLength(); Debug.Print("Frame length: " + frameLength); var totalBytesRead = 0; while (frameLength > 0) { var segmentLength = System.Math.Min(frameLength, _frameBuffer.Length); totalBytesRead += ReadFrameSegment(segmentLength, _frameBuffer, frameAddress); action(_frameBuffer, segmentLength, frameLength); frameLength -= segmentLength; frameAddress += segmentLength; } ReadResponse(5, false); ResumeFrame(); }
public DelayWriter( string file, string message, int delay, WriterDelegate writeDelegate ) { this.file = file; this.delay = delay; this.message = message; this.method = writeDelegate; }
static void Main() { Logger logger = new Logger(); WriterDelegate writer = new WriterDelegate(logger.WriteMessage); writer("This is NOT A TEST!!!"); }
public Track(ICar <Engine>[] cars, int length, List <Viewer> viewers, Woman woman, WriterDelegate writerDelegate) { this.cars = cars; this.length = length; this.viewers = viewers; this.woman = woman; this.writerDelegate = writerDelegate; }
private void EmptyTable() { using (var writer = WriterDelegate.Invoke()) { writer.WriteLine($"DELETE FROM {Table}"); StatementDelegate.Invoke(writer); } }
public MyTerminalControlSlider(string id, MyStringId title, MyStringId tooltip) : base(id) { Title = title; Tooltip = tooltip; CompactWriter = CompactWriterMethod; m_amountConfirmed = AmountSetter; }
private void DropPeriodConstraint() { using (var writer = WriterDelegate.Invoke()) { const string sql = "ALTER TABLE {0} DROP PERIOD FOR SYSTEM_TIME;"; writer.WriteLine(sql, Settings.Table); StatementDelegate.Invoke(writer); } }
private void DisableSystemVersioning() { using (var writer = WriterDelegate.Invoke()) { const string sql = "ALTER TABLE {0} SET(SYSTEM_VERSIONING = OFF);"; writer.WriteLine(sql, Settings.Table); StatementDelegate.Invoke(writer); } }
private void DropHistoryTable() { using (var writer = WriterDelegate.Invoke()) { const string sql = "DROP TABLE {0};"; writer.WriteLine(sql, Settings.HistoryTable); StatementDelegate.Invoke(writer); } }
private void CreatePeriodIndex() { using (var writer = WriterDelegate.Invoke()) { const string sql = "ALTER TABLE {0} ADD PERIOD FOR SYSTEM_TIME ({1}, {2});"; writer.WriteLine(sql, Settings.Table, Settings.StartPeriodColumnName, Settings.EndPeriodColumnName); StatementDelegate.Invoke(writer); } }
private void EnableSystemVersioning() { using (var writer = WriterDelegate.Invoke()) { const string sql = "ALTER TABLE {0} SET(SYSTEM_VERSIONING = ON (HISTORY_TABLE = {1}, DATA_CONSISTENCY_CHECK = ON));"; writer.WriteLine(sql, Settings.Table, Settings.HistoryTable); StatementDelegate.Invoke(writer); } }
private void AddDefaultValues() { using (var writer = WriterDelegate.Invoke()) { const string sql = "UPDATE {0} SET {1} = '{2}', {3} = '{4}';"; writer.WriteLine(sql, Settings.Table, Settings.StartPeriodColumnName, "19000101 00:00:00.0000000", Settings.EndPeriodColumnName, "99991231 23:59:59.9999999"); StatementDelegate.Invoke(writer); } }
public override void Configure(UnderlyingSession session) { base.Configure(session); Context.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking; Set = Context.Set <TDataModel>(); Query = Set.AsNoTracking(); Write = Context.ChangeTracker.TrackGraph; }
private void DropPeriodColumns() { using (var writer = WriterDelegate.Invoke()) { const string sql = "ALTER TABLE {0} DROP COLUMN {1};"; writer.WriteLine(sql, Settings.Table, Settings.StartPeriodColumnName); writer.WriteLine(sql, Settings.Table, Settings.EndPeriodColumnName); StatementDelegate.Invoke(writer); } }
private void AddPeriodColumnConstraints() { using (var writer = WriterDelegate.Invoke()) { const string sql = "ALTER TABLE {0} ALTER COLUMN {1} [DATETIME2] NOT NULL;"; writer.WriteLine(sql, Settings.Table, Settings.StartPeriodColumnName); writer.WriteLine(sql, Settings.Table, Settings.EndPeriodColumnName); StatementDelegate.Invoke(writer); } }
public MyTerminalControlSlider(string id, MyStringId title, MyStringId tooltip) : base(id) { Title = title; Tooltip = tooltip; CompactWriter = CompactWriterMethod; m_amountConfirmed = AmountSetter; Serializer = delegate(BitStream stream, ref float value) { stream.Serialize(ref value); }; }
private unsafe void Write <T>(T obj, IntPtr data, ref int index, WriterDelegate <T> writer, WriterContext context) { if (context.references > 0) { var r = (byte *)(data + index); * r = (byte)GroBufTypeCode.Reference; *(int *)(r + 1) = context.references; index += 5; } context.start = index; writer(obj, true, data, ref index, new WriterContext(serializerId, context.length, context.start, trackReferences)); }
private void Write <T>(T value, int itemSize, int chunkId, WriterDelegate <T> writer) { int offset = AlignChunk(itemSize, chunkId); if (IntPtr.Zero != _nativeBuffer) { writer(_nativeBuffer, offset, value); } offset += itemSize; _offsetPerChunk[chunkId] = offset; return; }
public override void Execute(string LineInput) { WriterDelegate wr = null; if (ActionMappings.TryGetValue(LineInput.Trim(), out wr)) { wr(); } else { WriteNormalCode(LineInput); } }
internal static void InitInstance(Form form, WriterDelegate writedelegate) { if (_instance == null) { lock (mylock) { if (_instance == null) { _instance = new MsgWriter(form, writedelegate); } } } }
static void Main(string[] args) { //Instantiation WriterDelegate writerDelegate = new WriterDelegate(Write); //Invocation writerDelegate("Some example text."); Func <int, int, int> sumDelegate = Sum; Console.WriteLine(sumDelegate(10, 20)); Action <string> writeDelegate = Write; writeDelegate("String parameter to write."); }
public Game(ICarFactory factory, WriterDelegate writerDelegate) { List <Viewer> viewers = new List <Viewer>() { new Viewer() { Name = "Антон" }, new Viewer() { Name = "Дима" } }; Woman woman = new Woman() { Name = "Света" }; track = new Track(factory.Create(), length: 2000, viewers, woman, writerDelegate); }
/// <summary> /// Returns false when (a) the specified AsyncWrite value already exists, (b) the queue is full, or (c) the thread pool queue is full /// </summary> /// <param name="w"></param> /// <param name="writerDelegate"></param> /// <returns></returns> public bool Queue(AsyncWrite w, WriterDelegate writerDelegate) { lock (_sync) { if (GetQueuedBufferBytes() + w.GetBufferLength() > MaxQueueBytes) { return(false); //Because we would use too much ram. } if (c.ContainsKey(w.Key)) { return(false); //We already have a queued write for this data. } c.Add(w.Key, w); Task.Run( async() => { await writerDelegate(w); Remove(w); }).ConfigureAwait(false); return(true); } }
/// <summary> /// Returns false when (a) the specified AsyncWrite value already exists, (b) the queue is full, or (c) the thread pool queue is full /// </summary> /// <param name="w"></param> /// <returns></returns> public bool Queue(AsyncWrite w, WriterDelegate writerDelegate) { lock (_sync) { if (GetQueuedBufferBytes() + w.GetBufferLength() > MaxQueueBytes) { return(false); //Because we would use too much ram. } if (c.ContainsKey(HashTogether(w.RelativePath, w.ModifiedDateUtc))) { return(false); //We already have a queued write for this data. } if (!ThreadPool.QueueUserWorkItem(delegate(object state){ AsyncWrite job = state as AsyncWrite; writerDelegate(job); }, w)) { return(false); //thread pool refused } return(true); } }
private void PopulateDateDimension() { using (var writer = WriterDelegate.Invoke()) { foreach (var dimension in GenerateDateDimensions()) { string sql = $@"INSERT INTO {Table} ( [Date], [Year], [Month], [Day], [DayOfWeek], [DayOfYear], [DayOfWeekName], [MonthName], [Week], [Suffix] ) VALUES ( '{dimension.Date.ToString("yyyy-MM-dd")}', {dimension.Year}, {dimension.Month}, {dimension.Day}, {dimension.DayOfWeek}, {dimension.DayOfYear}, '{dimension.DayOfWeekName}', '{dimension.MonthName}', {dimension.Week}, '{dimension.Suffix}' )"; writer.WriteLine(sql, Table, dimension.Date); } StatementDelegate.Invoke(writer); } }
private static void test <T>(T value, WriterDelegate <T> w, ReaderDelegate <T> r) { Type type = value.GetType(); using (MemoryStream stream = new MemoryStream()) { using (BinaryWriter writer = new BinaryWriter(stream, Encoding.UTF8, true)) { Logger.LogMessage("Writing {0}: {1}", type, value); w(writer, value); } // Rewind stream.Position = 0; using (BinaryReader reader = new BinaryReader(stream, Encoding.UTF8, true)) { T readValue = r(reader); Logger.LogMessage("Read {0}: {1}", type, readValue); Assert.AreEqual(value, readValue); } } }
/// <summary> /// Returns false when (a) the specified AsyncWrite value already exists, (b) the queue is full, or (c) the thread pool queue is full /// </summary> /// <param name="w"></param> /// <param name="writerDelegate"></param> /// <returns></returns> public bool Queue(AsyncWrite w, WriterDelegate writerDelegate) { lock (_sync) { if (GetQueuedBufferBytes() + w.GetBufferLength() > MaxQueueBytes) { return(false); //Because we would use too much ram. } if (c.ContainsKey(w.Key)) { return(false); //We already have a queued write for this data. } c.Add(w.Key, w); if (!ThreadPool.QueueUserWorkItem(delegate(object state) { AsyncWrite job = state as AsyncWrite; writerDelegate(job); Remove(job); }, w)) { return(false); //thread pool refused } return(true); } }
public async Task <string> Work(int fuelTankVolume, WriterDelegate writerDelegate) { try { int time = 3000; var step = time * Volume / 1000; for (int i = 0; i < fuelTankVolume; i += step) { if (i == step) { OnActive?.Invoke(this, new EventArgs()); } await Task.Delay(time); writerDelegate($"{this.ToString()} Мощность = {Power} лс"); } OnDeactivate?.Invoke(this, new EventArgs()); return("ok"); } catch (Exception ex) { return(ex.Message); } }
/// <summary> /// Returns false when (a) the specified AsyncWrite value already exists, (b) the queue is full, or (c) the thread pool queue is full /// </summary> /// <param name="w"></param> /// <returns></returns> public bool Queue(AsyncWrite w,WriterDelegate writerDelegate ) { lock (_sync) { if (GetQueuedBufferBytes() + w.GetBufferLength() > MaxQueueBytes) return false; //Because we would use too much ram. if (c.ContainsKey(HashTogether(w.RelativePath, w.ModifiedDateUtc))) return false; //We already have a queued write for this data. if (!ThreadPool.QueueUserWorkItem(delegate(object state){ AsyncWrite job = state as AsyncWrite; writerDelegate(job); }, w)) return false; //thread pool refused return true; } }
EQXSerializer(Type type) { m_type = type; m_dynamicType = DynamicType.GetDynamicType(m_type); // build the functions here to pay the cost up front, once per type, instead of at runtime // whenever an element is processed ReaderDelegate readAttributes = (XPathNavigator reader, ref object target) => { }; ReaderDelegate readElements = (XPathNavigator reader, ref object target) => { }; ReaderDelegate readArrays = (XPathNavigator reader, ref object target) => { }; WriterDelegate writeAttributes = (XElement result, ref object target) => { }; WriterDelegate writeElements = (XElement result, ref object target) => { }; WriterDelegate writeArrays = (XElement result, ref object target) => { }; for (int i = 0; i < m_dynamicType.Members.Count; i++) { // this goofy setup is to prevent the dynamic methods from acessing the wrong member int temp = i; DynamicMember member = m_dynamicType.Members[temp]; object[] attributes = member.MemberInfo.GetCustomAttributes(false); EqXAttributeAttribute eqxAttribute = null; EqXElementAttribute eqxElement = null; EqXArrayAttribute eqxArray = null; DefaultValueAttribute defaultValue = null; foreach (object attr in attributes) { eqxAttribute = eqxAttribute ?? attr as EqXAttributeAttribute; eqxElement = eqxElement ?? attr as EqXElementAttribute; eqxArray = eqxArray ?? attr as EqXArrayAttribute; defaultValue = defaultValue ?? attr as DefaultValueAttribute; } // count how many of the eqx attributes are present int eqxCount = ((eqxAttribute != null) ? 1 : 0) + ((eqxElement != null) ? 1 : 0) + ((eqxArray != null) ? 1 : 0); #if DEBUG // check how many attributes are present in debug builds to sort out ambiguity if (eqxCount > 1) Trace.TraceWarning(TooManyAttributes, m_type.Name, member.MemberName); #endif // don't process members that aren't marked if (eqxCount < 1) continue; #if DEBUG if (!member.CanWrite && !member.CanRead) { Trace.TraceWarning("'{0}.{1}' has no way to be read or written, skipping it.", m_type.Name, member.MemberName); continue; } else if (!member.CanRead) { Trace.TraceWarning("'{0}.{1}' marked for serialization but can not be read, skipping it.", m_type.Name, member.MemberName); continue; } else if (!member.CanWrite) { Trace.TraceWarning("'{0}.{1}' marked for serialization but can not be written, skipping it.", m_type.Name, member.MemberName); continue; } #endif // find the default value for the member object dvalue = null; if (defaultValue != null) dvalue = defaultValue.Value; if (member.MemberType.IsValueType && dvalue == null) dvalue = Activator.CreateInstance(member.MemberType); if (eqxAttribute != null) { if (!member.MemberType.IsPrimitive && member.MemberType != typeof(string)) throw new InvalidOperationException(string.Format(OnlyPrimitivesXmlAttributes, m_type.Name, member.MemberName)); string name = eqxAttribute.Name ?? member.MemberName; readAttributes += ReadPrimitive(member, string.Concat("@", name), dvalue); writeAttributes += WritePrimitiveAttribute(member, name, dvalue, eqxAttribute.AlwaysWrite); } else if (eqxElement != null) { string name = eqxElement.Name ?? member.MemberName; if (member.MemberType.IsComplex() && member.MemberType != typeof(string)) { readElements += ReadComplex(member, name, dvalue); writeElements += WriteComplexElement(member, name, dvalue, eqxElement.AlwaysWrite); } else { readElements += ReadPrimitive(member, name, dvalue); writeElements += WritePrimitiveElement(member, name, dvalue, eqxElement.AlwaysWrite); } } else if (eqxArray != null) { string name = eqxArray.Name ?? member.MemberName; readElements += ReadArray(member, name, eqxArray.ItemName, dvalue); writeElements += WriteArray(member, name, eqxArray.ItemName, dvalue, eqxArray.AlwaysWrite); } } m_reader = (XPathNavigator navigator, ref object target) => { if (target == null) target = m_dynamicType.CreateInstance(); if (navigator.HasAttributes) readAttributes(navigator, ref target); if (navigator.HasChildren) { readElements(navigator, ref target); readArrays(navigator, ref target); } }; m_writer = (XElement result, ref object target) => { if (target != null) { writeAttributes(result, ref target); writeElements(result, ref target); writeArrays(result, ref target); } }; }
private void WriteDelayed(string file, string message) { WriterDelegate wrtdel = new WriterDelegate( this.WriteToFile ); DelayWriter dw = new DelayWriter( file, message,1000, wrtdel ); Thread t = new Thread( new ThreadStart( dw.Start ) ); t.Name = "DelayedLogWriterThread"; t.IsBackground = false; t.Start(); }
private void Init() { this.writer = new Form1.WriterDelegate(this.Log); form1 = this; }
public Listener(string name, string pipe, CancellationTokenSource tokenSource, WriterDelegate writer = null) { VMName = name; Pipe = pipe; TokenSource = tokenSource; Writer = writer; Task = new Task(() => { string trimmed = Pipe.Substring(2); // trim the leading '\\' const string PipeID = @"\pipe\"; int index = trimmed.IndexOf(PipeID); string pipeServer = trimmed.Substring(0, index); string pipeName = trimmed.Substring(index + PipeID.Length); NamedPipeClientStream pipeStream = new NamedPipeClientStream(pipeServer, pipeName); try { pipeStream.Connect(3000); } catch (Exception) { write("Failed to make connection to pipe: " + Pipe, EventLogEntryType.Error); this.Dispose(); return; } while (!Task.IsCanceled && !TokenSource.IsCancellationRequested) Listen(pipeStream, TokenSource.Token); try{pipeStream.Close();} catch (Exception){} // I don't really care if closing the pipe failed, I just don't want to kill the program. }, TokenSource.Token); Task.Start(); }
public static WriterDelegate GetWriter(Func <Type, WriterDelegate> writersFactory, WriterDelegate baseWriter) { return((object o, bool writeEmpty, IntPtr result, ref int index, WriterContext context) => { Type type = o.GetType(); writersFactory(typeof(string))(type.Name, writeEmpty, result, ref index, context); writersFactory(type)(o, writeEmpty, result, ref index, context); }); }