Basic JsonConvert.SerializeObject() stopped working on IoT Core - raspberry-pi

The follow code is a simplistic example of the issue that I'm having. This was working fine on IoT Core but now when debugging it jumps over var personJson line and never sets a value. I've tested this same code in a blank UWP app and ran it fine on my desktop.
I'm running Windows IoT Core v.10.0.16299.371 on a Raspberry Pi3 B. I'm sure the code was working on v.10.0.16299.309.
Anyone have an idea of what may be happening?
public sealed class StartupTask : IBackgroundTask
{
private BackgroundTaskDeferral deferral;
public void Run(IBackgroundTaskInstance taskInstance)
{
deferral = taskInstance.GetDeferral();
LoadPerson();
}
private void LoadPerson()
{
Person person = new Person();
person.firstName = "John";
person.lastName = "Doe";
person.age = 21;
var personJson = JsonConvert.SerializeObject(person, Formatting.Indented);
}
}
public sealed class Person
{
public string firstName { get; set; }
public string lastName { get; set; }
public int age { get; set; }
}

Related

Swagger-net breaks when using [FromUri] with a complex EF model

I'm using Swagger-Net in my .NET 4.5.1 WebAPI project and one of my API calls is causing the Swagger UI to spin forever on load before coming back with the error below.
Specifically, I found that using [FromUri] in combination with a complex EF entity that has references to other entities ends up causing this.
[HttpPost]
public APIResponse CreateSchool([FromUri]School school)
{
// save school object to db
}
public partial class School : IAuditableEntity,IEntity
{
public School()
{
this.Affiliations = new HashSet<Affiliation>();
this.SchoolAccreditations = new HashSet<SchoolAccreditation>();
this.SchoolAdultRoles = new HashSet<SchoolAdultRole>();
this.SchoolCareOptions = new HashSet<SchoolCareOption>();
this.SchoolDailySessions = new HashSet<SchoolDailySession>();
this.SchoolEligibilityRequirements = new HashSet<SchoolEligibilityRequirement>();
// ...more hashsets
[DataMember]
public int SchoolID { get; set; }
[DataMember]
public string Name { get; set; }
[DataMember]
public bool Active { get; set; }
//...more properties
}
}
Is there a way to still use FromUri and the EF model? Or do I need to change my API call signature?

Mapping from EF entities to gRPC Protobuf messages

I've started experimenting with gRPC and I would like to be able to map my db entities to protobuf messages using automapper. But I can't figure out how to map the repeated fields.
My message definitions looks like this:
message WorklistResponse {
repeated WorklistMessage Worklists = 1;
}
message WorklistMessage {
int32 WorklistId = 1;
repeated CollectionWorkMessage Work = 2;
}
message CollectionWorkMessage {
int32 WorkId = 1;
string AddressComment = 2;
}
And I'm trying to map from an entity that looks like this:
[Table("Worklist")]
public sealed class DbWorklist
{
public DbWorklist()
{
Work = new HashSet<DbWork>();
}
[Key]
public int WorklistId { get; set; }
public ICollection<DbWork> Work { get; set; }
}
Where the related entities DbWork is an abstract baseclass to DbCollectionWork and look like this:
[Table("Work")]
public abstract class DbWork
{
[Key]
public int WorkId { get; set; }
public int WorklistId { get; set; }
[ForeignKey(nameof(WorklistId))]
public DbWorklist Worklist { get; set; }
}
public sealed class DbCollectionWork : DbWork
{
[StringLength(255)]
public string AddressComment { get; set; }
}
I have two mappings configured:
cfg.CreateMap<DbWorklist, WorklistMessage>();
cfg.CreateMap<DbCollectionWork, CollectionWorkMessage>();
I can do this:
var worklists = dbContext.Worklists.Include(wl => wl.Work).ToList();
var worklistWork = autoMapper.Map<List<CollectionWorkMessage>>(worklists[0].Work);
var worklistResponse = new WorklistResponse
{
Worklists = { new WorklistMessage
{
Work = { worklistWork }
}}
};
This seems to be the only way I can set the Work property which is a protobuf3 RepeatedField<CollectionWorkMessage> that becomes a read-only property in the autogenerated protobuf class.
I would like to be able to construct my message using automapper.
I'm using AutoMapper 8.0, Grpc 1.19.0, Protobuf 3.7.0 and EF Core 2.2.4

How to access class properties using interface object which are not defined in the interface?

I am new to this forum. Now-days I am studying design patterns. I learnt about factory pattern and implemented simple example as shown below.
public interface IPlc
{
string Name { get; set; }
void Testping();
}
Public AbbPlc : IPlc
{
string Name { get; set; }
string slotnumber { get; set; }// Property relevant with this class
public void Testping()
{
console.writeline("ping executed successfully");
}
}
Public SiemensPlc : IPlc
{
string Name { get; set; }
string Racknumber { get; set; }// Property relevant with this class
public void Testping()
{
console.writeline("ping executed successfully");
}
}
//In Main Program
var objAbb = new IPlc() //Created object from interface
objAbb.Name = "46IC-PLC"; //Works OK
objAbb.slotnumber "3"; //Not works
var objSiemens = new IPlc() //Created object from interface
objSiemens.Name = "45IC-PLC"; //Works OK
objSiemens.Racknumber "5"; //Not works
Could you please tell me why these two methods doesn't work?
What I have to do to access properties from Interface object?
Do I need to use one more pattern with factory like decorator?

Why isn't my test method executing?

I have a fairly complex integration test that requires a lot of data in each distinct test case.
My test case class is as follows:
public class TestCases
{
public static IEnumerable MatchingCases
{
get
{
yield return
new SearchSetup
{
MinimumMatches = 1,
BulletinSetups = new List<BulletinSetup>
{
new BulletinSetup
{
ParameterSetups = new List<ParameterSetup>
{
new ParameterSetup
{
FieldName = "Number",
ParameterName = "#Number",
Value = "TBS1001" + DateTime.Now.ToLocalTime()
}
}
}
},
FilterValues = new Dictionary<string, object> { { "Number", "TBS1001" } }
};
}
}
}
The header of my test method is:
[Test, TestCaseSource(typeof(TestCases), "MatchingCases")]
public void Search_VariableFilter_NoAccountTeam_ResultIncludesExpected(SearchSetup searchSetup)
When I run the test, it returns inconclusive. When I step thru the code, I find that the MatchingCases property getter is being accessed, and the yield return statement executes w/o issue, but the test method itself is not called - or rather, not predictably.
See, I wrote this question up once already, then I tried moving the test class out of the testfixture scope. When I did that, the code executed once, and so I dumped my question. Then it stopped executing anymore...
Why isn't my test method being called?
Edit: Anticipating the question - these are the supporting classes being used:
public class ParameterSetup
{
public string ParameterName { get; set; }
public string FieldName { get; set; }
public object Value { get; set; }
}
public class BulletinSetup
{
public List<ParameterSetup> ParameterSetups { get; set; }
}
public class SearchSetup
{
public List<BulletinSetup> BulletinSetups { get; set; }
public int MinimumMatches { get; set; }
public Dictionary<string, object> FilterValues { get; set; }
}
Update - next day
After closing and reloading Visual Studio, and rerunning the test with no changes of any kind, the test code executes, repeatedly. I'm beginning to suspect this was a transitory glitch.
Since reloading VS the test method executes fine. I'm chalking it up as a glitch to close this question out.

1 to 1 Object Relations in EF4 Code First

I have a parent object book, and a property of that object is publisher. Everytime I ad a book, it is adding a new publisher, even if the publisher already exists. Can someone tell me how to add the book and instead of adding the publisher again, just reference an existing one? The code i am using is below... Thanks in advance!
public class Book
{
public int BookID { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public DateTime CreateDate { get; set; }
public virtual Publisher Publisher { get; set; }
}
public class Publisher
{
public int PublisherID { get; set; }
public string Address { get; set; }
}
public class SqlCEDataStore : DbContext
{
public DbSet<Book> Books { get; set; }
public DbSet<Publishers> Publishers { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.IncludeMetadataInDatabase = false;
}
}
public class TimeSinkRepository : IRepository<Book>
{
private static SqlCEDataStore context = new SqlCEDataStore();
public int Add(Book entity)
{
context.Books.Add(entity);
return context.SaveChanges();
}
}
var book = new Book()
{
Title = "New Title",
Description = "New Description",
CreateDate = DateTime.Now,
Publisher = new Publisher() { PublisherID = 1 }
};
var repository = new BookRepository();
var result = repository.Add(book);
The problem is in the line:
Publisher = new Publisher() { PublisherID = 1 }
Object context doesn't know that this is existing publisher. It is newly created entity so Object context will perform insert operation. You have to say object context that the publisher object is not newly created. One way to do that is modification of your Add method:
public int Add(Book entity)
{
context.Books.Add(entity);
// 0 means new one, other values mean existing one
if (entity.Publisher.PublisherID > 0)
{
context.ObjectStateManager.ChangeObjectState(entity.Publisher, EntityState.Unchanged);
}
context.SaveChanges();
}
It you can solve this by making sure the Publisher is attached to Publishers context before adding the Book entity (this way it knows it's a Publisher from the dbcontext and not a new one that it needs to add (again))
context.Publishers.Attach(book.Publisher); // This is only possible if the Publisher is not new
context.Books.Add(book);
the problem is in this line
Publisher = new Publisher() { PublisherID = 1 }
You should do a fetch method so something like this
- Get the Publisher you want from the context (eg where id = 1)
- Set the returned object as the publisher for your new book object
- The context should sort the rest out for you. when you save the book. (no need to mess with the object state manager)
Good luck, if you cant get this working put up some code of it and i will help you though it.