static void Main() { /***********************************************************/ /** This "using" relates to resource management **/ using (ExampleObject exampleObject = new ExampleObject()) { exampleObject.SomeMethod(); } /***********************************************************/ /***********************************************************/ /** The previous using statement is similar than following try statement **/ ExampleObject exampleObjectCopy = new ExampleObject(); try { exampleObjectCopy.SomeMethod(); } finally { if (exampleObjectCopy != null) { ((IDisposable)exampleObjectCopy).Dispose(); } } /***********************************************************/ } //end method Main
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test public void testCreateObjectVariables() public virtual void testCreateObjectVariables() { VariableMap variables = createVariables().putValue(DESERIALIZED_OBJECT_VAR_NAME, objectValue(DESERIALIZED_OBJECT_VAR_VALUE)); assertEquals(DESERIALIZED_OBJECT_VAR_VALUE, variables[DESERIALIZED_OBJECT_VAR_NAME]); assertEquals(DESERIALIZED_OBJECT_VAR_VALUE, variables.getValue(DESERIALIZED_OBJECT_VAR_NAME, typeof(ExampleObject))); object untypedValue = variables.getValueTyped(DESERIALIZED_OBJECT_VAR_NAME).Value; assertEquals(DESERIALIZED_OBJECT_VAR_VALUE, untypedValue); ExampleObject typedValue = variables.getValueTyped <ObjectValue>(DESERIALIZED_OBJECT_VAR_NAME).getValue(typeof(ExampleObject)); assertEquals(DESERIALIZED_OBJECT_VAR_VALUE, typedValue); // object type name is not yet available assertNull(variables.getValueTyped <ObjectValue>(DESERIALIZED_OBJECT_VAR_NAME).ObjectTypeName); // class is available assertEquals(DESERIALIZED_OBJECT_VAR_VALUE.GetType(), variables.getValueTyped <ObjectValue>(DESERIALIZED_OBJECT_VAR_NAME).ObjectType); variables = createVariables().putValue(DESERIALIZED_OBJECT_VAR_NAME, objectValue(DESERIALIZED_OBJECT_VAR_VALUE).serializationDataFormat(SERIALIZATION_DATA_FORMAT_NAME)); assertEquals(DESERIALIZED_OBJECT_VAR_VALUE, variables[DESERIALIZED_OBJECT_VAR_NAME]); }
public void Receive_TestAutoSerializedObj(NetworkReader reader) { ExampleObject obj = new ExampleObject(); NetworkSerializer.ExampleObjectSerializer.NetworkDeserialize(obj, reader); TestAutoSerializedObj(obj); }
public void ShouldAllowValueToBeUpdated() { var newValue = new ExampleObject(); var newContext = StateVariables.GetNewStateVariablesBuilder().Update(new StringKey("key"), newValue).Build(); Assert.AreEqual(newValue, newContext.Get<ExampleObject>(new StringKey("key"))); }
public static void NetworkSerialize(ExampleObject value, NetworkWriter writer) { writer.Write(value.num); writer.Write(value.str); writer.Write(value.flt); writer.Write(value.numNonSerialized); }
/// <summary> /// Reads all stored game object ids. /// </summary> void ReadAllStoredObjects() { if (File.Exists(_filePath)) { Debug.LogFormat("Found file {0}", _filePath); using (var source = new StreamReader(_filePath)) { string fileContents = source.ReadToEnd(); if (!string.IsNullOrEmpty(fileContents)) { ObjIds ids = JsonUtility.FromJson <ObjIds>(fileContents); if (ids.Ids != null && ids.Ids.Length > 0) { foreach (string id in ids.Ids) { Debug.LogFormat("Found : {0} in file", id); ExampleObject exampleObj = new ExampleObject(); exampleObj.GO = Instantiate(_goPrefab, Vector3.zero, Quaternion.identity); exampleObj.GO.name = id; exampleObj.GO.SetActive(false); _exampleObjects.Add(exampleObj); } } } _state = State.StartRestore; } } }
public void TestAutoSerializedObj(ExampleObject obj) { NetworkWriter writer = _netSender.CreateWriter(-1696487214); NetworkSerializer.ExampleObjectSerializer.NetworkSerialize(obj, writer); _netSender.PrepareAndSendWriter(writer); }
void DrawMatchGUI() { GUILayout.Label("Match Scope"); GUILayout.Space(10); if (GUILayout.Button("Send Play Action")) { client.Match.SendToServer.Play(); } if (GUILayout.Button("Send Auto-Serialized Object")) { ExampleObject obj = new ExampleObject(); obj.num = 10; obj.flt = 99.99f; obj.str = "Ten"; obj.numNonSerialized = 99; Debug.Log("Sending auto-serialized object: " + obj); client.Match.SendToServer.TestAutoSerializedObj(obj); } if (GUILayout.Button("Leave Match")) { client.Match.SendToServer.LeaveMatch(); } }
public static void NetworkDeserialize(ExampleObject value, NetworkReader reader) { value.num = reader.ReadInt32(); value.str = reader.ReadString(); value.flt = reader.ReadSingle(); value.numNonSerialized = reader.ReadInt32(); }
public void ParseCommandLineArguments_OrdinalPositions() { var obj = new ExampleObject(); ArgumentParser.ParseCommandLineArguments(obj, new string[] { "a", "b" }); Assert.AreEqual("a", obj.Value1); Assert.AreEqual("b", obj.Value2); }
private static Example ExampleObjectToModel(ExampleObject e) { return(new Example() { text = e.text, language = e.language }); }
public void Add(ExampleObject example) { using (Database context = new Database()) { context.Examples.Add(example); context.SaveChanges(); } }
public void TestCustomGetter() { var o = new ExampleObject(); for (int i = 0; i < 10; i++) { Assert.AreEqual(i * 2, o.Double[i]); } }
public void TestCharAccess() { var o = new ExampleObject(); for (int i = 0; i < o._letters.Length; i++) { Assert.AreEqual(o._letters[i], o.Typesetter[i]); } }
public void Delete(int id) { using (Database context = new Database()) { ExampleObject example = context.Examples.FirstOrDefault(p => p.Id == id); context.Examples.Remove(example); context.SaveChanges(); } }
public string Serialize_Object() { // set up JsonNetBsonFormatter formatter = new JsonNetBsonFormatter(); ExampleObject expected = new ExampleObject { Number = 42, Text = "fourty-two" }; HttpRequestMessage request = this.GetRequest(expected, formatter); // verify return this.GetSerialized(expected, request, formatter); }
public void SetValue_ValidObject_ValidValue() { // Arrange var reflection = ReflectionCache.GetReflection(typeof(ExampleObject)).Properties["Property2"]; ExampleObject obj = new ExampleObject(); // Act reflection.SetValue(obj, "test string"); // Assert Assert.AreEqual("test string", obj.Property2); }
public void GetValue_ValidObject_ValidValue() { // Arrange var reflection = ReflectionCache.GetReflection(typeof(ExampleObject)).Properties["Property4"]; ExampleObject obj = new ExampleObject(); // Act var result = reflection.GetValue(obj); // Assert Assert.AreEqual(obj, result); }
public void Invoke_ValidObject_ValidValue() { // Arrange var reflection = ReflectionCache.GetReflection(typeof(ExampleObject)).Methods["TestMethod"][1]; ExampleObject obj = new ExampleObject(); // Act reflection.Invoke(obj, 3); // Assert Assert.AreEqual(3, obj.Property1); }
public string Serialize_Object() { // set up BsonFormatter formatter = new BsonFormatter(); ExampleObject expected = new ExampleObject { Number = 42, Text = "fourty-two" }; HttpRequestMessage request = this.GetRequest(expected, formatter); // verify return(this.GetSerialized(expected, request, formatter)); }
public void ShouldNotThrowGivenSameObject() { //Arrange VariabledClass expectedValue = new VariabledClass(); ExampleObject exampleObject = new ExampleObject(expectedValue); ClassVariableTypeValidation subject = new ClassVariableTypeValidation() .FieldShouldBeType <VariabledClass>("_variable", expectedValue); //Act Action action = () => subject.AssertFieldsAreExpectedType(exampleObject); //Assert action.Should().NotThrow(); }
public void ShouldThrowGivenDifferentObjects() { //Arrange ExampleObject exampleObject = new ExampleObject(new VariabledClass()); ClassVariableTypeValidation subject = new ClassVariableTypeValidation() .FieldShouldBeType <VariabledClass>("_variable", new VariabledClass()); //Act Action action = () => subject.AssertFieldsAreExpectedType(exampleObject); //Assert action.Should().Throw <AsserterException>().WithMessage( "Field [name=_variable] is not the same reference as expected and does not '#Equals()' actual. [expected=InterfaceMocksTests.Validators.ClassVariableTypeValidationTests+VariabledClass] [actual =InterfaceMocksTests.Validators.ClassVariableTypeValidationTests+VariabledClass]"); }
public void Deserialize_Object(string content) { // set up JsonNetBsonFormatter formatter = new JsonNetBsonFormatter(); ExampleObject expected = new ExampleObject { Number = 42, Text = "fourty-two" }; HttpRequestMessage request = this.GetRequest(content, formatter); // execute ExampleObject result = (ExampleObject)this.GetDeserialized(typeof(ExampleObject), content, request, formatter); // verify Assert.That(result, Is.Not.Null); Assert.That(result.Number, Is.EqualTo(expected.Number)); Assert.That(result.Text, Is.EqualTo(expected.Text)); }
public void ParseCommandLineArguments_NamedArgument() { { var obj = new ExampleObject(); ArgumentParser.ParseCommandLineArguments(obj, new string[] { "--Value3", "c" }); Assert.AreEqual("c", obj.Value3); } { var obj = new ExampleObject(); ArgumentParser.ParseCommandLineArguments(obj, new string[] { "--Value3", "c", "-Value1", "a" }); Assert.AreEqual("a", obj.Value1); Assert.IsTrue(string.IsNullOrEmpty(obj.Value2)); Assert.AreEqual("c", obj.Value3); } }
internal static void ExampleProgram() { // Assuming setting some variable is thread-sensitive. // Often the variable is the state or value of a UI object in a Forms application // since you can't change UI objects across threads. string ThreadSensitiveVariable; ExampleObject AnObject = new ExampleObject(); // Generally speaking you should only do this once during initialization AnObject.ExampleEvent += Result => ThreadSensitiveVariable = Result; var backgroundTask = Task.Run(() => AnObject.BackgroundTask()); // In a windows forms application, if this were a button event, you can just return now // That lets the UI thread keep chugging along. }
public override void UpdateDatabaseAfterUpdateSchema() { base.UpdateDatabaseAfterUpdateSchema(); if (ObjectSpace.GetObjectsCount(typeof(ExampleObject), null) == 0) { for (int i = 0; i < 5; i++) { ReferencedObject refObject = ObjectSpace.CreateObject <ReferencedObject>(); refObject.Name = string.Format("Owner Object {0:d}", i + 1); ExampleObject exampleObj = ObjectSpace.CreateObject <ExampleObject>(); exampleObj.Name = string.Format("Example object {0:d}", i + 1); exampleObj.LookupReferencedObject = refObject; } ObjectSpace.CommitChanges(); } }
static void Main() { try { var server = new MetricServer(port: 5725); server.Start(); // Run test string dbName = Guid.NewGuid().ToString(); using var db = new SampleDBContext(); Task.Run(() => { while (true) { if (File.Exists(db.DbName)) { DatabaseSize.Set(new FileInfo(db.DbName).Length); } Task.Delay(5000).Wait(); } }); Log("Insert 1000000 of objects"); for (int i = 0; i < 1000000; i++) { var obj = new ExampleObject() { Name = "example name", Value = 1234567890 }; db.ExampleObjects.Add(obj); db.SaveChanges(); InsertObjectCounter.Inc(); } Log("Process finished"); } catch (Exception ex) { Log($"Error: {ex.Message} - {ex.StackTrace}"); } }
public void Deserialize_Object(string content) { // set up BsonFormatter formatter = new BsonFormatter(); ExampleObject expected = new ExampleObject { Number = 42, Text = "fourty-two" }; HttpRequestMessage request = this.GetRequest(content, formatter); // execute ExampleObject result = (ExampleObject)this.GetDeserialized(typeof(ExampleObject), content, request, formatter); // verify Assert.That(result, Is.Not.Null); Assert.That(result.Number, Is.EqualTo(expected.Number)); Assert.That(result.Text, Is.EqualTo(expected.Text)); }
//if you call this, you need to remove the record from PrizmRecordGroup.associates list as well public IEnumerator RemoveRecord(ExampleObject record) { Debug.LogError("Removing from database: " + record.name + "with UID: " + record.dbEntry._id); var methodCall = Meteor.Method <ChannelResponse> .Call("removeGameObject", record.dbEntry._id); yield return((Coroutine)methodCall); if (methodCall.Response.success) { Debug.LogError("Successfully removed from database, message: " + methodCall.Response.message); } else { Debug.LogError("Error removing " + record.dbEntry._id + " from database"); } }
public void SerializationAndDeserialization_RespectsNewtonsoftAttributes() { var obj = new ExampleObject() { ShouldNotSerialize = "value should not get serialized", ShouldIncludeWhenSerializing = "value should get serialized", }; var jsonString = JsonConvert.SerializeObject(obj); var expectedJson = new JObject { { "ShouldIncludeWhenSerializing", "value should get serialized" }, }; var json = JToken.Parse(jsonString); Test.AssertSameJson(expectedJson, json); }
static void Main() { try { var server = new MetricServer(port: 5724); server.Start(); // Run test string dbName = Guid.NewGuid().ToString(); using var db = new LiteDatabase($"Filename={dbName};"); Task.Run(() => { while (true) { DatabaseSize.Set(new FileInfo(dbName).Length); Task.Delay(5000).Wait(); } }); // Insert 1M of objects var insertCollection = db.GetCollection <ExampleObject>("insertData"); Log("Insert 1000000 of objects"); for (int i = 0; i < 1000000; i++) { var obj = new ExampleObject() { Name = "example name", Value = 1234567890 }; insertCollection.Insert(obj); InsertObjectCounter.Inc(); } Log("Process finished"); } catch (Exception ex) { Log($"Error: {ex.Message} - {ex.StackTrace}"); } }
/// <summary> /// Add a Record to the database and prove it exists. /// </summary> public void ExampleAdd() { ConsoleLog.LogSub("Example Start: Add Object"); ExampleObject example = new ExampleObject { Name = "Terry" }; exampleService.Add(example); ConsoleLog.LogText("Example Object added."); ConsoleLog.LogText($"Getting Example Object"); List <ExampleObject> examples = exampleService.GetAll(); for (int i = 0; i < examples.Count(); i++) { ConsoleLog.LogResult($"Found Example {examples[i].Id}, Name:{examples[i].Name}"); } ConsoleLog.LogSub("Example End: Add Object"); }
public void SetValue_NoSetter_NoSuchMethodException() { // Arrange var reflection = ReflectionCache.GetReflection(typeof(ExampleObject)).Properties["Property4"]; ExampleObject obj = new ExampleObject(); // Act NoSuchMethodReflectionException e = null; try { reflection.SetValue(obj, "test string"); } catch (NoSuchMethodReflectionException ex) { e = ex; } // Assert Assert.IsNotNull(e); }
public void ValueShouldNotBeUpdatedInOriginalContext() { var newValue = new ExampleObject(); StateVariables.GetNewStateVariablesBuilder().Update(new StringKey("key"), newValue).Build(); Assert.AreNotEqual(newValue, StateVariables.Get<ExampleObject>(new StringKey("key"))); Assert.AreEqual(FirstValue, StateVariables.Get<ExampleObject>(new StringKey("key"))); }