public AsyncIO(IIoHandler parent, int maxFrameSize, TransportBase transport, bool isInitiator) : base("async-io", transport.Identifier) { Fx.Assert(transport != null, "transport required"); this.ioHandler = parent; this.transport = transport; this.writer = this.transport.RequiresCompleteFrames ? new AsyncFrameWriter(this.transport, parent) : new AsyncWriter(this.transport, parent); this.reader = new AsyncReader(this, maxFrameSize, isInitiator); }
public AsyncIO(IIoHandler parent, int maxFrameSize, int writeQueueFullLimit, int writeQueueEmptyLimit, TransportBase transport, bool isInitiator) : base("async-io", transport.Identifier) { Fx.Assert(transport != null, "transport required"); this.ioHandler = parent; this.transport = transport; this.writer = new AsyncWriter(this.transport, writeQueueFullLimit, writeQueueEmptyLimit, parent); this.reader = new AsyncReader(this, maxFrameSize, isInitiator); }
/// <summary> /// Initializes a new instance of <see cref="AsyncConsoleSink"/>. /// </summary> /// <param name="formatter">Log formatter.</param> /// <param name="renderer">Renderer factory method.</param> public AsyncConsoleSink(ILogFormatter formatter, Func <IDataRenderer> renderer) { Formatter = formatter; this.renderer = renderer; asyncWriter = new AsyncWriter((level, entries) => { System.Console.WriteLine(Formatter.Format(level, entries, renderer())); }); asyncWriter.Start(); }
static void WriteCompleteCallback(TransportAsyncCallbackArgs args) { AsyncWriter thisPtr = (AsyncWriter)args.UserToken; if (!thisPtr.HandleWriteBufferComplete(args)) { return; } thisPtr.ContinueWrite(); }
public AsyncIO(IIoHandler parent, int maxFrameSize, int writeQueueFullLimit, int writeQueueEmptyLimit, TransportBase transport, bool isInitiator) : base("async-io", transport.Identifier) { Fx.Assert(transport != null, "transport required"); this.ioHandler = parent; this.transport = transport; this.writer = this.transport.RequiresCompleteFrames ? new AsyncFrameWriter(this.transport, writeQueueFullLimit, writeQueueEmptyLimit, parent) : new AsyncWriter(this.transport, writeQueueFullLimit, writeQueueEmptyLimit, parent); this.reader = new AsyncReader(this, maxFrameSize, isInitiator); }
public AsyncIO( int bufferSize, TransportBase transport, Action<ByteBuffer> receiveBufferHandler, Action<Exception> faultHandler) { Fx.Assert(transport != null, "transport required"); Fx.Assert(receiveBufferHandler != null, "receiveBufferHandler required"); this.transport = transport; this.faultHandler = faultHandler; this.reader = new AsyncReader(this, bufferSize, receiveBufferHandler); this.writer = new AsyncWriter(this, bufferSize); }
public AsyncIO( int bufferSize, TransportBase transport, Action <ByteBuffer> receiveBufferHandler, Action <Exception> faultHandler) { Fx.Assert(transport != null, "transport required"); Fx.Assert(receiveBufferHandler != null, "receiveBufferHandler required"); this.transport = transport; this.faultHandler = faultHandler; this.reader = new AsyncReader(this, bufferSize, receiveBufferHandler); this.writer = new AsyncWriter(this, bufferSize); }
/// <summary> /// Initializes a new instance of <see cref="AsyncSingleFileSink"/>. /// </summary> /// <param name="formatter">Log formatter.</param> /// <param name="renderer">Renderer factory method.</param> /// <param name="logFilePath">Log file path.</param> /// <param name="encoding">File encoding. The default is UTF8.</param> /// <param name="bufferSize">Buffer size to be used. The default is 4096.</param> public AsyncSingleFileSink(ILogFormatter formatter, Func <IDataRenderer> renderer, string logFilePath, Encoding encoding = null, int bufferSize = 4096) { Formatter = formatter; this.renderer = renderer; sink = new FileSink(Formatter, renderer, logFilePath, encoding, bufferSize); asyncWriter = new AsyncWriter((level, entries) => { sink.Write(level, entries); }); asyncWriter.Start(); }
public void Initialize() { resultPath = Environment.CurrentDirectory + "\\Tests"; aw = new AsyncWriter(resultPath); files = new List <string>(); string pathToFile1 = Environment.CurrentDirectory + "\\..\\..\\..\\TestGeneratorTest.cs"; files.Add(pathToFile1); maxReadableCount = 3; maxProcessableCount = 3; maxWritableCount = 3; testsGenerator = new TestGenerator.TestGenerator(files, maxReadableCount, maxProcessableCount, maxWritableCount); }
static void Main() { List <string> inputFiles = new List <string>(); inputFiles.Add("../../../../Classes/Class1.cs"); inputFiles.Add("../../../../Classes/Classes.cs"); TestGenerator.TestGenerator generator = new TestGenerator.TestGenerator(inputFiles, 2, 2, 2); AsyncWriter asyncWriter = new AsyncWriter("../../../../Tests"); generator.Generate(asyncWriter).Wait(); Console.WriteLine("Generation completed"); Console.ReadKey(); }
/// <summary> /// Initializes a new instance of the <see cref="ExcelOutputWriter"/> class. /// </summary> /// <param name="outFileName">Name of the out file. If null no excel file will be created</param> /// <param name="options">Excel startup options</param> public ExcelOutputWriter(string outFileName, ExcelOptions options) { using (Tracer t = new Tracer(myType, "ExcelOutputWriter")) { using (new USCulture()) { mybCloseOnDispose = ((options & ExcelOptions.CloseOnExit) == ExcelOptions.CloseOnExit); myExcelFileName = outFileName; myExcel.DisplayAlerts = false; myExcel.Visible = ((options & ExcelOptions.Visible) == ExcelOptions.Visible); myWorkbook = myExcel.Workbooks.Add(1); t.Info("CloseOnDispose: {0}, OutFileName: {1}, Visible: {2}", mybCloseOnDispose, outFileName, myExcel.Visible); myWriter = new AsyncWriter <List <string> >(WriteLine); } } }
protected virtual void Dispose(bool isDisposing) { if (myExcel != null) { myWriter.Dispose(); myWriter = null; EnableAutoFilter(); Save(); myWorkbook = null; // Close excel when nothing has been written. if (mybCloseOnDispose || myTotalLinesWritten == 0) { myExcel.Quit(); } myExcel = null; } }
public void Exeption_In_Async_Thread_Is_Marshalled_Back() { AsyncWriter <string> writer = new AsyncWriter <string>((str) => { throw new InvalidOperationException("Test exception"); }); Assert.Throws <TargetInvocationException>(() => { int i = 0; while (true) { writer.Write(i.ToString()); i++; Thread.Sleep(10); } }); Assert.Throws <TargetInvocationException>(() => writer.Dispose()); }
public void TestAllTheThings() { using (var stream = new MemoryStream()) { var writer = new AsyncWriter(stream); var t = CancellationToken.None; writer.Write((Byte)42, t).Wait(); writer.Write((Int32)42, t).Wait(); writer.Write((Int64)42, t).Wait(); writer.Write((UInt32)42, t).Wait(); writer.Write((UInt64)42, t).Wait(); writer.Write(new byte[] { }, t).Wait(); writer.Write(new byte[] { 13, 37 }, t).Wait(); writer.Write("#rekt", t).Wait(); writer.Write("nope.avi", t).Wait(); stream.Position = 0; var reader = new AsyncReader(stream); Assert.AreEqual <Byte>(42, reader.ReadByte(t).Result); Assert.AreEqual <Int32>(42, reader.ReadInt32(t).Result); Assert.AreEqual <Int64>(42, reader.ReadInt64(t).Result); Assert.AreEqual <UInt32>(42, reader.ReadUInt32(t).Result); Assert.AreEqual <UInt64>(42, reader.ReadUInt64(t).Result); Assert.IsTrue(reader.ReadByteArray(t).Result.Length == 0); Assert.IsTrue(new byte[] { 13, 37 }.SequenceEqual(reader.ReadByteArray(t).Result)); Assert.AreEqual <string>("#rekt", reader.ReadString(t).Result); try { reader.ReadByte(t).Wait(); Assert.IsTrue(false, "wtf"); } catch (AggregateException e) { Assert.IsInstanceOfType(e.InnerExceptions.Single(), typeof(ProtocolViolationException)); } } }
public void Dispose_Does_Not_Throw_When_ExceptionProcessing_InProgress() { Exception ex1 = null; Exception ex2 = null; try { using (AsyncWriter <string> writer = new AsyncWriter <string>((str) => { throw new InvalidOperationException("Test exception"); })) { try { while (true) { writer.Write(null); } } catch (Exception ex) { ex1 = ex; throw; } finally { Assert.IsTrue(ExceptionHelper.InException); } } } catch (Exception exx2) { ex2 = exx2; } Assert.IsNotNull(ex1); Assert.IsNotNull(ex2); Assert.IsTrue(Object.ReferenceEquals(ex1, ex2)); }
public void SetCurrentSheet(SheetInfo header) { using (Tracer t = new Tracer(myType, "SetCurrentSheet")) { using (new USCulture()) { if (myCurrentSheet != null) { t.Info("Wait until previous sheet data has been written"); myWriter.Close(); t.Info("Wait finished"); myWriter = new AsyncWriter <List <string> >(this.WriteLine); } lock (this) { if (myCurrentSheet != null) { EnableAutoFilter(); } myCurrentSheetInfo = header; myCurrentSheet = AddSheet(header.SheetName); myRowIndex = 1; for (int i = 0; i < header.Columns.Count; i++) { var colum = header.Columns[i]; Range r = GetCell(myCurrentSheet, i, header.HeaderRow); r.Value2 = colum.Name; r.ColumnWidth = colum.Width; } SetHeaderFont(header); } } } }
/// Execute action public override object Execute() { string args = (GetTransformedValueStr()??string.Empty).Trim(); ShellMode t = this.Mode; if (t == ShellMode.Auto) { if (string.IsNullOrEmpty(Verb)) t = ShellMode.Comspec; else t=ShellMode.ShellExecute; } string outp = Context.TransformStr(OutTo, Transform); string errorp = Context.TransformStr(ErrorTo, Transform); string enc = Context.TransformStr(Encoding, Transform); object input = Context.Transform(Input, Transform); bool redirectError = !string.IsNullOrEmpty(errorp); bool redirectOutput = !string.IsNullOrEmpty(outp); ProcessStartInfo pi = new ProcessStartInfo(); if (!string.IsNullOrEmpty(enc)) pi.StandardOutputEncoding = pi.StandardErrorEncoding = Utils.GetEncoding(enc); pi.CreateNoWindow = CreateNoWindow; pi.WindowStyle = WindowStyle; pi.ErrorDialog = false; pi.WorkingDirectory = Context.TransformStr(Directory, Transform); if (string.IsNullOrEmpty(pi.WorkingDirectory)) pi.WorkingDirectory = Environment.CurrentDirectory; string fileToDelete = null; // do a bit of clean up occasionally by deleting older xsh-batch-*.cmd files if (Utils.GenRandom(0,5)==3) { try { VerboseMessage("Cleaning up older batch files in temp directory"); var dt = DateTime.UtcNow.AddDays(-1); foreach (var file in new DirectoryInfo(Path.GetTempPath()).GetFileSystemInfos("xsh-batch-*.cmd")) { if (file.LastWriteTimeUtc<dt) file.Delete(); } } catch { } } try { switch (t) { case ShellMode.Batch: fileToDelete = Path.Combine(Path.GetTempPath(), "xsh-batch-" +Utils.GenRandom(0, int.MaxValue) + "-" + Utils.GenRandom(0, int.MaxValue) + ".cmd"); File.WriteAllText(fileToDelete, args, System.Text.Encoding.Default); args = Utils.QuoteArg(fileToDelete); if (!Wait) fileToDelete = null; // don't delete the batch if we're not waiting for it to complete goto default; default: string cmd = Utils.QuoteArg(Environment.ExpandEnvironmentVariables("%COMSPEC%")) ; if (!string.IsNullOrEmpty(args)) cmd += " " + args; fillFilenameAndArguments(pi, cmd); pi.Arguments = " /C \"" + pi.Arguments + "\""; pi.UseShellExecute = false; pi.RedirectStandardError = redirectError && Wait; pi.RedirectStandardOutput = redirectOutput && Wait; pi.RedirectStandardInput = (input != null) && Wait; break; case ShellMode.Direct: fillFilenameAndArguments(pi, args); pi.UseShellExecute = false; pi.RedirectStandardError = redirectError && Wait; pi.RedirectStandardOutput = redirectOutput && Wait; pi.RedirectStandardInput = (input != null) && Wait; break; case ShellMode.ShellExecute: pi.UseShellExecute = true; fillFilenameAndArguments(pi, args); if (!string.IsNullOrEmpty(Verb)) pi.Verb = Verb; break; } TimeSpan? ts = null; if (!string.IsNullOrEmpty(Timeout)) ts = Utils.ToTimeSpan(Context.TransformStr(Timeout, Transform)); VerboseMessage("Executing " + Utils.QuoteArg(pi.FileName) + " " + pi.Arguments); if (!string.IsNullOrEmpty(pi.UserName)) { pi.UserName = Context.TransformStr(Username, Transform); var ss = new SecureString(); foreach (var c in (Context.TransformStr(Password, Transform) ?? string.Empty)) ss.AppendChar(c); pi.Password = ss; pi.LoadUserProfile = LoadUserProfile; } using (ManualResetEvent terminated = new ManualResetEvent(false)) using (WaitableTimer timeout = new WaitableTimer(ts)) { ExitedWithContext ect = new ExitedWithContext(terminated); using (Process p = Process.Start(pi)) { if (!string.IsNullOrEmpty(ProcessIdTo)) Context.OutTo(Context.TransformStr(ProcessIdTo, Transform), p.Id); if (Wait && p != null) { Redir[] r = new Redir[2] {new Redir(Context, outp), new Redir(Context, errorp)}; p.Exited += ect.onExited; p.EnableRaisingEvents = true; AsyncWriter asyncWriter = null; try { if (pi.RedirectStandardInput) { byte[] data; if (input is byte[]) data = ((byte[]) input); else { Encoding en = System.Text.Encoding.Default; if (string.IsNullOrEmpty(enc)) en = Utils.GetEncoding(enc); if (en == null) en = System.Text.Encoding.Default; data = en.GetBytes(Utils.To<string>(input)); } asyncWriter = new AsyncWriter(p.StandardInput, data); } if (pi.RedirectStandardOutput) if (BinaryOutput) r[0].StartRedirect(p.StandardOutput.BaseStream); else r[0].StartRedirect(p.StandardOutput.BaseStream, p.StandardOutput.CurrentEncoding); if (pi.RedirectStandardError) r[1].StartRedirect(p.StandardError.BaseStream, p.StandardError.CurrentEncoding); var wh = new WaitHandle[] {r[0].Event, r[1].Event, terminated, timeout.WaitHandle}; do { Context.OnProgress(1); int n = WaitHandle.WaitAny(wh, 500,true); switch (n) { case 0: case 1: r[n].Flush(false); break; case 2: break; // Exit case 3: throw new TimeoutException("Command execution timed out"); } } while (!p.HasExited); // must wait to ensure that all output is flushed p.WaitForExit(); } finally { try { if (!p.HasExited && !p.WaitForExit(1000)) { VerboseMessage("Process didn't terminate as expected. TASKKILL will be used."); Shell sh = new Shell(Utils.BackslashAdd(Environment.GetFolderPath(Environment.SpecialFolder.System)) + "TASKKILL.EXE /T /F /pid " + p.Id); sh.CreateNoWindow = true; sh.Mode = ShellMode.Comspec; sh.IgnoreExitCode = true; Context.InitializeAndExecute(sh); VerboseMessage("TASKKILL completed"); } VerboseMessage("Waiting for process to terminate completely."); p.WaitForExit(); } catch { VerboseMessage("Failed to wait until the process is terminated"); } try { if (!p.HasExited) p.Kill(); } catch { VerboseMessage("Kill failed"); } r[0].Flush(true); r[1].Flush(true); r[0].Dispose(); r[1].Dispose(); terminated.WaitOne(1000, false); // Restore p.Exited -= ect.onExited; } int exitCode = p.ExitCode; if (!string.IsNullOrEmpty(ExitCodeTo)) Context.OutTo(Context.TransformStr(ExitCodeTo, Transform), exitCode); VerboseMessage("Execution completed with exit code={0}", exitCode); if (exitCode != 0 && !IgnoreExitCode) { string a = Utils.QuoteArg(pi.FileName); if (!string.IsNullOrEmpty(pi.Arguments)) { if (!ExtendedErrors) a += " ... arguments ..."; else a += " " + pi.Arguments; } throw new ScriptRuntimeException(string.Format("Command [{0}] failed with exit code = {1}", a, p.ExitCode)); } } } } } finally { if (fileToDelete!=null) { try { File.Delete(fileToDelete); } catch { } } } return null; }
/// Execute action public override object Execute() { string args = (GetTransformedValueStr() ?? string.Empty).Trim(); ShellMode t = this.Mode; if (t == ShellMode.Auto) { if (string.IsNullOrEmpty(Verb)) { t = ShellMode.Comspec; } else { t = ShellMode.ShellExecute; } } string outp = Context.TransformStr(OutTo, Transform); string errorp = Context.TransformStr(ErrorTo, Transform); string enc = Context.TransformStr(Encoding, Transform); object input = Context.Transform(Input, Transform); bool redirectError = !string.IsNullOrEmpty(errorp); bool redirectOutput = !string.IsNullOrEmpty(outp); ProcessStartInfo pi = new ProcessStartInfo(); if (!string.IsNullOrEmpty(enc)) { pi.StandardOutputEncoding = pi.StandardErrorEncoding = Utils.GetEncoding(enc); } pi.CreateNoWindow = CreateNoWindow; pi.WindowStyle = WindowStyle; pi.ErrorDialog = false; pi.WorkingDirectory = Context.TransformStr(Directory, Transform); if (string.IsNullOrEmpty(pi.WorkingDirectory)) { pi.WorkingDirectory = Environment.CurrentDirectory; } string fileToDelete = null; // do a bit of clean up occasionally by deleting older xsh-batch-*.cmd files if (Utils.GenRandom(0, 5) == 3) { try { VerboseMessage("Cleaning up older batch files in temp directory"); var dt = DateTime.UtcNow.AddDays(-1); foreach (var file in new DirectoryInfo(Path.GetTempPath()).GetFileSystemInfos("xsh-batch-*.cmd")) { if (file.LastWriteTimeUtc < dt) { file.Delete(); } } } catch { } } try { switch (t) { case ShellMode.Batch: fileToDelete = Path.Combine(Path.GetTempPath(), "xsh-batch-" + Utils.GenRandom(0, int.MaxValue) + "-" + Utils.GenRandom(0, int.MaxValue) + ".cmd"); File.WriteAllText(fileToDelete, args, System.Text.Encoding.Default); args = Utils.QuoteArg(fileToDelete); if (!Wait) { fileToDelete = null; // don't delete the batch if we're not waiting for it to complete } goto default; default: string cmd = Utils.QuoteArg(Environment.ExpandEnvironmentVariables("%COMSPEC%")); if (!string.IsNullOrEmpty(args)) { cmd += " " + args; } fillFilenameAndArguments(pi, cmd); pi.Arguments = " /C \"" + pi.Arguments + "\""; pi.UseShellExecute = false; pi.RedirectStandardError = redirectError && Wait; pi.RedirectStandardOutput = redirectOutput && Wait; pi.RedirectStandardInput = (input != null) && Wait; break; case ShellMode.Direct: fillFilenameAndArguments(pi, args); pi.UseShellExecute = false; pi.RedirectStandardError = redirectError && Wait; pi.RedirectStandardOutput = redirectOutput && Wait; pi.RedirectStandardInput = (input != null) && Wait; break; case ShellMode.ShellExecute: pi.UseShellExecute = true; fillFilenameAndArguments(pi, args); if (!string.IsNullOrEmpty(Verb)) { pi.Verb = Verb; } break; } TimeSpan?ts = null; if (!string.IsNullOrEmpty(Timeout)) { ts = Utils.ToTimeSpan(Context.TransformStr(Timeout, Transform)); } VerboseMessage("Executing " + Utils.QuoteArg(pi.FileName) + " " + pi.Arguments); if (!string.IsNullOrEmpty(pi.UserName)) { pi.UserName = Context.TransformStr(Username, Transform); var ss = new SecureString(); foreach (var c in (Context.TransformStr(Password, Transform) ?? string.Empty)) { ss.AppendChar(c); } pi.Password = ss; pi.LoadUserProfile = LoadUserProfile; } using (ManualResetEvent terminated = new ManualResetEvent(false)) using (WaitableTimer timeout = new WaitableTimer(ts)) { ExitedWithContext ect = new ExitedWithContext(terminated); using (Process p = Process.Start(pi)) { if (!string.IsNullOrEmpty(ProcessIdTo)) { Context.OutTo(Context.TransformStr(ProcessIdTo, Transform), p.Id); } if (Wait && p != null) { Redir[] r = new Redir[2] { new Redir(Context, outp), new Redir(Context, errorp) }; p.Exited += ect.onExited; p.EnableRaisingEvents = true; AsyncWriter asyncWriter = null; try { if (pi.RedirectStandardInput) { byte[] data; if (input is byte[]) { data = ((byte[])input); } else { Encoding en = System.Text.Encoding.Default; if (string.IsNullOrEmpty(enc)) { en = Utils.GetEncoding(enc); } if (en == null) { en = System.Text.Encoding.Default; } data = en.GetBytes(Utils.To <string>(input)); } asyncWriter = new AsyncWriter(p.StandardInput, data); } if (pi.RedirectStandardOutput) { if (BinaryOutput) { r[0].StartRedirect(p.StandardOutput.BaseStream); } else { r[0].StartRedirect(p.StandardOutput.BaseStream, p.StandardOutput.CurrentEncoding); } } if (pi.RedirectStandardError) { r[1].StartRedirect(p.StandardError.BaseStream, p.StandardError.CurrentEncoding); } var wh = new WaitHandle[] { r[0].Event, r[1].Event, terminated, timeout.WaitHandle }; do { Context.OnProgress(1); int n = WaitHandle.WaitAny(wh, 500, true); switch (n) { case 0: case 1: r[n].Flush(false); break; case 2: break; // Exit case 3: throw new TimeoutException("Command execution timed out"); } } while (!p.HasExited); // must wait to ensure that all output is flushed p.WaitForExit(); } finally { try { if (!p.HasExited && !p.WaitForExit(1000)) { VerboseMessage("Process didn't terminate as expected. TASKKILL will be used."); Shell sh = new Shell(Utils.BackslashAdd(Environment.GetFolderPath(Environment.SpecialFolder.System)) + "TASKKILL.EXE /T /F /pid " + p.Id); sh.CreateNoWindow = true; sh.Mode = ShellMode.Comspec; sh.IgnoreExitCode = true; Context.InitializeAndExecute(sh); VerboseMessage("TASKKILL completed"); } VerboseMessage("Waiting for process to terminate completely."); p.WaitForExit(); } catch { VerboseMessage("Failed to wait until the process is terminated"); } try { if (!p.HasExited) { p.Kill(); } } catch { VerboseMessage("Kill failed"); } r[0].Flush(true); r[1].Flush(true); r[0].Dispose(); r[1].Dispose(); terminated.WaitOne(1000, false); // Restore p.Exited -= ect.onExited; } int exitCode = p.ExitCode; if (!string.IsNullOrEmpty(ExitCodeTo)) { Context.OutTo(Context.TransformStr(ExitCodeTo, Transform), exitCode); } VerboseMessage("Execution completed with exit code={0}", exitCode); if (exitCode != 0 && !IgnoreExitCode) { string a = Utils.QuoteArg(pi.FileName); if (!string.IsNullOrEmpty(pi.Arguments)) { if (!ExtendedErrors) { a += " ... arguments ..."; } else { a += " " + pi.Arguments; } } throw new ScriptRuntimeException(string.Format("Command [{0}] failed with exit code = {1}", a, p.ExitCode)); } } } } } finally { if (fileToDelete != null) { try { File.Delete(fileToDelete); } catch { } } } return(null); }
public async void Test() { _databaseConnection.Connect(); ///////////////////////////////////// // OPERATIONAL, CONTEXUAL SCOPE... // ///////////////////////////////////// // create a Writer to write to the database IWriter writer = new Writer(_databaseConnection); // create a Reader to read from the database IReader reader = new Reader(_databaseConnection); // create an Updater to update the database IUpdater updater = new Updater(_databaseConnection); Entry exampleMongoDBEntry = new Entry(); exampleMongoDBEntry.Message = "Hello"; // write the object to the "MyFirstCollection" Collection that exists within the // previously referenced "MyFirstDatabase" that was used to create the "writer" object writer.Write<Entry>("MyFirstCollection", exampleMongoDBEntry); IEnumerable<Entry> readEntrys = reader.Read<Entry>("MyFirstCollection", // within this collection... "Message",// for the object field "Description" "Hello");// return matches for 'Hello' Assert.AreEqual(1, readEntrys.Count()); //////////////////////////////////// // AND ASYNCHRONOUS OPERATIONS... // //////////////////////////////////// // read, write and update asynchronously using System.Threading.Task IAsyncReader asyncReader = new AsyncReader(reader); readEntrys = await asyncReader.ReadAsync<Entry>("MyFirstCollection", "Message", "Hello"); Assert.AreEqual(1, readEntrys.Count()); IAsyncWriter asyncWriter = new AsyncWriter(writer); IAsyncUpdater asyncUpdater = new AsyncUpdater(updater); // or delegate call backs IAsyncDelegateReader asyncDelegateReader = new AsyncDelegateReader(reader); asyncDelegateReader.AsyncReadCompleted += new ReadCompletedEvent(readerCallBack); asyncDelegateReader.ReadAsync<Entry>("MyFirstCollection", "Message", "Hello"); _readerAutoResetEvent.WaitOne(); Assert.AreEqual(1, _asyncReadResults.Count()); IAsyncDelegateWriter asyncDelegateWriter = new AsyncDelegateWriter(writer); IAsyncDelegateUpdater asyncDelegateUpdater = new AsyncDelegateUpdater(updater); ///////////////////////////////////////////// // FOR A SERVER, DATABASE OR COLLECTION... // ///////////////////////////////////////////// // get a little higher level with the EasyMongo.Database namespace to target a database for operations IDatabaseReader databaseReader = new DatabaseReader(reader, asyncReader); IDatabaseWriter databaseWriter = new DatabaseWriter(writer, asyncWriter); IDatabaseUpdater databaseUpdater = new DatabaseUpdater(updater, asyncUpdater); // or a little lower level with the EasyMongo.Collection namespace to target a specific Collection ICollectionReader collectionReader = new CollectionReader(databaseReader, "MyFirstCollection"); ICollectionWriter collectionWriter = new CollectionWriter(databaseWriter, "MyFirstCollection"); ICollectionUpdater collectionUpdater = new CollectionUpdater(databaseUpdater, "MyFirstCollection"); /////////////////////////////////////////////// // TO RESTRICT CLIENT SCOPE (LAW OF DEMETER) // /////////////////////////////////////////////// // operate only against "MyFirstDatabase"'s "MySecondCollection" readEntrys = collectionReader.Read<Entry>("Message", "Hello"); Assert.AreEqual(1, readEntrys.Count()); ///////////////////// // GENERIC CLASSES // ///////////////////// // Instead of defining generic type arguments at the method level, // you can do it once at the class declaration IWriter<Entry> writerT = new Writer<Entry>(writer); writerT.Write("MySecondCollection", new Entry() { Message = "Goodbye World (Generically)" }); /////////////////////////////// // SIMPLIFY CREATION VIA IoC // /////////////////////////////// // because EasyMongo is a componentized framework built with blocks of functionality, EasyMongo // works great with DI containers and Inversion of Control. // here's an example of using the nuget Ninject extension to load EasyMongo mappings and a conn // string from configuration Ninject.IKernel kernel = new Ninject.StandardKernel(); ICollectionUpdater<Entry> collectionUpdaterT = kernel.TryGet<ICollectionUpdater<Entry>>(); // the alternative to this would be: IServerConnection serverConn = new ServerConnection(LOCAL_MONGO_SERVER_CONNECTION_STRING); IDatabaseConnection databaseConnn = new DatabaseConnection(serverConn, "MyFirstDatabase"); IDatabaseUpdater databaseUpdatr = new DatabaseUpdater(updater, asyncUpdater); ICollectionUpdater collectionUpdaterTheHardWay = new CollectionUpdater(databaseUpdater, "MySecondCollection"); ///////////////////////// // SIMPLE QUERIES... // ///////////////////////// databaseReader.Read<Entry>("MyFirstCollection", "Message", "Hello"); readEntrys = await databaseReader.ReadAsync<Entry>("MyFirstCollection", "Message", "Hello"); Assert.AreEqual(1, readEntrys.Count()); ///////////////////////// // POWERFUL QUERIES... // ///////////////////////// // when more robust querying is needed leverage power of underlying MongoDB driver IMongoQuery IMongoQuery query1 = Query.Matches("Message", new BsonRegularExpression("HE", "i")); IEnumerable<Entry> queryResults = reader.Execute<Entry>("MyFirstCollection", query1); Assert.AreEqual(1, queryResults.Count()); Assert.AreEqual("Hello", queryResults.ElementAt(0).Message); ////////////////////// // AND COMBINATIONS // ////////////////////// Entry exampleMongoDBEntry2 = new Entry(); exampleMongoDBEntry2.Message = "Hello Again"; Entry exampleMongoDBEntry3 = new Entry(); exampleMongoDBEntry3.Message = "Goodbye"; writer.Write<Entry>("MyFirstCollection", exampleMongoDBEntry2); writer.Write<Entry>("MyFirstCollection", exampleMongoDBEntry3); // "AND" multiple IMongoQueries... IMongoQuery query2 = Query.Matches("Message", new BsonRegularExpression("Again")); queryResults = reader.ExecuteAnds<Entry>("MyFirstCollection", new []{ query1, query2}); Assert.AreEqual(1, queryResults.Count()); Assert.AreEqual("Hello Again", queryResults.ElementAt(0).Message); // "OR" multiple IMongoQueries... IMongoQuery query3 = Query.Matches("Message", new BsonRegularExpression("Goo")); queryResults = reader.ExecuteOrs<Entry>("MyFirstCollection", new[] { query1, query2, query3 }); Assert.AreEqual(3, queryResults.Count()); Assert.AreEqual("Hello", queryResults.ElementAt(0).Message); Assert.AreEqual("Hello Again", queryResults.ElementAt(1).Message); Assert.AreEqual("Goodbye", queryResults.ElementAt(2).Message); }
public async void Test() { _databaseConnection.Connect(); ///////////////////////////////////// // OPERATIONAL, CONTEXUAL SCOPE... // ///////////////////////////////////// // create a Writer to write to the database IWriter writer = new Writer(_databaseConnection); // create a Reader to read from the database IReader reader = new Reader(_databaseConnection); // create an Updater to update the database IUpdater updater = new Updater(_databaseConnection); Entry exampleMongoDBEntry = new Entry(); exampleMongoDBEntry.Message = "Hello"; // write the object to the "MyFirstCollection" Collection that exists within the // previously referenced "MyFirstDatabase" that was used to create the "writer" object writer.Write <Entry>("MyFirstCollection", exampleMongoDBEntry); IEnumerable <Entry> readEntrys = reader.Read <Entry>("MyFirstCollection", // within this collection... "Message", // for the object field "Description" "Hello"); // return matches for 'Hello' Assert.AreEqual(1, readEntrys.Count()); //////////////////////////////////// // AND ASYNCHRONOUS OPERATIONS... // //////////////////////////////////// // read, write and update asynchronously using System.Threading.Task IAsyncReader asyncReader = new AsyncReader(reader); readEntrys = await asyncReader.ReadAsync <Entry>("MyFirstCollection", "Message", "Hello"); Assert.AreEqual(1, readEntrys.Count()); IAsyncWriter asyncWriter = new AsyncWriter(writer); IAsyncUpdater asyncUpdater = new AsyncUpdater(updater); // or delegate call backs IAsyncDelegateReader asyncDelegateReader = new AsyncDelegateReader(reader); asyncDelegateReader.AsyncReadCompleted += new ReadCompletedEvent(readerCallBack); asyncDelegateReader.ReadAsync <Entry>("MyFirstCollection", "Message", "Hello"); _readerAutoResetEvent.WaitOne(); Assert.AreEqual(1, _asyncReadResults.Count()); IAsyncDelegateWriter asyncDelegateWriter = new AsyncDelegateWriter(writer); IAsyncDelegateUpdater asyncDelegateUpdater = new AsyncDelegateUpdater(updater); ///////////////////////////////////////////// // FOR A SERVER, DATABASE OR COLLECTION... // ///////////////////////////////////////////// // get a little higher level with the EasyMongo.Database namespace to target a database for operations IDatabaseReader databaseReader = new DatabaseReader(reader, asyncReader); IDatabaseWriter databaseWriter = new DatabaseWriter(writer, asyncWriter); IDatabaseUpdater databaseUpdater = new DatabaseUpdater(updater, asyncUpdater); // or a little lower level with the EasyMongo.Collection namespace to target a specific Collection ICollectionReader collectionReader = new CollectionReader(databaseReader, "MyFirstCollection"); ICollectionWriter collectionWriter = new CollectionWriter(databaseWriter, "MyFirstCollection"); ICollectionUpdater collectionUpdater = new CollectionUpdater(databaseUpdater, "MyFirstCollection"); /////////////////////////////////////////////// // TO RESTRICT CLIENT SCOPE (LAW OF DEMETER) // /////////////////////////////////////////////// // operate only against "MyFirstDatabase"'s "MySecondCollection" readEntrys = collectionReader.Read <Entry>("Message", "Hello"); Assert.AreEqual(1, readEntrys.Count()); ///////////////////// // GENERIC CLASSES // ///////////////////// // Instead of defining generic type arguments at the method level, // you can do it once at the class declaration IWriter <Entry> writerT = new Writer <Entry>(writer); writerT.Write("MySecondCollection", new Entry() { Message = "Goodbye World (Generically)" }); /////////////////////////////// // SIMPLIFY CREATION VIA IoC // /////////////////////////////// // because EasyMongo is a componentized framework built with blocks of functionality, EasyMongo // works great with DI containers and Inversion of Control. // here's an example of using the nuget Ninject extension to load EasyMongo mappings and a conn // string from configuration Ninject.IKernel kernel = new Ninject.StandardKernel(); ICollectionUpdater <Entry> collectionUpdaterT = kernel.TryGet <ICollectionUpdater <Entry> >(); // the alternative to this would be: IServerConnection serverConn = new ServerConnection(LOCAL_MONGO_SERVER_CONNECTION_STRING); IDatabaseConnection databaseConnn = new DatabaseConnection(serverConn, "MyFirstDatabase"); IDatabaseUpdater databaseUpdatr = new DatabaseUpdater(updater, asyncUpdater); ICollectionUpdater collectionUpdaterTheHardWay = new CollectionUpdater(databaseUpdater, "MySecondCollection"); ///////////////////////// // SIMPLE QUERIES... // ///////////////////////// databaseReader.Read <Entry>("MyFirstCollection", "Message", "Hello"); readEntrys = await databaseReader.ReadAsync <Entry>("MyFirstCollection", "Message", "Hello"); Assert.AreEqual(1, readEntrys.Count()); ///////////////////////// // POWERFUL QUERIES... // ///////////////////////// // when more robust querying is needed leverage power of underlying MongoDB driver IMongoQuery IMongoQuery query1 = Query.Matches("Message", new BsonRegularExpression("HE", "i")); IEnumerable <Entry> queryResults = reader.Execute <Entry>("MyFirstCollection", query1); Assert.AreEqual(1, queryResults.Count()); Assert.AreEqual("Hello", queryResults.ElementAt(0).Message); ////////////////////// // AND COMBINATIONS // ////////////////////// Entry exampleMongoDBEntry2 = new Entry(); exampleMongoDBEntry2.Message = "Hello Again"; Entry exampleMongoDBEntry3 = new Entry(); exampleMongoDBEntry3.Message = "Goodbye"; writer.Write <Entry>("MyFirstCollection", exampleMongoDBEntry2); writer.Write <Entry>("MyFirstCollection", exampleMongoDBEntry3); // "AND" multiple IMongoQueries... IMongoQuery query2 = Query.Matches("Message", new BsonRegularExpression("Again")); queryResults = reader.ExecuteAnds <Entry>("MyFirstCollection", new [] { query1, query2 }); Assert.AreEqual(1, queryResults.Count()); Assert.AreEqual("Hello Again", queryResults.ElementAt(0).Message); // "OR" multiple IMongoQueries... IMongoQuery query3 = Query.Matches("Message", new BsonRegularExpression("Goo")); queryResults = reader.ExecuteOrs <Entry>("MyFirstCollection", new[] { query1, query2, query3 }); Assert.AreEqual(3, queryResults.Count()); Assert.AreEqual("Hello", queryResults.ElementAt(0).Message); Assert.AreEqual("Hello Again", queryResults.ElementAt(1).Message); Assert.AreEqual("Goodbye", queryResults.ElementAt(2).Message); }
public SIMONDataManager() { AsyncRead = new AsyncReader(Read); AsyncWrite = new AsyncWriter(Write); }
public static void onSave(WorldSaveEventArgs e) { System.Console.WriteLine("Saving Jailings"); if (!Directory.Exists(jailDirectory)) Directory.CreateDirectory(jailDirectory); GenericWriter idxWriter; GenericWriter binWriter; long tPos; /*if (World.SaveType == 0) { idxWriter = new BinaryFileWriter(idxPath, false); binWriter = new BinaryFileWriter(binPath, true); } else {*/ idxWriter = new AsyncWriter(idxPath, false); binWriter = new AsyncWriter(binPath, true); //} idxWriter.Write((int)m_jailings.Count); try { foreach (JailSystem tJail in m_jailings.Values) { tPos = binWriter.Position; idxWriter.Write((int)0); idxWriter.Write((int)tJail.ID); idxWriter.Write((long)tPos); try { tJail.Serialize((GenericWriter)binWriter); } catch (Exception err) { System.Console.WriteLine("{0}, {1} serialize", err.Message, err.TargetSite); } idxWriter.Write((int)(binWriter.Position - tPos)); } saveingameeditsettings((GenericWriter)binWriter); } catch (Exception er) { System.Console.WriteLine("{0}, {1}", er.Message, er.TargetSite); } finally { } idxWriter.Close(); binWriter.Close(); System.Console.WriteLine("Jailings Saved"); }