public void Typical () { using (var ms = new MemoryStream ()) using (var sw = new StreamWriter (ms)) { XDocument doc; XmlNamespaceManager namespaceManager; using (var stream = AssemblyExtensions.OpenScopedResourceStream<Program> ("Template.cxml")) using (var reader = XmlReader.Create (stream)) { doc = XDocument.Load (reader); namespaceManager = new XmlNamespaceManager (reader.NameTable); namespaceManager.AddNamespace ("c", Program.CollectionNamespace.NamespaceName); } using (var cw = new CollectionWriter (ms, Program.WriterSettings, futureCw => { futureCw.Flush (); sw.Write (ProgramTest.ExpectedAnsweredAndAccepted); sw.Flush (); }) ) { doc.Save (cw); } sw.Flush (); ProgramTest.AssertStreamsAreEqual<CollectionWriterTest> ("CollectionWithInjectedItems.cxml", ms); } }
public void Typical() { using (var ms = new MemoryStream()) using (var sw = new StreamWriter(ms)) { XDocument doc; XmlNamespaceManager namespaceManager; using (var stream = AssemblyExtensions.OpenScopedResourceStream <CollectionWriter> ("Template.cxml")) using (var reader = XmlReader.Create(stream)) { doc = XDocument.Load(reader); namespaceManager = new XmlNamespaceManager(reader.NameTable); namespaceManager.AddNamespace("c", Namespaces.Collection.NamespaceName); } using (var cw = new CollectionWriter(ms, XmlWriterSettings, futureCw => { futureCw.Flush(); sw.Write(ProgramTest.ExpectedAnsweredAndAccepted); sw.Flush(); }) ) { doc.Save(cw); } sw.Flush(); ProgramTest.AssertStreamsAreEqual <CollectionWriterTest> ("CollectionWithInjectedItems.cxml", ms); } }
/// <summary> /// Gets a collection with the primitive elements from the data. /// </summary> /// <param name="data"> Data of the collection. </param> /// <param name="collectionType"> Type of the collection. </param> /// <param name="elementType"> Type of the element. </param> /// <param name="count"> Count of the elements. </param> /// <returns> The collection. </returns> protected virtual IEnumerable GetPrimitiveCollection(byte[] data, Type collectionType, Type elementType, int count) { IEnumerable enumerable = this.CreateCollection(collectionType, elementType, count); Func <string, object> reader = GetValueReader(elementType); if (reader != null) { IEnumerable <string> lines = StringUtils.SplitLines(data.GetString()); Array array = enumerable as Array; if (array != null) { int index = -1; foreach (string line in lines) { if (++index == count) { break; } array.SetValue(reader(line), index); } return(enumerable); } IList list = enumerable as IList; if (list != null) { int index = 0; foreach (string line in lines) { if (index++ == count) { break; } list.Add(reader(line)); } return(enumerable); } using (CollectionWriter writer = new CollectionWriter(this, enumerable)) { int index = 0; foreach (string line in lines) { if (index++ == count) { break; } writer.Add(reader(line)); } return(enumerable); } } return(enumerable); }
public void AddToCollection() { VerticeTransform defaultPosition = new VerticeTransform(); if (ArtefactSaveData.ArtefactIdentifier != null) { Debug.Log("Collection identifier: " + identifier.text); CollectionWriter.AddArtefactToCollectionWithIdentifier(identifier.text, ArtefactSaveData.ArtefactIdentifier, defaultPosition); } }
public void AddToCollection() { string artefactIdentifier = GameObject.Find("ArtefactInfoIdenifier_Text").GetComponent <Text>().text; VerticeTransform defaultPosition = new VerticeTransform(); if (artefactIdentifier.Length > 0) { Debug.Log("Collection identifier: " + identifier.text); CollectionWriter.AddArtefactToCollectionWithIdentifier(identifier.text, artefactIdentifier, defaultPosition); } }
public void SaveCollectionData() { //Pull metadata from struct Dictionary <string, string[]> collectionMetadata = new Dictionary <string, string[]>(); string[] collectTitles = DataListToArray(CollectDataHost.CollectionTitle); collectionMetadata.Add("title", collectTitles); // string[] identArray = new string[1]{CollectDataHost.CollectionIdentifier}; //FIXME can't have two 'identifier' keys in the dictionary // collectionMetadata.Add("identifier", identArray); string[] collectCreators = DataListToArray(CollectDataHost.CollectionCreator); collectionMetadata.Add("creator", collectCreators); string[] collectContributors = DataListToArray(CollectDataHost.CollectionContributor); collectionMetadata.Add("contributor", collectContributors); string[] collectDates = DataListToArray(CollectDataHost.CollectionDate); collectionMetadata.Add("date", collectDates); string[] collectCoverage = DataListToArray(CollectDataHost.CollectionCoverage); collectionMetadata.Add("coverage", collectCoverage); string[] collectSubject = DataListToArray(CollectDataHost.CollectionSubject); collectionMetadata.Add("subject", collectSubject); string[] descriptArray = new string[1] { CollectDataHost.CollectionDescription }; collectionMetadata.Add("description", descriptArray); //Create transforms Dictionary <string, VerticeTransform> artefactTransforms = new Dictionary <string, VerticeTransform>(); if (collectionArtefactsParent.childCount > 0) { for (int i = 0; i < collectionArtefactsParent.childCount; i++) { Transform curObjTrans = collectionArtefactsParent.GetChild(i); VerticeTransform curArtefactVerticeTrans = new VerticeTransform(curObjTrans.position, curObjTrans.rotation, curObjTrans.localScale); string curArtefactName = curObjTrans.name; artefactTransforms.Add(curArtefactName, curArtefactVerticeTrans); } } CollectionWriter.WriteCollectionWithIdentifer(CollectDataHost.CollectionIdentifier, collectionMetadata, artefactTransforms); // CollectMenuGuiControl.LoadCollectInfo(CollectDataHost.CollectionIdentifier); }
public void TestAddArtefactToCollection() { CreateTwoCollectionsWithTwoArtefacts(); CollectionReader.LoadXmlFromFile(Paths.CollectionMetadata); string[] collectionIdentifiers_00 = CollectionReader.GetIdentifiersForArtefactsInCollectionWithIdentifier("TEST-COLLECTION-00"); int numArtefactsBeforeAdd = collectionIdentifiers_00.Length; CollectionWriter.AddArtefactToCollectionWithIdentifier("TEST-COLLECTION-00", "NEW-ARTEFACT", new VerticeTransform(0f, 0f, 0f, 0f)); CollectionReader.LoadXmlFromFile(Paths.CollectionMetadata); string[] updated_collectionIdentifiers_00 = CollectionReader.GetIdentifiersForArtefactsInCollectionWithIdentifier("TEST-COLLECTION-00"); int numArtefactsAfterAdd = updated_collectionIdentifiers_00.Length; Assert.That(numArtefactsAfterAdd == (numArtefactsBeforeAdd + 1)); }
public void CreateTwoCollectionsWithTwoArtefacts() { for (int i = 0; i < 2; i++) { Dictionary <string, string[]> descriptiveData = new Dictionary <string, string[]> (); Dictionary <string, VerticeTransform> structuralData = new Dictionary <string, VerticeTransform> (); descriptiveData.Add("title", new string[] { "Test Title", "A second title" }); descriptiveData.Add("creator", new string[] { "Test Creator", "A co-creator" }); descriptiveData.Add("date", new string[] { "2016-10-20" }); for (int j = 0; j < 2; j++) { structuralData.Add(String.Format("TEST-ARTEFACT-0{0}", j), new VerticeTransform(Vector3.one, Quaternion.identity, Vector3.one)); } CollectionWriter.WriteCollectionWithIdentifer(String.Format("TEST-COLLECTION-0{0}", i), descriptiveData, structuralData); } }
public void TestSaveLocationChanges() { // Check that, when the save location is changed, the two XML files a) can vary independently, and that b) the second file // is an extension of whatever data existed in the first file (i.e. that, in a sense, operations on the second file are precluded by // all of the operations that had occurred to establish the first file). CollectionWriter.EstablishNewDocument(); // Create some data Dictionary <string, string[]> descriptiveData = new Dictionary <string, string[]>(); Dictionary <string, VerticeTransform> structuralData = new Dictionary <string, VerticeTransform>(); descriptiveData.Add("title", new string[] { "Test Title" }); descriptiveData.Add("creator", new string[] { "Test Creator" }); descriptiveData.Add("date", new string[] { "2016-10-20" }); structuralData.Add("TEST-ARTEFACT-01", new VerticeTransform(Vector3.one, Quaternion.identity, Vector3.one)); // Write data to the first file Paths.CollectionMetadata = Environment.CurrentDirectory + "/Assets/Scripts/Metadata/TestAssets/Collection_Writer_Test.xml"; CollectionWriter.WriteCollectionWithIdentifer("TEST-COLLECTION-01", descriptiveData, structuralData); // Change location and save the new collection Paths.CollectionMetadata = Environment.CurrentDirectory + "/Assets/Scripts/Metadata/TestAssets/Collection_Writer_Test_02.xml"; CollectionWriter.WriteCollectionWithIdentifer("TEST-COLLECTION-02", descriptiveData, structuralData); // Check that the first file has only one collection CollectionReader.LoadXmlFromFile(Environment.CurrentDirectory + "/Assets/Scripts/Metadata/TestAssets/Collection_Writer_Test.xml"); string[] collectionIdentifiers_01 = CollectionReader.GetIdentifiersForCollections(); Assert.That(collectionIdentifiers_01.Length == 1); // Now check that the second file has two CollectionReader.LoadXmlFromFile(Paths.CollectionMetadata); string[] collectionIdentifiers_02 = CollectionReader.GetIdentifiersForCollections(); Assert.That(collectionIdentifiers_02.Length == 2); // Tidy up (the second file will be deleted in TearDown) File.Delete(Environment.CurrentDirectory + "/Assets/Scripts/Metadata/TestAssets/Collection_Writer_Test.xml"); }
public void TestOverwriteCollection() { CreateTwoCollectionsWithTwoArtefacts(); Dictionary <string, string[]> descriptiveData = new Dictionary <string, string[]>(); Dictionary <string, VerticeTransform> structuralData = new Dictionary <string, VerticeTransform>(); descriptiveData.Add("title", new string[] { "Test Overwrite" }); descriptiveData.Add("creator", new string[] { "Test Creator Overwrite" }); descriptiveData.Add("date", new string[] { "2016-10-26" }); structuralData.Add("TEST-ARTEFACT-03", new VerticeTransform(Vector3.one, Quaternion.identity, Vector3.one)); CollectionWriter.WriteCollectionWithIdentifer("TEST-COLLECTION-00", descriptiveData, structuralData); CollectionReader.LoadXmlFromFile(Paths.CollectionMetadata); Dictionary <string, string[]> collectionMetadata = CollectionReader.GetCollectionMetadataWithIdentifier("TEST-COLLECTION-00"); Assert.That(collectionMetadata ["title"] [0] == "Test Overwrite"); Assert.That(collectionMetadata ["creator"] [0] == "Test Creator Overwrite"); Assert.That(collectionMetadata ["date"] [0] == "2016-10-26"); Dictionary <string, Dictionary <string, float> > transformData = CollectionReader.GetTransformForArtefactWithIdentifierInCollection("TEST-COLLECTION-00", "TEST-ARTEFACT-03"); Assert.That(transformData ["position"] ["x"] == Vector3.one.x); Assert.That(transformData ["position"] ["y"] == Vector3.one.y); Assert.That(transformData ["position"] ["z"] == Vector3.one.z); Assert.That(transformData ["rotation"] ["x"] == Quaternion.identity.x); Assert.That(transformData ["rotation"] ["y"] == Quaternion.identity.y); Assert.That(transformData ["rotation"] ["z"] == Quaternion.identity.z); Assert.That(transformData ["rotation"] ["w"] == Quaternion.identity.w); Assert.That(transformData ["scale"] ["x"] == Vector3.one.x); Assert.That(transformData ["scale"] ["y"] == Vector3.one.y); Assert.That(transformData ["scale"] ["z"] == Vector3.one.z); }
public void TestWriteCollectionData_OneToOne() { // Test that a collection whose descriptive elements are non-repeating write correctly Dictionary <string, string[]> descriptiveData = new Dictionary <string, string[]>(); Dictionary <string, VerticeTransform> structuralData = new Dictionary <string, VerticeTransform>(); descriptiveData.Add("title", new string[] { "Test Title" }); descriptiveData.Add("creator", new string[] { "Test Creator" }); descriptiveData.Add("date", new string[] { "2016-10-20" }); structuralData.Add("TEST-ARTEFACT-01", new VerticeTransform(Vector3.one, Quaternion.identity, Vector3.one)); CollectionWriter.WriteCollectionWithIdentifer("TEST-COLLECTION-01", descriptiveData, structuralData); CollectionReader.LoadXmlFromFile(Paths.CollectionMetadata); Dictionary <string, string[]> collectionMetadata = CollectionReader.GetCollectionMetadataWithIdentifier("TEST-COLLECTION-01"); Dictionary <string, Dictionary <string, float> > transformData = CollectionReader.GetTransformForArtefactWithIdentifierInCollection("TEST-COLLECTION-01", "TEST-ARTEFACT-01"); Assert.That(collectionMetadata ["title"] [0] == "Test Title"); Assert.That(collectionMetadata ["creator"] [0] == "Test Creator"); Assert.That(collectionMetadata ["date"] [0] == "2016-10-20"); Assert.That(transformData ["position"] ["x"] == Vector3.one.x); Assert.That(transformData ["position"] ["y"] == Vector3.one.y); Assert.That(transformData ["position"] ["z"] == Vector3.one.z); Assert.That(transformData ["rotation"] ["x"] == Quaternion.identity.x); Assert.That(transformData ["rotation"] ["y"] == Quaternion.identity.y); Assert.That(transformData ["rotation"] ["z"] == Quaternion.identity.z); Assert.That(transformData ["rotation"] ["w"] == Quaternion.identity.w); Assert.That(transformData ["scale"] ["x"] == Vector3.one.x); Assert.That(transformData ["scale"] ["y"] == Vector3.one.y); Assert.That(transformData ["scale"] ["z"] == Vector3.one.z); }
public void ConstructorTest() { _collectionWriterT = new CollectionWriter<Entry>(_collectionWriter); }
/// <summary> /// Tries read the entries of the data by the path and creates a new collection. /// </summary> /// <param name="path"> The path. </param> /// <param name="type"> The type. </param> /// <param name="typeInterfaces"> Interfaces of the type. </param> /// <param name="className"> Name of the class. </param> /// <param name="values"> Values of the class. </param> /// <param name="storer"> The storer. </param> /// <param name="entries"> List of the entries of the storer. </param> /// <param name="references"> Dictionary that contains references to the objects. </param> /// <returns> Collection if collection has been created successfully, otherwise null. </returns> private object TryReadCollection(string path, Type type, Type[] typeInterfaces, string className, IDictionary <string, string> values, IReadOnlyDataStorer storer, LinkedList <IDataStorerEntry> entries, Dictionary <string, object> references) { // Tries get types of the collection and elements of the collection Type[] targetTypes = GetCollectionTypesCA(type, typeInterfaces, className); if (targetTypes == null) { // Target types are null -> collection isn't supported -> returns null return(null); } // Reads the information about of the collection Type collectionType = targetTypes[0]; Type elementType = targetTypes[1]; int count = Convert.ToInt32(values[CountString]); if (count != 0) { bool isPrimitive = values[PrimitiveString] == TrueString; if (!isPrimitive) { // Elements of the array/collection aren't primitive - reads the elements from different files IEnumerable enumerable = this.CreateCollection(collectionType, elementType, count); references.Add(path, enumerable); Array array = enumerable as Array; if (array != null) { // Reads the array for (int i = 0; i < count; i++) { array.SetValue(this.Read( elementType, StringUtils.Combine(path, i.ToString(), DirectorySeparatorString), storer, entries, references), i ); } return(enumerable); } else { // Reads the collection IList list = enumerable as IList; if (list != null) { // Collection implements IList interface - the interface should be used for the fast writing the elements of the collection for (int i = 0; i < count; i++) { list.Add(this.Read( elementType, StringUtils.Combine(path, i.ToString(), DirectorySeparatorString), storer, entries, references) ); } return(enumerable); } else { // Collection not implements IList interface - the collection writer should be used for the writing the elements of the collection using (CollectionWriter writer = new CollectionWriter(this, enumerable)) { for (int i = 0; i < count; i++) { writer.Add(this.Read( elementType, StringUtils.Combine(path, i.ToString(), DirectorySeparatorString), storer, entries, references) ); } } return(enumerable); } } } else { // Elements of the array/collection are primitive - reads the elements from single file byte[] data = ReadAndRemoveEntry(path, CollectionFileName, storer, entries); IEnumerable enumerable = this.GetPrimitiveCollection(data, collectionType, elementType, count); references.Add(path, enumerable); return(enumerable); } } else { // Collection is empty -> returns empty collection IEnumerable enumerable = this.CreateCollection(collectionType, elementType, 0); references.Add(path, enumerable); return(enumerable); } }
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 void TestAddArtefactToNonexistantCollection() { CollectionWriter.EstablishNewDocument(); CollectionWriter.AddArtefactToCollectionWithIdentifier("NON-EXISTANT COLLECTION", "", new VerticeTransform(0f, 0f, 0f, 0f)); }
// asynchronously write into post man collection private static void LogException(HttpContext context, Exception e) => CollectionWriter.WriteIntoCollection(context, e);
public void ConstructorTest() { _collectionWriterT = new CollectionWriter <Entry>(_collectionWriter); }