public void DoTests() { int hr; bool b = false; bool b2; IFileSourceFilter fsf; IBaseFilter ibf = new AsyncReader() as IBaseFilter; fsf = ibf as IFileSourceFilter; hr = fsf.Load(@"C:\Users\Public\Recorded TV\Sample Media\win7_scenic-demoshort_raw.wtv", null); IPin ppin = DsFindPin.ByDirection(ibf, PinDirection.Output, 0); m_pi = ppin as IAMAsyncReaderTimestampScaling; hr = m_pi.SetTimestampMode(b); DsError.ThrowExceptionForHR(hr); hr = m_pi.GetTimestampMode(out b2); DsError.ThrowExceptionForHR(hr); Debug.Assert(b == b2); hr = m_pi.SetTimestampMode(!b); DsError.ThrowExceptionForHR(hr); hr = m_pi.GetTimestampMode(out b2); DsError.ThrowExceptionForHR(hr); Debug.Assert(!b == b2); }
public void ReadAsync(String filename, ReadCompleted rc, ReadFailed rf /*callback*/) { //AsyncReader-Objekt mit korrekten Parametern erzeugen AsyncReader myReader = new AsyncReader(filename, rc, rf); //Worker-Thread starten, welcher doRead ausführt new System.Threading.Thread(new System.Threading.ThreadStart(myReader.doRead)).Start(); }
private void Setup() { IFileSourceFilter ifsf = new AsyncReader() as IFileSourceFilter; int hr = ifsf.Load("foo.avi", null); IPin pPin = DsFindPin.ByDirection((IBaseFilter)ifsf, PinDirection.Output, 0); m_iar = pPin as IAsyncReader; }
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 void Initialize() { path = Environment.CurrentDirectory + "\\..\\..\\..\\TemplateGeneratorTest.cs"; ar = new AsyncReader(); code = ar.Read(path).Result; generator = new TemplateGenerator(); root = CSharpSyntaxTree.ParseText(code).GetRoot(); }
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); }
private IFilterGraph2 BuildGraph(string sFileName) { int hr; IBaseFilter ibfRenderer = null; IBaseFilter ibfAVISource = null; IPin IPinIn = null; IPin IPinOut = null; IFilterGraph2 graphBuilder = new FilterGraph() as IFilterGraph2; m_dsrot = new DsROTEntry(graphBuilder); try { // Get the file source filter ibfAVISource = new AsyncReader() as IBaseFilter; // Add it to the graph hr = graphBuilder.AddFilter(ibfAVISource, "Ds.NET AsyncReader"); Marshal.ThrowExceptionForHR(hr); // Set the file name IFileSourceFilter fsf = ibfAVISource as IFileSourceFilter; hr = fsf.Load(sFileName, null); Marshal.ThrowExceptionForHR(hr); IPinOut = DsFindPin.ByDirection(ibfAVISource, PinDirection.Output, 0); // Get the default video renderer ibfRenderer = (IBaseFilter) new VideoRendererDefault(); // Add it to the graph hr = graphBuilder.AddFilter(ibfRenderer, "Ds.NET VideoRendererDefault"); Marshal.ThrowExceptionForHR(hr); IPinIn = DsFindPin.ByDirection(ibfRenderer, PinDirection.Input, 0); hr = graphBuilder.Connect(IPinOut, IPinIn); Marshal.ThrowExceptionForHR(hr); } catch { Marshal.ReleaseComObject(graphBuilder); throw; } finally { Marshal.ReleaseComObject(ibfAVISource); Marshal.ReleaseComObject(ibfRenderer); Marshal.ReleaseComObject(IPinIn); Marshal.ReleaseComObject(IPinOut); } return(graphBuilder); }
public void Initialize() { path = Environment.CurrentDirectory + "\\..\\..\\..\\CodeAnalyzerTest.cs"; ar = new AsyncReader(); string sourceCode = ar.Read(path).Result; analyzer = new CodeAnalyzer(); classes = analyzer.Parse(sourceCode); root = CSharpSyntaxTree.ParseText(sourceCode).GetRoot(); }
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); }
protected virtual void Dispose(bool dispose) { if (dispose && _dataReady != null) { if (_reader != null) { _reader.Dispose(); } _dataReady.Close(); } _dataReady = null; _reader = null; }
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); }
private string GetPygmentizeResult(string code, Language language) { var lexer = language.GetAttribute <LexerAttribute>().lexer; var arguments = lexer == null ? "-g" : $"-l {lexer}"; arguments += " -f tokens -O encoding=utf-8"; var sw = Stopwatch.StartNew(); using (var process = BuildProcess(arguments)) { process.Start(); const int limit = 10 * 1024 * 1024; var utf8StandardErrorReader = new StreamReader(process.StandardError.BaseStream, Encoding.UTF8); var utf8StandardOutputReader = new StreamReader(process.StandardOutput.BaseStream, Encoding.UTF8); var readErrTask = new AsyncReader(utf8StandardErrorReader, limit).GetDataAsync(); var readOutTask = new AsyncReader(utf8StandardOutputReader, limit).GetDataAsync(); process.StandardInput.BaseStream.Write(Encoding.UTF8.GetBytes(code)); process.StandardInput.BaseStream.Close(); var isFinished = Task.WaitAll(new Task[] { readErrTask, readOutTask }, 1000); var ms = sw.ElapsedMilliseconds; if (!process.HasExited) { Shutdown(process); } if (readErrTask.Result.Length > 0) { log.Warn($"pygmentize написал на stderr: {readErrTask.Result}"); } if (!isFinished) { log.Warn($"Не хватило времени ({ms} ms) на работу pygmentize"); } else { log.Info($"pygmentize закончил работу за {ms} ms"); } if (process.ExitCode != 0) { log.Info($"pygmentize завершился с кодом {process.ExitCode}"); } return(isFinished && readErrTask.Result.Length == 0 && readOutTask.Result.Length > 0 ? readOutTask.Result : null); } }
private void Load() { string metaString = File.ReadAllText(MetaFilePath); MetaData meta = MetaData.Parse(metaString); _texture = new Texture2D(meta.width, meta.height, meta.format, false); AsyncReader asyncReader = new AsyncReader(_texture, _ => { Debug.Log("Done"); }); asyncReader.Load(FilePath); }
static void Main() { Stopwatch stopWatch = Stopwatch.StartNew(); AsyncReader asyncReader = new AsyncReader(filePath); asyncReader.MainAsync().GetAwaiter().GetResult(); stopWatch.Stop(); string resultAsync = ($"{stopWatch.Elapsed}"); stopWatch.Start(); SyncReader syncReader = new SyncReader(filePath); syncReader.MainSync(); stopWatch.Stop(); string resultSync = ($"{stopWatch.Elapsed}"); Console.WriteLine($"\nAsync \t\t {resultAsync}\nSync \t\t {resultSync}"); }
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)); } } }
private static void SyncAsync() { Console.WriteLine("Sync"); var frs = new Hashtable().Fill(collection => { using (StreamReader streamReader = new StreamReader(FILE_NAME)) { while (!streamReader.EndOfStream) { string line = streamReader.ReadLine(); Int32 code = line.GetHashCode(); Object prevValue = collection[code]; collection[code] = prevValue == null ? 1 : (Int32)prevValue + 1; // unbox } } }); Console.WriteLine("Async"); GC.Collect(); var beforeMemoryUsage = GC.GetTotalMemory(true); var watch = new Stopwatch(); watch.Start(); var reader = new AsyncReader(FILE_NAME); var ht = reader.ReadToHashtable(); watch.Stop(); Console.WriteLine("Memory usage - {0}", GC.GetTotalMemory(true) - beforeMemoryUsage); Console.WriteLine("Parce time - {0}", watch.ElapsedMilliseconds); Console.ReadLine(); }
public void StartRedirect(Stream stream, Encoding encoding) { _binary = false; _reader = new AsyncReader(stream, encoding, dataReceiver); }
public void TestConnectDisconnectConnectedToConnectionMediaType() { int hr; IBaseFilter aviSplitter = null; IBaseFilter ibfAVISource = null; IPin pinIn = null; IPin pinOut = null; IFilterGraph2 graphBuilder = new FilterGraph() as IFilterGraph2; try { ibfAVISource = new AsyncReader() as IBaseFilter; // Add it to the graph hr = graphBuilder.AddFilter(ibfAVISource, "Ds.NET AsyncReader"); Marshal.ThrowExceptionForHR(hr); // Set the file name IFileSourceFilter fsf = ibfAVISource as IFileSourceFilter; hr = fsf.Load(@"foo.avi", null); Marshal.ThrowExceptionForHR(hr); pinOut = DsFindPin.ByDirection(ibfAVISource, PinDirection.Output, 0); // Get the avi splitter aviSplitter = (IBaseFilter) new AviSplitter(); // Add it to the graph hr = graphBuilder.AddFilter(aviSplitter, "Ds.NET AviSplitter"); Marshal.ThrowExceptionForHR(hr); pinIn = DsFindPin.ByDirection(aviSplitter, PinDirection.Input, 0); Assert.IsNotNull(pinOut); Assert.IsNotNull(pinIn); // Test Connect hr = pinOut.Connect(pinIn, null); Marshal.ThrowExceptionForHR(hr); // Test ConnectedTo IPin pinConnect; hr = pinOut.ConnectedTo(out pinConnect); Marshal.ThrowExceptionForHR(hr); Assert.AreEqual(pinIn, pinConnect); // Test ConnectionMediaType AMMediaType mediaType = new AMMediaType(); hr = pinIn.ConnectionMediaType(mediaType); Marshal.ThrowExceptionForHR(hr); Assert.IsNotNull(mediaType); Assert.IsNotNull(mediaType.majorType); // Test Disconnect hr = pinOut.Disconnect(); Marshal.ThrowExceptionForHR(hr); } finally { Marshal.ReleaseComObject(graphBuilder); } }
private IFilterGraph2 BuildGraph(string sFileName) { int hr; IBaseFilter ibfRenderer = null; IBaseFilter ibfAVISource = null; IPin IPinIn = null; IPin IPinOut = null; IPin iSampleIn = null; IPin iSampleOut = null; SampleGrabber sg = null; IFilterGraph2 graphBuilder = new FilterGraph() as IFilterGraph2; try { // Get the file source filter ibfAVISource = new AsyncReader() as IBaseFilter; // Add it to the graph hr = graphBuilder.AddFilter(ibfAVISource, "Ds.NET AsyncReader"); Marshal.ThrowExceptionForHR(hr); // Set the file name IFileSourceFilter fsf = ibfAVISource as IFileSourceFilter; hr = fsf.Load(sFileName, null); Marshal.ThrowExceptionForHR(hr); IPinOut = DsFindPin.ByDirection(ibfAVISource, PinDirection.Output, 0); // Get a SampleGrabber sg = new SampleGrabber(); IBaseFilter grabFilt = sg as IBaseFilter; ISampleGrabber isg = sg as ISampleGrabber; // Add the sample grabber to the graph hr = graphBuilder.AddFilter(grabFilt, "Ds.NET SampleGrabber"); Marshal.ThrowExceptionForHR(hr); iSampleIn = DsFindPin.ByDirection(grabFilt, PinDirection.Input, 0); iSampleOut = DsFindPin.ByDirection(grabFilt, PinDirection.Output, 0); // Get the default video renderer ibfRenderer = (IBaseFilter) new VideoRendererDefault(); // Add it to the graph hr = graphBuilder.AddFilter(ibfRenderer, "Ds.NET VideoRendererDefault"); Marshal.ThrowExceptionForHR(hr); IPinIn = DsFindPin.ByDirection(ibfRenderer, PinDirection.Input, 0); // Connect the file to the sample grabber hr = graphBuilder.Connect(IPinOut, iSampleIn); Marshal.ThrowExceptionForHR(hr); // Connect the sample grabber to the renderer hr = graphBuilder.Connect(iSampleOut, IPinIn); Marshal.ThrowExceptionForHR(hr); // Configure the sample grabber ConfigureSampleGrabber(isg); // Grab a copy of the mediatype being used. Needed // in one of the tests m_MediaType = new AMMediaType(); hr = IPinOut.ConnectionMediaType(m_MediaType); Marshal.ThrowExceptionForHR(hr); } catch { Marshal.ReleaseComObject(graphBuilder); throw; } finally { Marshal.ReleaseComObject(ibfRenderer); Marshal.ReleaseComObject(ibfAVISource); Marshal.ReleaseComObject(IPinIn); Marshal.ReleaseComObject(IPinOut); Marshal.ReleaseComObject(iSampleIn); Marshal.ReleaseComObject(iSampleOut); Marshal.ReleaseComObject(sg); } return(graphBuilder); }
private IFilterGraph2 BuildGraph(string sFileName) { int hr; IBaseFilter ibfRenderer = null; IBaseFilter ibfAVISource = null; IPin IPinIn = null; IPin IPinOut = null; IPin iSampleIn = null; IPin iSampleOut = null; SampleGrabber sg = null; IFilterGraph2 graphBuilder = new FilterGraph() as IFilterGraph2; try { // Get the file source filter ibfAVISource = new AsyncReader() as IBaseFilter; // Add it to the graph hr = graphBuilder.AddFilter(ibfAVISource, "Ds.NET AsyncReader"); Marshal.ThrowExceptionForHR(hr); // Set the file name IFileSourceFilter fsf = ibfAVISource as IFileSourceFilter; hr = fsf.Load(sFileName, null); Marshal.ThrowExceptionForHR(hr); IPinOut = DsFindPin.ByDirection(ibfAVISource, PinDirection.Output, 0); // Get a SampleGrabber sg = new SampleGrabber(); IBaseFilter grabFilt = sg as IBaseFilter; m_isg = sg as ISampleGrabber; // Set the media type to Video/RBG24 AMMediaType media; media = new AMMediaType(); media.majorType = MediaType.Video; media.subType = MediaSubType.RGB24; media.formatType = FormatType.VideoInfo; hr = m_isg.SetMediaType(media); Marshal.ThrowExceptionForHR(hr); // Add the sample grabber to the graph hr = graphBuilder.AddFilter(grabFilt, "Ds.NET SampleGrabber"); Marshal.ThrowExceptionForHR(hr); iSampleIn = DsFindPin.ByDirection(grabFilt, PinDirection.Input, 0); iSampleOut = DsFindPin.ByDirection(grabFilt, PinDirection.Output, 0); // Get the default video renderer ibfRenderer = (IBaseFilter) new VideoRendererDefault(); // Add it to the graph hr = graphBuilder.AddFilter(ibfRenderer, "Ds.NET VideoRendererDefault"); Marshal.ThrowExceptionForHR(hr); IPinIn = DsFindPin.ByDirection(ibfRenderer, PinDirection.Input, 0); // Connect the file to the sample grabber hr = graphBuilder.Connect(IPinOut, iSampleIn); Marshal.ThrowExceptionForHR(hr); // Connect the sample grabber to the renderer hr = graphBuilder.Connect(iSampleOut, IPinIn); Marshal.ThrowExceptionForHR(hr); } catch { Marshal.ReleaseComObject(graphBuilder); throw; } finally { Marshal.ReleaseComObject(ibfRenderer); Marshal.ReleaseComObject(ibfAVISource); Marshal.ReleaseComObject(IPinIn); Marshal.ReleaseComObject(IPinOut); Marshal.ReleaseComObject(iSampleIn); Marshal.ReleaseComObject(iSampleOut); } return(graphBuilder); }
protected virtual void Dispose(bool dispose) { if (dispose && _dataReady!=null) { if (_reader != null) _reader.Dispose(); _dataReady.Close(); } _dataReady = null; _reader = null; }
public void StartRedirect(Stream stream) { _binary = true; _reader = new AsyncReader(stream, binaryReceiver); }
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 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); }