I am working on a project to convert multiple document sources to a MkDocs project. The MkDocs project file, MkDocs.yml, is a YAML document. I need to deserialize the existing pages so I can insert new .md pages and titles in that project through a C# console application.
Sample MkDocs.yml File
site_name: Knowledge Base
theme: readthedocs
pages:
- Home: 'index.md'
- User Guide:
- 'Writing your docs': 'user-guide/writing-your-docs.md'
- 'Styling your docs': 'user-guide/styling-your-docs.md'
- About:
- 'License': 'about/license.md'
- 'Release Notes': 'about/release-notes.md'
I used the DeserializeObjectGraph unit test supplied with the YamlDotNet to test the pages deserialization. The test always fails with this exception:
Exception Generated when Executing Attached Unit Test
Message: YamlDotNet.Core.YamlException : (Line: 8, Col: 15, Idx: 214) - (Line: 8, Col: 15, Idx: 214): Exception during deserialization
---- System.Runtime.Serialization.SerializationException : Property 'Home' not found on type 'YamlDotNet.Samples.DeserializeObjectGraph+Page'.
I am guessing there's some type of attribute I need to place on the Page class or one of its attributes. Does anyone have any experience deserializing a structure similar to this? If so, can you post a sample to give me some reference?
Here's the input DeserializeObjectGraph.cs I used:
using System;
using System.Collections.Generic;
using System.IO;
using YamlDotNet.Serialization;
using YamlDotNet.Serialization.NamingConventions;
using YamlDotNet.Samples.Helpers;
using Xunit.Abstractions;
namespace YamlDotNet.Samples
{
public class DeserializeObjectGraph
{
private readonly ITestOutputHelper output;
public DeserializeObjectGraph(ITestOutputHelper output)
{
this.output = output;
}
[Sample(
DisplayName = "Deserializing an object graph",
Description = "Shows how to convert a YAML document to an object graph."
)]
public void Main()
{
var input = new StringReader(Document);
var deserializer = new DeserializerBuilder()
.WithNamingConvention(new CamelCaseNamingConvention())
.Build();
var order = deserializer.Deserialize<Order>(input);
output.WriteLine("Order");
output.WriteLine("-----");
output.WriteLine();
foreach (var item in order.Items)
{
output.WriteLine("{0}\t{1}\t{2}\t{3}", item.PartNo, item.Quantity, item.Price, item.Descrip);
}
output.WriteLine();
output.WriteLine("Shipping");
output.WriteLine("--------");
output.WriteLine();
output.WriteLine(order.ShipTo.Street);
output.WriteLine(order.ShipTo.City);
output.WriteLine(order.ShipTo.State);
output.WriteLine();
output.WriteLine("Billing");
output.WriteLine("-------");
output.WriteLine();
if (order.BillTo == order.ShipTo)
{
output.WriteLine("*same as shipping address*");
}
else
{
output.WriteLine(order.ShipTo.Street);
output.WriteLine(order.ShipTo.City);
output.WriteLine(order.ShipTo.State);
}
output.WriteLine();
output.WriteLine("Delivery instructions");
output.WriteLine("---------------------");
output.WriteLine();
output.WriteLine(order.SpecialDelivery);
}
public class Order
{
public string Receipt { get; set; }
public DateTime Date { get; set; }
public Customer Customer { get; set; }
public List<OrderItem> Items { get; set; }
[YamlMember(Alias = "bill-to", ApplyNamingConventions = false)]
public Address BillTo { get; set; }
[YamlMember(Alias = "ship-to", ApplyNamingConventions = false)]
public Address ShipTo { get; set; }
public List<Page> Pages { get; set; }
public string SpecialDelivery { get; set; }
}
public class Page
{
public Dictionary<string, string> link;
}
public class Customer
{
public string Given { get; set; }
public string Family { get; set; }
}
public class OrderItem
{
[YamlMember(Alias = "part_no", ApplyNamingConventions = false)]
public string PartNo { get; set; }
public string Descrip { get; set; }
public decimal Price { get; set; }
public int Quantity { get; set; }
}
public class Address
{
public string Street { get; set; }
public string City { get; set; }
public string State { get; set; }
}
private const string Document = #"---
receipt: Oz-Ware Purchase Invoice
date: 2007-08-06
customer:
given: Dorothy
family: Gale
pages:
- Home: 'index.md'
- User Guide:
- 'Writing your docs': 'user-guide/writing-your-docs.md'
- 'Styling your docs': 'user-guide/styling-your-docs.md'
- About:
- 'License': 'about/license.md'
- 'Release Notes': 'about/release-notes.md'
items:
- part_no: A4786
descrip: Water Bucket (Filled)
price: 1.47
quantity: 4
- part_no: E1628
descrip: High Heeled ""Ruby"" Slippers
price: 100.27
quantity: 1
bill-to: &id001
street: |-
123 Tornado Alley
Suite 16
city: East Westville
state: KS
ship-to: *id001
specialDelivery: >
Follow the Yellow Brick
Road to the Emerald City.
Pay no attention to the
man behind the curtain.
...";
}
}
Related
I am currently using the Plugin.CloudFirestore.Sample project (link: https://github.com/f-miyu/Plugin.CloudFirestore) as a reference for creating my own application and would like to know how I should code my project to upload documents containing Firestore Maps and Firestore Arrays that have nested Firestore Maps then listen for document changes and display these changes using Xamarin Forms, Plugin.CloudFirestore, and Reactive. I would also like to know the maximum amount of Map conversions that can be handled at a time while converting from a Firestore Document to a .Net Model Class. To clarify, if the ExampleItem Class mentioned below contains another Model Class as a property, how would the class and reactive class viewmodel code look to upload/listen for changes. If anyone knows the answer to my question, it would be awesome if you could download the Plugin.CloudFirestore.Sample project, make the changes to the file, share a response explaining what you added, and share a download link.
public class TodoItem
{
public static string CollectionPath = "todoItems";
//Should I use DocumentConverters for converting to the "DataMap" and "DataMapArray" properties? If so what would the code for them look like?
[Id]
public string? Id { get; set; }
public string? Name { get; set; }
public string? Notes { get; set; }
public ExampleItem1? DataMap { get; set; }
public ObservableCollection<ExampleItem1>? DataMapArray { get; set; }
[ServerTimestamp(CanReplace = false)]
public Timestamp CreatedAt { get; set; }
[ServerTimestamp]
public Timestamp UpdatedAt { get; set; }
}
public class ExampleItem1
{
// Should I use [Id] on the Id property or any other Plugin.CloudFirestore.Attributes?
public string? Id { get; set; }
public string? Name { get; set; }
public ExampleItem2? DataMap { get; set; }
public ObservableCollection<ExampleItem2>? DataMapArray { get; set; }
}
public class TodoItemViewModel : BindableBase
{
public string? Id { get; }
public ReactivePropertySlim<string?> Name { get; set; } = new ReactivePropertySlim<string?>();
public ReactivePropertySlim<string?> Notes { get; set; } = new ReactivePropertySlim<string?>();
public ReactivePropertySlim<ExampleItem?> DataMap { get; set; } = new ReactivePropertySlim<ExampleItem?>();
public ReactivePropertySlim<ObservableCollection<ExampleItem>?> DataMapArray { get; set; } = new ReactivePropertySlim<ObservableCollection<ExampleItem>?>();
public TodoItemViewModel(TodoItem item)
{
Id = item.Id;
Name.Value = item.Name;
Notes.Value = item.Notes;
DataMap.Value = item.DataMap;
DataMapArray.Value = item.DataMapArray;
}
public void Update(string? name, string? notes, ExampleItem1? dataMap, ObservableCollection<ExampleItem1>? dataMapArray)
{
Name.Value = name;
Notes.Value = notes;
DataMap.Value = dataMap;
DataMapArray.Value = dataMapArray;
}
}
I want to include object in the main collection's child object, I tried below code but it didn't work.
Can someone help?
Here I want to include "Sample" object in "Template" when getting collection of "Instance".
public class Instance
{
public long IId { get; set; }
public string Name { get; set; }
public long TemplateId { get; set; }
public Template Template { get; set; }
}
public class Template
{
public long TId { get; set; }
public string Name { get; set; }
public long SampleId { get; set; }
public Sample Sample { get; set; }
}
public class Sample
{
public long SId { get; set; }
public string Name { get; set; }
}
string connectionString = "mongodb://localhost:27017";
var client = new MongoClient(connectionString);
var db = client.GetDatabase("test");
var instances = db.GetCollection<Instance>("Instances");
var resultOfJoin = instances.Aggregate()
.Lookup("Template", "TemplateId", "TId", #as: "Template")
.Lookup("Sample", "SampleId", "SId", #as: "Template.Sample")
.Unwind("Template")
.Unwind("Template.Sample")
.As<Instance>()
.ToList();
I found the solution by try and error, We need to add a local filed key with the object name as below,
.Lookup("Sample", "Template.SampleId", "SId", #as: "Template.Sample")
var resultOfJoin = instances.Aggregate()
.Lookup("Template", "TemplateId", "TId", #as: "Template")
.Lookup("Sample", "Template.SampleId", "SId", #as: "Template.Sample")
.Unwind("Template")
.Unwind("Template.Sample")
.As<Instance>()
.ToList();
Hello I am new to servers and REST API and am trying to extract data from a dynamically created table and the data does not sync with the data in the database.
I have an sql database from which I extracted an entity database in asp.net web project.
This is an example for GET of one entity class (exists in database):
public class EmployeeBL
{
private FSProject1Entities db = new FSProject1Entities();
public List<Employee> GetEmployees(string fname, string lname, string depID)
{
return GetEmployeeSearchResult(fname, lname, depID);
}
}
And this is an example for a method from a class such as I created in order to combine data from 2 tables:
public class ShiftEmployeeDataBL
{
private FSProject1Entities db = new FSProject1Entities();
private List<ShiftEmployeeDataBL> GetEmployeeByShiftID(int id)
{
List<ShiftEmployeeDataBL> shiftEmpData = new List<ShiftEmployeeDataBL>();
foreach (Employee emp in db.Employee)
{//build list... }
return shiftEmpData;
}
My problem is that db.Employee via this GET request path (ShiftEmployeeData) is old data and via Employee GET request is good data (assuming the data was updated via Employee path).
And vice versa - it would appear that if I update Employee via ShiftEmployeeData class, it would appear as good data for ShiftEmployeeData class and not update for Employee.
I have APIcontrollers for both classes.
what is happening? I feel like I am missing something.
I tried closing cache options in browser.
update with code for elaboration:
entity Employee:
public partial class Employee
{
public int ID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public int StartWorkYear { get; set; }
public int DepartmentID { get; set; }
}
employee update(auto generated by entity model code generation from db):
public void UpdateEmployee(int id, Employee employee)
{
Employee emp= db.Employee.Where(x => x.ID == id).First();
emp.FirstName = employee.FirstName;
emp.LastName = employee.LastName;
emp.StartWorkYear = employee.StartWorkYear;
emp.DepartmentID = employee.DepartmentID;
db.SaveChanges();
}
employeeshiftdata class (not a db table but still in the models folder):
public class EmployeeShiftData
{
public int ID { get; set; } //EmployeeID
public string FirstName { get; set; }
public string LastName { get; set; }
public int StartWorkYear { get; set; }
public string DepartmentName { get; set; }
public List<Shift> Shifts { get; set; }
}
employeeshift GET part of the controller:
[EnableCors(origins: "*", headers: "*", methods: "*")]
public class EmployeeShiftDataController : ApiController
{
private static EmployeeShiftDataBL empShiftDataBL = new EmployeeShiftDataBL();
// GET: api/EmployeeShiftData
public IEnumerable<EmployeeShiftData> Get(string FirstName = "", string LastName = "", string Department = "")
{
return empShiftDataBL.GetAllEmployeeShiftData(FirstName, LastName, Department);
}
//...
}
Would need to see the code that interacts with the database, especially the code that makes the updates.
If the changes are written with Entity Framework, are the models themselves properly related with navigational properties?
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public List<EmployeeShift> EmployeeShifts { get; set; }
// etc.
}
public class EmployeeShift
{
public int Id { get; set; }
public Int EmployeeID { get; set; }
public Employee Employee { get; set; }
// etc.
}
If those are good, and both models are covered by Entity Framework's context tracking, then both should be updated.
While using TestCaseSource in unit testing for multiple ServiceStack service clients, deserialized to a string format for the XmlServiceClient does not match the deserialized for JsonServiceClient or JsvServiceClient. The serialization is using the SerializeAndFormat extension method from the ServiceStack.Text.TypeSerializer class.
Using the OnDeserializing fuctionality doesn't seem to provide the same formatted string, as it is missing the default values.
The same JsConfig scope is used with excludeDefaultValues set to false prior to calling the SerializeAndFormat method. The Json and Jsv results match, including the default values, but the xml service client's result does not include them. The object that is not deserializing correctly is a property of a property of the response object and is decorated with this attribute [Serializable].
The response is decorated with [DataContract], [Serializable] and the property objects are both decorated with [Serializable].
How should the objects be decorated so that the serialized response is consistent for all three clients?
[DataContract]
[Serializable]
public class CustomResponse : IMeta, IHasResponseStatus
{
[DataMember(Order = 5)]
public Dictionary<string, string> Meta { get; set; }
[DataMember(Order = 100)]
public DataView Result { get; set; }
[DataMember(Order = 1)]
public Summary Summary { get; protected set; }
[DataMember(Order = 8)]
public ResponseStatus ResponseStatus { get; set; }
}
[Serializable]
public class Summary : IResponseStatus
{
public IEnumerable<HateoasLinks> Links { get; set; }
[DataMember(Order = 5)]
public string Message { get; protected set; }
[DataMember(IsRequired = false)]
public int? Offset { get; set; }
[DataMember(IsRequired = false)]
public int? Limit { get; set; }
public string RequestFormat { get; private set; }
[DataMember(IsRequired = false)]
public int? Results { get; protected set; }
public Parameters Params { get; protected set; }
}
[Serializable]
public class Parameters
{
[DataMember(Order = 1)]
public string Status { get; set; } = "OK";
public string Sort { get; set; } = string.Empty;
public string Filter { get; set; } = string.Empty;
public DateTime? StartDate { get; set; }
public DateTime? EndDate { get; set; }
[DataMember(EmitDefaultValue =true)]
public int? Offset { get; set; } = 0;
public int? Limit { get; set; } = 10;
[OnDeserializing]
void OnDeserializing(StreamingContext context)
{
if (!this.Limit.HasValue)
{
this.Limit = 10;
}
if (!this.Offset.HasValue)
{
this.Offset = 0;
}
}
}
results in:
{
summary:
{
links: [],
message: OK,
params:
{
status: OK,
sort: "",
filter: "",
},
isSuccess: False,
status: 200,
requestTime: 2014-03-14,
currentPage: 1
},
result:
{
}
}
but should be
params:
{
status: OK,
sort: "",
filter: "",
offset: 0,
limit: 10
}
ServiceStack uses .NET DataContract Serializer for XML so it’s limited to the behaviour and features it provides.
JsConfig only applies to ServiceStack implemented Text Serializers, primarily designed for JSON/JSV and partially used by CSV.
I'm having problems resolving this error message. I've looked at some other answers on here and changed some things but I still receive this error:
Newtonsoft.Json.JsonSerializationException: Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[Clocker.Models.PeopleLocationForUser]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
This is my class:
namespace Clocker.Models
{
public class PeopleLocationForUser
{
string locationPeople { get; set; }
public users users { get; set; }
}
public class users
{
public int EB_Counter { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public int TATokenValue { get; set; }
}
}
This is the method that errors on the deserialize line:
public static async Task<PeopleLocationForUser> GetPeopleLocationForUser(string UserName, int LocationId)
{
Uri uri = new Uri(URL + "GetPeopleLocationForUser" + "?username=" + UserName + "&locationid=" + LocationId);
HttpClient myClient = new HttpClient();
var response = await myClient.GetAsync(uri);
var content = await response.Content.ReadAsStringAsync();
var test = JsonConvert.DeserializeObject<List<PeopleLocationForUser>>(content);
//return something when it's working
return null;
}
This is the start of the Json data:
{"result":true,"locationPeople":[{"EB_Counter":101,"FirstName":"RSS","LastName":"13.11.1","TATokenValue":"TS_101_1_RSS_SWIPE"},{"EB_Counter":102,"FirstName":"RSS","LastName":"13.11.2","TATokenValue":"TS_102_1_RSS_SWIPE"},{"EB_Counter":93,"FirstName":"RSS","LastName":"13.7.1","TATokenValue":"TS_93_1_RSS_SWIPE"},{"EB_Counter":94,"FirstName":"RSS","LastName":"13.7.10","TATokenValue":"TS_94_1_RSS_SWIPE"},{"EB_Counter":95,"FirstName":"RSS","LastName":"13.8.2","TATokenValue":"TS_95_1_RSS_SWIPE"},{"EB_Counter":99,"FirstName":"RSS","LastName":"13.9.2","TATokenValue":"TS_99_1_RSS_SWIPE"},
This is what my Json data looks like when it arrives:
I hope you can help. The end result is that I'm trying to get this data into a list so I can use it in a Xamarin ListView.
You are receiving list and in the class you are expecting just one instance of user, this is how the class should be:
public class LocationPeople
{
public int EB_Counter { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string TATokenValue { get; set; }
}
public class RootObject
{
public bool result { get; set; }
public List<LocationPeople> locationPeople { get; set; }
}
var test = JsonConvert.DeserializeObject<RootObject>(content);