How can I work out this part of a class diagram? - c#

For school homework I'm supposed to work out a class diagram in C#. Everything went smoothly, but I'm struggling with the constructor for the Track part.
So I think I have to convert a SectionTypes -> Section to put it in the LinkedList, but this doesn't seem logical to me, or am I missing something? Should I convert it in any way or is my overall code for Section wrong?
Here is the class diagram
Here is the part of Section:
namespace Model
{
public enum SectionTypes { Straight, LeftCorner, RightCorner, StartGrid, Finish }
internal class Section
{
public SectionTypes SectionType { get; set; }
}
}
And finally here is where I'm trying to make the constructor, Track:
namespace Model
{
internal class Track
{
public string Name { get; set; }
public LinkedList<Section> Sections { get; set; }
public Track(string name, SectionTypes[] sections)
{
Name = name;
// set Sections here
}
}
}
The error that I get is CS1503, when I try to add anything to Sections in the front, which means the types aren't the same.
Thanks for reading, and thank you for helping in advance!

Here's what I did. By the way, I renamed the SectionTypes enumeration to SectionType (that way, it reads SectionType.Finish, not SectionTypes.Finish).
First I created the enum the same as you:
public enum SectionType
{
Straight,
LeftCorner,
RightCorner,
StartGrid,
Finish,
}
and the Section class pretty much the same way:
public class Section
{
public SectionType SectionType { get; set; }
}
I'm not sure why the class diagram is laid out the way it is, but you need to translate a SectionType to a Section in order to get it to work. That's pretty easy; a Section is a pretty stupid/simple wrapper around a single SectionType. So, things end up looking like:
public class Track
{
public string Name { get; set; }
public LinkedList<Section> Sections { get; set; } = new LinkedList<Section>();
public Track(string name, SectionType[] sections)
{
Name = name;
foreach (var section in sections)
{
Sections.AddLast(new Section { SectionType = section });
}
}
}
Note that I construct the Sections LinkedList. It can either be done the way I show, or it could be done in the constructor. But, the magic is to convert the incoming SectionType[] sections into a collection of Section type. I'm sure that there is a way to do this with LINQ (though I don't have a lot of experience with the LinkedList collection). But, doing it explicitly like this makes it more clear.

Related

C# Iterating through list of objects

First post on here so go easy on me!
I'm trying to deserialize a json document into a list of objects.
So far I've got two classes - one which contains the data structure:
class Server
{
public string hostname { get; set; }
public string ipAddress { get; set; }
public string monitoring { get; set; }
public int pollingInterval { get; set; }
}
The other that contains the collection
class ServerCollection
{
public List<Server> servers { get; set; }
}
In the applicaion I do a simple ReadAllText and I'm deserializing the object like so
private ServerCollection _servers;
string json = File.ReadAllText(#"c:\users\admin\desktop\server.monitoring\servers.json");
_servers = JsonConvert.DeserializeObject<ServerCollection>(json);
I'm struggling to iterate over this using a foreach... Can't think what I'm missing.
Severity Code Description Project File Line Suppression State
Error CS1579 foreach statement cannot operate on variables of type 'ServerCollection' because 'ServerCollection' does not contain a public instance definition for 'GetEnumerator' Server.Monitoring.Service.Core C:\Code\Admin\Server.Monitoring\Server.Monitoring.Service.Core\GetSystemHealth.cs 25 Active
Any ideas on what I've missed?
Thanks in advance!
class ServerCollection
{
public List<Server> servers { get; set; }
}
Is not a collection but Servers is, you need to iterate over that.
foreach (var server in _servers.servers)
{
//do something with server
}
Your ServerCollection class does not implement the IEnumerable interface. You have two options:
Have ServerCollection implement that interface (i.e., public class ServerCollection : IEnumerable<Server> and add the necessary methods)
Loop over _servers.servers instead
The second option is the easier one to get you going, but implementing the interface may have other benefits down the road

How to retrieve property from GameSparks inside Unity

I am going crazy... I am missing something and I can't see what?!?!
I have created a property called "GAME_SETTINGS" inside the gameSparks admin area and have included this in it:
{
"AppVersionIOS": 1,
"AppVersionAndroid": 1
}
I am then trying to retrieve it inside Unity like this:
new GameSparks.Api.Requests.GetPropertyRequest().SetPropertyShortCode("GAME_SETTINGS").Send((response) => {
if (!response.HasErrors) {
Debug.Log("Setting Achieved: "+response.JSONString);
} else {
Debug.Log("Error Getting Settings");
}
});
I can see that I am getting the settings in my Debug.Log:
Setting Achieved: {"#class":".GetPropertyResponse","property":{"AppVersionIOS":1,"AppVersionAndroid":1},"requestId":"XXXXXXXXXXXXXXX","scriptData":null}
My question is though... How do I get the properties AppVersionIOS and AppVersionAndroid inside an Dictionary so I can call on them from other scripts...
Really hoping for help in this matter and thanks in advance :-)
I actually work for GameSparks and noticed your question so set up an account to answer you.
The property values returned in the JSON are of nullable type : https://msdn.microsoft.com/en-us/library/1t3y8s4s.aspx
Best practice is to parse the values before they are cached in a Dictionary or otherwise.
The following code should allow you to get those properties, then you may store them in a dictionary as you see fit.
public void GetProperties()
{
new GameSparks.Api.Requests.GetPropertyRequest()
.SetPropertyShortCode("GAME_SETTINGS")
.Send((response) =>
{
if (!response.HasErrors)
{
print(response.JSONString);
int androidProperty = (int)response.Property.GetInt("AppVersionAndroid");
int IOSProperty = (int)response.Property.GetInt("AppVersionIOS");
print("AndroidProperty:" + androidProperty);
print("IOSProperty:" + IOSProperty);
}
else
{
Debug.LogWarning(response.JSONString);
}
});
}
Hopefully this solves your problem. If you have any other questions please feel free to head to our website and log a ticket with us.
Regards, Patrick.
Notice: This answer assumes that the API doesn't have a way of converting this into a nice object which you can easily manipulate / parse, so it converts it itself using some class. It's however very likely that your API offers such a function somewhere, so you'd be better be looking in the documentation again. I guess it's somewhere near https://api.gamesparks.net/#getpropertyrequest .
You have the JSON document already, all you have to do is parse it. That'd be easier in a JavaScript file than in C#, but you can also use the JsonUtils class there, see http://docs.unity3d.com/Manual/JSONSerialization.html . Let http://json2csharp.com/ convert that JSON to a class layout for you and you get
public class Property
{
public int AppVersionIOS { get; set; }
public int AppVersionAndroid { get; set; }
}
public class RootObject
{
public string __invalid_name__#class { get; set; }
public Property property { get; set; }
public string requestId { get; set; }
public object scriptData { get; set; }
}
Now just take the string and serialize it into an RootObject.
new GameSparks.Api.Requests.GetPropertyRequest().SetPropertyShortCode("GAME_SETTINGS").Send((response) => {
if (!response.HasErrors) {
Debug.Log("Setting Achieved: "+response.JSONString);
//Serialization
var info = JsonUtility.FromJson<RootObject>(response.JSONString);
//Print the AppVersionIOS property
Debug.Log("App Version iOS: " + info.Property.AppVersionIOS);
} else {
Debug.Log("Error Getting Settings");
}
});
You might need some mofication in the data types of your class (e.g. make object scriptData to string scriptData if there can be an actual string in it), but that should be it. Have fun.

Create code from Pattern Graph

I got a graph from which I need to set some propery in objects. Im adding an example on which I will explain it better:
Assuming I have the following class:
public class Person
{
public int Account { get; set; }
public string BirthCity { get; set; }
public string Name { get; set; }
public Family Family { get; set; }
}
Each Person that gets to the DAL will automatically be assigned with Status according to that algorythm. My real problem is much more complex, but this example does explain it well I think.
The graph describes scenarios and I need to translate it to code. I want my solution to be as flexible to changes as possible. Ofcourse writing ifs and switch case is the easiest yet its not a good solution.
One idea I had was creating an Xml file suting the scenarios, but I think that it might not be that good.
Does anyone have any Ideas about this issue?

C# Complex Property Setter option

I have an ASP.Net MVC 5 (C#) application and I'm giving my users the ability to like posts and comments.
for this I have a Model called Likes with the following Properties:
public class Like
{
public Like()
{
this.CreatedUTC = System.DateTime.UtcNow;
this.isActive = true;
}
public long id { get; set; }
public string UserID { get; set; }
public bool isActive { get; set; }
public LikeType Type { get; set; }
public DateTime CreatedUTC { get; set; }
}
Type is an enum and it can be either Comments or Posts. I've also added the following Navigation Property to both Post Model and Comment Model:
public virtual ICollection<Like> Likes { get; set; }
My question is, can I have a setter function in the above line of code where it would automatically set Comments and Posts for the Like type? I know I can use the Value variable in the Setter but using Google I couldn't find how to use it for complex types as I have above (Like).
I'm sure this would be a better way of doing this than in the repository manually set that enum every-time I'm going to save a like.
UPDATE:
Seeing how we're starting a nice little conversation about this Questions, I will throw another alternative in the mix.
How about two Tables with a base class of Like, one CommentLikes and the other PostLikes Seeing that the size of this table will grow really fast, I'm thinking separating them would possibly be a good thing, Right?
I'd rather drop the "LikeType" and either have Comment and Post entity in the Like entity and distinguish by one of them being null or introduce two new entities
public class CommentLike
{
public Comment Comment { get; set; }
public Like Like { get; set; }
}
which holds a comment and a like and PostLike which holds a Post and a Like. The Comment then looks like this
public Comment
{
public virtual ICollection<CommentLike> { get; set; }
}
Another alternative is to create separate tables for comment and post likes. While what you ask for is definitely doable I would recommend more verbose but simpler solution which will result in code that is easier to maintain and has less bugs. Is there any specific reason you want to have a LikeType property?
I had same problem but didnt encounter an easy way.
class Post{
public virtual ICollection<Like> Likes {set;get;}
}
class Comment{
public virtual ICollection<Like> Likes {set;get;}
}
Then:
class Like{
//....
}
You dont need a bi-directional relationship. Do you have a case where you need to query Likes table? and if you do, you will have to manage parsing it as ENUM somewhere which can be an extension method.
EF will create Post_Id and Comment_Id implicityly in your table design. You wont be able to query it but you wont need to. IN my experience i never needed to.
My question is, can I have a setter function in the above line of code
where it would automatically set Comments and Posts for the Like type?
I assume you are using T4 template or the classes that were generated by EF are partialthen you can extend it by creating another partial class and a wrapper property for Likes
// Backing field
private ICollection<Like> _likesWrapper;
public ICollection<Like> LikesWrapper {
get {
// Lazy loading
if(_likes == null)
{
// Just create a new list or load it from the database.
_likes = new List<Like>();
}
return _likes;
}
set {
foreach(var val in value)
{
//Set the comment and posts
}
Likes = value;
}

How to model entities to enforce a data models constraints at compile time?

I have the below data model that constrains ItemTypes with a subset of Events. Each ItemType has a valid set of Events, this is constrained in the ItemEvent table. For example, a Video can be { played, stopped, paused }, an Image can be { resized, saved, or shared }, and so on.
What is the best way to reflect this constraint in the Entity model so that I can get compile time assurance that an Event used is valid for a particular Item? Specifically, I am refactoring the AddItemEventLog method:
public void AddItemEventLog(Item item, string ItemEvent)
{
//
}
Obviously, this is a contrived example, just trying illustrate-- it allows a developer to pass in any ItemEvent string they desire. Even if I create an enumeration based on ItemEvent resultset, there isnt anything in the entity model to prevent a developer from passing in ItemEvent.Resize with an Item of type Video.
I have Item as the base class of Video, and I have tried to override an enum but now know that is not possible. I am less interested in checking for the validity of the Event at runtime, as I already will throw an exception when the DB raises a FK violation. I want to nip it in the bud at coding time if possible :)
Currently have classes modeled like this but open to any modifications:
//enums.cs
public enum ItemType : byte
{
Video = 1,
Image = 2,
Document = 3
}
//item.cs
public class Item : BaseModel
{
public int ItemId { get; set; }
public ItemTypeLookup.ItemType ItemType { get; set; }
public string ItemName { get; set; }
}
//video.cs
public class Video : Item
{
public string Width { get; set; }
public string Height { get; set; }
public string Thumb { get; set; }
}
I think that Code Contracts may be the only way to enforce something like this at compile time. Outside of compile time checks, writing unit tests to ensure the correct functionality is the next best thing!

Categories

Resources