public static void JsonDocumentDeserialize_NonGeneric() { using JsonDocument dom = JsonDocument.Parse(Json); MyPoco obj = (MyPoco)dom.Deserialize(typeof(MyPoco)); obj.Verify(); }
public static void JsonNodeDeserialize_Null() { JsonNode node = null; MyPoco obj = JsonSerializer.Deserialize <MyPoco>(node); Assert.Null(obj); }
public static void JsonDocumentDeserialize_Generic() { using JsonDocument dom = JsonDocument.Parse(Json); MyPoco obj = dom.Deserialize <MyPoco>(); obj.Verify(); }
public void TestStoredProcedureOutput() { /* * CREATE PROCEDURE [Test] * @Input1 [int], * @Output1 [int] OUTPUT * AS * BEGIN * SET @Output1 = 2 * END; * GO */ MyPoco poco = new MyPoco(); var cmd = cn.CommandBuilder($"[dbo].[Test]") .AddParameter("Input1", dbType: DbType.Int32); //.AddParameter("Output1", dbType: DbType.Int32, direction: ParameterDirection.Output); //var getter = ParameterInfos.GetSetter((MyPoco p) => p.MyValue); cmd.Parameters.Add(ParameterInfo.CreateOutputParameter("Output1", poco, p => p.MyValue, ParameterInfo.OutputParameterDirection.Output, size: 4)); int affected = cmd.Execute(commandType: CommandType.StoredProcedure); string outputValue = cmd.Parameters.Get <string>("Output1"); // why is this being returned as string? just because I didn't provide type above? Assert.AreEqual(outputValue, "2"); Assert.AreEqual(poco.MyValue, 2); }
public static void JsonNodeDeserialize_Generic() { JsonNode dom = JsonNode.Parse(Json); MyPoco obj = dom.Deserialize <MyPoco>(); obj.Verify(); }
public static void JsonNodeDeserialize_NonGeneric() { JsonNode dom = JsonNode.Parse(Json); MyPoco obj = (MyPoco)dom.Deserialize(typeof(MyPoco)); obj.Verify(); }
public static void TableInput( [QueueTrigger("table-items")] string input, [Table("MyTable", "MyPartition", "{queueTrigger}")] MyPoco poco, ILogger log) { log.LogInformation($"PK={poco.PartitionKey}, RK={poco.RowKey}, Text={poco.Text}"); }
public static void JsonDocumentDeserialize_Null() { using JsonDocument dom = JsonDocument.Parse("null"); MyPoco obj = dom.Deserialize <MyPoco>(); Assert.Null(obj); }
public static void JsonElementDeserialize_Generic() { using JsonDocument document = JsonDocument.Parse(Json); JsonElement dom = document.RootElement; MyPoco obj = JsonSerializer.Deserialize <MyPoco>(dom); obj.Verify(); }
public static void JsonElementDeserialize_NonGeneric() { using JsonDocument document = JsonDocument.Parse(Json); JsonElement dom = document.RootElement; MyPoco obj = (MyPoco)JsonSerializer.Deserialize(dom, typeof(MyPoco)); obj.Verify(); }
public ActionResult <ActionResult <MyPoco> > Get(MyPoco poco) { if (poco is null) { return(NotFound()); } return(Ok(poco)); }
public static async Task <IActionResult> Run( [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req, ILogger log) { log.LogInformation("C# HTTP trigger function processed a request."); //Read Request Body var content = await new StreamReader(req.Body).ReadToEndAsync(); //Extract Request Body and Parse To Class MyPoco objMyPoco = JsonConvert.DeserializeObject <MyPoco>(content); // Validate param because PartitionKey and RowKey is required to read from Table storage In this case , so I am checking here. dynamic validationMessage; if (string.IsNullOrEmpty(objMyPoco.PartitionKey)) { validationMessage = new OkObjectResult("PartitionKey is required!"); return((IActionResult)validationMessage); } if (string.IsNullOrEmpty(objMyPoco.RowKey)) { validationMessage = new OkObjectResult("RowKey is required!"); return((IActionResult)validationMessage); } // Table Storage operation with credentials var client = new CloudTableClient(new Uri("https://YourStorageURL.table.core.windows.net/"), new Microsoft.WindowsAzure.Storage.Auth.StorageCredentials("YourStorageName", "xtaguZokAWbfYG4QDkBjT+YourStorageKey+T/kId/Ng+cl3TfYHtg==")); var table = client.GetTableReference("YourTableName"); //Query filter var query = new TableQuery() { FilterString = string.Format("PartitionKey eq '{0}' and RowKey eq '{1}'", objMyPoco.PartitionKey, objMyPoco.RowKey) }; //Request for storage query with query filter var continuationToken = new TableContinuationToken(); var storageTableQueryResults = new List <TableStorageClass>(); foreach (var entity in table.ExecuteQuerySegmentedAsync(query, continuationToken).GetAwaiter().GetResult().Results) { var request = new TableStorageClass(entity); storageTableQueryResults.Add(request); } //As we have to return IAction Type So converting to IAction Class Using OkObjectResult We Even Can Use OkResult var result = new OkObjectResult(storageTableQueryResults); return((IActionResult)result); }
public void Can_StoreObject() { object poco = new MyPoco { Id = 1, Name = "Test" }; Redis.StoreObject(poco); Assert.That(Redis.Get <string>("urn:mypoco:1"), Is.EqualTo("{\"Id\":1,\"Name\":\"Test\"}")); Assert.That(Redis.PopItemFromSet("ids:MyPoco"), Is.EqualTo("1")); }
public static JsonResult TableGetRow( [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "TableGetRow/{PartitionKey}/{RowKey}")] HttpRequest req, [Table("TableBinding", "{PartitionKey}", "{RowKey}")] MyPoco poco, ILogger log, string PartitionKey, string RowKey) { log.LogInformation($"Hello: Query PartitionKey={PartitionKey} and Query RowKey={RowKey}"); log.LogInformation($"PK={poco.PartitionKey}, RK={poco.RowKey}, Name={poco.Name}, Job={poco.Job}"); return(new JsonResult(poco)); }
public void Can_StoreObject() { object poco = new MyPoco { Id = 1, Name = "Test" }; this.Redis.StoreObject(poco); Assert.That(this.Redis.GetValue(this.Redis.NamespacePrefix + "urn:mypoco:1"), Is.EqualTo("{\"Id\":1,\"Name\":\"Test\"}")); Assert.That(this.Redis.PopItemFromSet(this.Redis.NamespacePrefix + "ids:MyPoco"), Is.EqualTo("1")); }
public async Task Can_StoreObject() { object poco = new MyPoco { Id = 1, Name = "Test" }; await RedisAsync.StoreObjectAsync(poco); Assert.That(await RedisAsync.GetValueAsync(RedisRaw.NamespacePrefix + "urn:mypoco:1"), Is.EqualTo("{\"Id\":1,\"Name\":\"Test\"}")); Assert.That(await RedisAsync.PopItemFromSetAsync(RedisRaw.NamespacePrefix + "ids:MyPoco"), Is.EqualTo("1")); }
public static void WritePocoArray() { var input = new MyPoco[] { null, new MyPoco { Foo = "foo" } }; string json = JsonSerializer.Serialize(input, new JsonSerializerOptions { Converters = { new MyPocoConverter() } }); Assert.Equal("[null,{\"Foo\":\"foo\"}]", json); }
public static JsonResult TableInput( [HttpTrigger(AuthorizationLevel.Function, "get", Route = "TableRowOut/{PartitionKey}/{RowKey}")] HttpRequest req, //Trigger Route expects two parameters in Nice Url Style [Table("TableBinding", "{PartitionKey}", "{RowKey}")] MyPoco poco, //poco is the object that will be returned from the table ILogger log, string PartitionKey, //pass the params into the function so we can use them if nessasary. string RowKey) { //Log Query and Reult Info log.LogInformation($"Hello: Query PartitionKey={PartitionKey} and Query RowKey={RowKey}"); log.LogInformation($"PK={poco.PartitionKey}, RK={poco.RowKey}, Name={poco.Name}, Job={poco.Job}"); //Return Json Formatted Data return(new JsonResult(poco)); }
public static ActionResult TableGetRowJsonOrXml( [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "TableGetRowJsonOrXml/{PartitionKey}/{RowKey}")] HttpRequest req, [Table("TableBinding", "{PartitionKey}", "{RowKey}")] MyPoco poco, ILogger log, string PartitionKey, string RowKey) { log.LogInformation($"Hello: Query PartitionKey={PartitionKey} and Query RowKey={RowKey}"); log.LogInformation($"PK={poco.PartitionKey}, RK={poco.RowKey}, Name={poco.Name}, Job={poco.Job}"); return(poco != null ? (ActionResult) new OkObjectResult(poco) : new BadRequestObjectResult("Data not found.")); }
public void CouldWritePOCO() { var ptr = Marshal.AllocHGlobal(1024); var myPoco = new MyPoco { String = "MyString", Long = 123 }; TypeHelper <MyPoco> .StructureToPtr(myPoco, ptr); var newPoco = TypeHelper <MyPoco> .PtrToStructure(ptr); Assert.AreEqual(myPoco.String, newPoco.String); Assert.AreEqual(myPoco.Long, newPoco.Long); }
public void WhenPocoDoesNotExist_ShouldAddPoco() { //Arrange var controller = new MyPocoController(); var expectedId = Guid.NewGuid(); var expectedName = "SomePocoName"; var newPoco = new MyPoco() { Id = expectedId, Name = expectedName }; //Act controller.UpdatePoco(newPoco); //Assert Assert.IsNotNull(controller.GetPoco(expectedId)); }
public void CouldWritePOCOToBuffer() { var ptr = Marshal.AllocHGlobal(1024); var buffer = new DirectBuffer(1024, ptr); var myPoco = new MyPoco { String = "MyString", Long = 123 }; buffer.Write(0, myPoco); var newPoco = buffer.Read <MyPoco>(0); Assert.AreEqual(myPoco.String, newPoco.String); Assert.AreEqual(myPoco.Long, newPoco.Long); }
//optional queue output message as C# object //Poco's can be used for numerous output bindings public static void FileProcessQueuePocoOutput( [FileTrigger(@"Queue\{fileName}", "*")] Stream localInput, string fileName, [Queue("azurequeue")] out MyPoco azureQueueMessage, TextWriter log) { azureQueueMessage = null; if (localInput.Length > 20) { azureQueueMessage = new MyPoco { Message = "Large file uploaded", FileName = fileName }; } }
public static void SerializeToElement() { MyPoco obj = MyPoco.Create(); JsonElement dom = JsonSerializer.SerializeToElement(obj); JsonElement stringProp = dom.GetProperty("StringProp"); Assert.Equal(JsonValueKind.String, stringProp.ValueKind); Assert.Equal("Hello", stringProp.ToString()); JsonElement[] elements = dom.GetProperty("IntArrayProp").EnumerateArray().ToArray(); Assert.Equal(JsonValueKind.Number, elements[0].ValueKind); Assert.Equal(1, elements[0].GetInt32()); Assert.Equal(JsonValueKind.Number, elements[1].ValueKind); Assert.Equal(2, elements[1].GetInt32()); }
public static void SerializeToNode() { MyPoco obj = MyPoco.Create(); JsonNode dom = JsonSerializer.SerializeToNode(obj); JsonNode stringProp = dom["StringProp"]; Assert.True(stringProp is JsonValue); Assert.Equal("Hello", stringProp.AsValue().GetValue <string>()); JsonNode arrayProp = dom["IntArrayProp"]; Assert.IsType <JsonArray>(arrayProp); Assert.Equal(1, arrayProp[0].AsValue().GetValue <int>()); Assert.Equal(2, arrayProp[1].AsValue().GetValue <int>()); }
public unsafe void CouldUseNewUnsafePackage() { var dt = new KeyValuePair <DateTime, decimal> [2]; dt[0] = new KeyValuePair <DateTime, decimal>(DateTime.UtcNow.Date, 123.456M); dt[1] = new KeyValuePair <DateTime, decimal>(DateTime.UtcNow.Date.AddDays(1), 789.101M); var obj = (object)dt; byte[] asBytes = Unsafe.As <byte[]>(obj); //Console.WriteLine(asBytes.Length); // prints 2 fixed(byte *ptr = &asBytes[0]) { // reading this: https://github.com/dotnet/coreclr/issues/5870 // it looks like we could fix byte[] and actually KeyValuePair<DateTime, decimal>[] will be fixed // because: // "GC does not care about the exact types, e.g. if type of local object // reference variable is not compatible with what is actually stored in it, // the GC will still track it fine." for (int i = 0; i < (8 + 16) * 2; i++) { Console.WriteLine(*(ptr + i)); } var firstDate = *(DateTime *)ptr; Assert.AreEqual(DateTime.UtcNow.Date, firstDate); Console.WriteLine(firstDate); var firstDecimal = *(decimal *)(ptr + 8); Assert.AreEqual(123.456M, firstDecimal); Console.WriteLine(firstDecimal); var secondDate = *(DateTime *)(ptr + 8 + 16); Assert.AreEqual(DateTime.UtcNow.Date.AddDays(1), secondDate); Console.WriteLine(secondDate); var secondDecimal = *(decimal *)(ptr + 8 + 16 + 8); Assert.AreEqual(789.101M, secondDecimal); Console.WriteLine(secondDecimal); } var ptr2 = Marshal.AllocHGlobal(1000); var myPoco = new MyPoco(); Unsafe.Write((void *)ptr2, myPoco); }
public void UsageTest() { var model = TypeModel.Create(); // Dynamically create the model for MyPoco AddProperties(model, typeof(MyPoco)); // Display the Generated Schema of MyPoco Console.WriteLine(model.GetSchema(typeof(MyPoco))); var instance = new MyPoco { IntegerProperty = 42, StringProperty = "Foobar", Containers = new List <EmbeddedPoco> { new EmbeddedPoco { Id = 12, Name = "MyFirstOne" }, new EmbeddedPoco { Id = 13, Name = "EmbeddedAgain" } } }; var ms = new MemoryStream(); model.Serialize(ms, instance); ms.Seek(0, SeekOrigin.Begin); var res = (MyPoco)model.Deserialize(ms, null, typeof(MyPoco)); Assert.IsNotNull(res); Assert.AreEqual(42, res.IntegerProperty); Assert.AreEqual("Foobar", res.StringProperty); var list = res.Containers; Assert.IsNotNull(list); Assert.AreEqual(2, list.Count); Assert.IsTrue(list.Any(x => x.Id == 12)); Assert.IsTrue(list.Where(x => x.Id == 12).Any(x => x.Name == "MyFirstOne")); Assert.IsTrue(list.Any(x => x.Id == 13)); Assert.IsTrue(list.Where(x => x.Id == 13).Any(x => x.Name == "EmbeddedAgain")); }
public IActionResult About() { // tag::string[] // cache/retrieve from cache // a string, stored under key "CachedString1" var message = _cache.GetString("CachedString1"); if (message == null) { message = DateTime.Now + " " + Path.GetRandomFileName(); _cache.SetString("CachedString1", message); } ViewData["Message"] = "'CachedString1' is '" + message + "'"; // end::string[] // cache a generated POCO // store under a random key // tag::set[] var pocoKey = Path.GetRandomFileName(); _cache.Set(pocoKey, MyPoco.Generate(), null); ViewData["Message2"] = "Cached a POCO in '" + pocoKey + "'"; // end::set[] // tag::expiry[] var anotherPocoKey = Path.GetRandomFileName(); _cache.Set(anotherPocoKey, MyPoco.Generate(), new DistributedCacheEntryOptions { SlidingExpiration = new TimeSpan(0, 0, 10) // 10 seconds }); ViewData["Message3"] = "Cached a POCO in '" + anotherPocoKey + "'"; // end::expiry[] return(View()); }
public void Can_StoreObject() { object poco = new MyPoco { Id = 1, Name = "Test" }; Redis.StoreObject(poco); Assert.That(Redis.GetValue(Redis.NamespacePrefix + "urn:mypoco:1"), Is.EqualTo("{\"Id\":1,\"Name\":\"Test\"}")); Assert.That(Redis.PopItemFromSet(Redis.NamespacePrefix + "ids:MyPoco"), Is.EqualTo("1")); }