QuickGraph - How can I associate an Edge with a Class? (i.e. like you can with a Vertex) - quickgraph

Q1 - How can I associate an Edge with a Class? (i.e. like you can with a Vertex)
In my case there are various types of edges I want to be able to model. So my real question I guess is how can I associate some level of data with Edges (e.g. edge type).
The graph I was looking at using was: http://quickgraph.codeplex.com/wikipage?title=BidirectionalGraph&referringTitle=Documentation
thanks

An edge by default only connects two vertices on the graph. If you need more information associated with an edge (i.e. a "Relationship"), you can implement the IEdge<T> interfaces or subclass Edge<T>. Then, in your custom edge class you can store the information that's relevant to that edge.
i.e.
public class MyEdge<TVertex> : Edge<TVertex>
{
public string Name { get; set; }
public MyEdge(TVertex source, TVertex target) : base(source, target)
{
}
}
... later
var graph = new BidirectionalGraph<int, MyEdge<int>>();

You can also use the TaggedEdge class, which allows you to associate an arbitrary object with each edge.

Related

Custom DataAnnotations to Fluent-API

For my ef core appliation I created some classes which are constrained by DataAnnotations. i. e. I had to define a custom attribute which ensures that a IList will have at least one item in it.
Custom ValidationAttribute:
public class ListLengthAttribute : ValidationAttribute
{
public int Min { get; set; }
public int Max { get; set; }
public ListLengthAttribute()
{
Min = 0;
Max = int.MaxValue;
}
public override bool IsValid(object value)
{
IList listValue = value as IList;
if (listValue != null)
{
int listLength = listValue.Count;
return listLength >= Min && listLength <= Max;
}
return false;
}
}
The resulting class might look something like:
public class Dummy
{
[ListLength( Min = 1, ErrorMessage = "Each dummy should contain at least 1 foo." )]
public List<Foo> Foos { get; set; }
}
Now I want to completely move away from DataAnnotations and use the (ef-core) Fluent-API.
Is there any way to map the above constrain while using the ModelBuilder in my EntityFrameworkCore.DbContext class?
Maybe something like:
modelBuilder.Entity<Dummy>().Property( d => d.Foos ).MinLength(1);
You mainly need to understand the purposes of each of these. Data annotations are used to define rules and constraints for your model. These can be used for server side, client side and database validations (for the relevant parts). A custom ValidationAttribute can be used for server side validations.
Fluent API is used purely to translate into database configuration. Only attributes such as MaxLength(n) have a direct meaning in client, server and database side (varchar(n)). So, these attributes do have direct alternates in fluent API. However, EF will not automatically understand what your custom validation means in your database. For instance, in your case the validation seems to be translated to a one to one relation when max length is 1. So, for this perceptual example you can set a one to one in fluent API. EF can not check the code and understand the validation's intent in a situation like this.
For all other values of max length and min length, there is no mapping configuration that can be set in a database. Hence, fluent API can't have a mapping functionality for it. If the database you use does have a similar feature, you can look into the documentation of it's EF library for the mapping functionality.
Based on why you would like to move away from data annotations, what you are really looking for maybe fluent validations. You can look into this library and this git repo that provides a sample clean implementation of of models while using this library.

How to bind lists like an updating ForEach?

Here is a sample code:
public class Example3 {
class Point {
int x, y; // these can be properties if it matters
}
class PointRepresentation {
Point point; // this can be a property if it matters
public PointRepresentation(Point point) {
this.point = point;
}
}
Example3() {
ObservableList<Point> points = FXCollections.observableArrayList();
ObservableList<PointRepresentation> representations = FXCollections.observableArrayList();
points.forEach(point -> representations.add(new PointRepresentation(point)));
}
}
I have a data holder Point and a data representor PointRepresentation. I have a list of points and i would like that for each point in the list there would be an equivalent representation object in the second list. The code I gave works for the initialization but if there is any change later the above will not update.
What I am doing now is using a change listener to synchronize the lists (add and remove elements based on the change object) and it's OK but i am wondering if there's a simpler solution. I was looking for something like a "for each bind" that means: for each element in one list there is one in the other with the specified relation between them [in my case its that constructor]. In pseudocode:
representations.bindForEach(points, point -> new PointRepresentation(point));
Things I looked at: extractors for the list but that sends updates when a property in the objects they hold change and not when the list itself changes. So in my case if x in the point changes i can make an extractor that notifies it. Another thing I looked at is http://docs.oracle.com/javase/8/javafx/api/javafx/beans/binding/ListBinding.html, so maybe a custom binding does it but I don't know if it's simpler.
Also is there a similar solution for arrays instead of lists? i saw the http://docs.oracle.com/javase/8/javafx/api/javafx/collections/ObservableArray.html as a possibility.
The third-party library ReactFX has functionality for this. You can do
ObservableList<Point> points = FXCollections.observableArrayList();
ObservableList<PointRepresentation> representations = LiveList.map(points, PointRepresentation::new);
This will update representations automatically on add/remove etc changes to points.

Comparing properties in Gremlin

I have a simple graph, with parents and children being vertices.
Parents have the relationship "isParentOf" to their children.
The vertices all have one property: the "familyName".
I want to use gremlin to match all the parents whose child's familyName is different from theirs.
Note: I cannot use the Groovy syntax of Gremlin. I must use pure Java code only.
The GremlinPipeline should look like this:
find all parents
follow the "isParentOf" relationship and get all the children
filter the children through a PipeFunction that compares the parent's "familyName" with the child's "familyName"
The problem is in the last step. How to retrieve the parent's "familyName", when this pipeline step only has access to (what is coming from the previous step, that is to say) the children?
My answer:
Accessing previous steps of a GremlinPipeline in a filter's PipeFunction is not possible. BUT it is possible if you use a PipesFunction instead (note the 's' !).
Let's look at the javadoc here:
public PipesFunction extends PipeFunction{
public AsMap getAsMap();
}
So you should setup the GremlinPipeline like this:
find all parents
name that step as "theParent"
follow the "isParentOf" relationship and get all the children
filter the children with a PipesFunction like this:
.filter(new PipesFunction<Vertex,Boolean>()
{
public Boolean compute(Vertex child) {
return parentHasDifferentFamilyName(child);
}
private Boolean parentHasDifferentFamilyName(child){
Vertex theParent = getAsMap().get("theParent");
String theParentFamilyName = theParent.getProperty("familyName");
String childFamilyName = child.getParameter("familyName");
return !(childFamilyName.equals(parentFamilyName));
}
})
Note: in the step 4, we could retrieve the "theParent" vertex thanks to the getAsMap() method, and thanks to the step 2 (that implicitly filled the "As" map).

Getting a tree node using the name and not the position

How to get a child tree node using the name and not the range of the node in the child node list .
i found this method but it uses the position of the element in the children list:
selectedNode.getChildren().get(i).
Many thanks
The collection you receive by calling getChildren() is a standard Java collection IIRC and is not indexed by name. The only ways I can think of realizing this is to create your own Node implementation or to iterate over the collection (which I think is the easiest solution).
public Node getNodeByName(String name)
{
for (Node n : selectedNode.getChildren())
{
if (name.equals(n.getName())
{ return n; }
}
return null;
}

C# database access, Dapper, SQL and POCOs - programming design

Let's say we have a table in SQL represented in C# like this:
public class Product
{
public int ID { get; set; }
public string Name { get; set; }
public string Picture { get; set; } // filename of the picture, e.g. apple.jpg
public int CategoryID { get; set; }
}
Now we would query the database and retrieve the object, let's say with values like this:
ID = 1
Name = Yellow apple
Picture = apple.jpg
CategoryID = 25
All perfectly normal. The thing I'm meditating about at the moment is this: if I want to show a product, I need some additional info that wasn't queried from the database, like exact file path to the image, all we have is
apple.jpg
, but we need maybe something like
~/images/apple.jpg
So, I was thinking of 3 possibilities:
1.) add a new property to the class Product
public string PictureUrl
{
get
{
return "~/images/apple.jpg";
}
}
2.) specify the full url during performing of the presentation logic, let's say:
public void ShowProductDetails()
{
Product p = ProductRepo.GetProduct(id);
txtName.Text = p.Name;
imgPicture.ImageUrl = "~/images/" + p.Picture;
}
3.) use Decorator pattern
First approach seems wrong to me (even though I have been using it for quite a long time), because I'm trying to have a layered web application. I'm not sure hard-coding this is a good way to go.
Second approach is better, but worse in the sense it can't be easily reused. If I have multiple places where I'm doing the same thing and something changes, ... Maybe it would work if I specify some static constants holding the paths...
Third possibility seems quite complicated in terms of maintainability. The number of my classes would probably have to double. If I have 30 classes now, it would suddenly become 60 :/
What is the best/recommended way of doing things like this? If I add properties to my POCOs that aren't included in the db schema, I'm unable to use Dapper.Contrib or Rainbow and similar libraries, because even though "selects" work fine, I can't "insert" nor "delete". I have to hard-code the sql strings for every command which becomes really tedious after some time, when you're doing all the time the same stuff.
EDIT:
The solution from Govind KamalaPrakash Malviya is great, but can't be used every time. I need a way to solve this for any type of properties, even those more complex ones - for instance the number of photos of some album. It's a good idea to query the count of photos along with albums, but assign it to what? Create a decorated class using a Decorator pattern?
How do YOU solve this kind of architecture problems?
I think you should manipulate it in presentation layer because image path for presentation layer only. so use third one but make it easy using utility method
public class PathUtility
{
public static string ImageUrl(string imageName)
{
if(string.IsNullOrEmpty(imageName))
{
throw new Exception("Image name not valid!!");
}
else
{
return "YourImageDirectroyUrl" + imageName;
}
}
}
and use it easily
PathUtility.ImageUrl("apple.jpg");
I normally solve this by leaving the entity object as it is and creating an extra data container, which will either hold a reference to the corresponding entity or implement the corresponding properties from the entity object itself. In the latter case I use a mapping library (AutoMapper) to copy data from an entity to a the enhanced container.
The logic for filling the extra properties normally lies in a factory (or factory method). It's up to you, where you want to place this in your architecture. In a current project we are including them in our data access facade on client side, because we don't want to clutter the data access layer with too many DTO's. This of course means, that the data access layer still needs to support retrieving the extra properties. In your case an operation like int GetNumberOfPhotosForAlbum(Album album).
We found that the benefits outweigh the risk of an ever-growing contract of the data access layer, which of course might need to support many different calls like the example above instead of just EnhancedAlbum GetEnhancedAlbumWithAllKindsOfExtraProperties(long albumId). This might also become a performance problem in some scenarios, because of the overhead of an increased frequency of service calls. In the end you need to decide, what's best for your project.
I like this approach, because my entities (Album) stay untouched and I retain a clear separation of concerns between persistence, client logic and mapping.
Example:
class Album
{
string Name { get; set; }
}
class EnhancedAlbum
{
Album Album { get; set; }
int NumberOfPhotos { get; set; }
}
class EnhancedAlbumFactory
{
private MyDataService _dataService;
//include some means of constructing or (better) injecting the data service
EnhancedAlbum GetEnhancedAlbum(Album album)
{
return new EnhancedAlbum
{
Album = Album,
NumberOfPhotos = _dataService.GetNumberOfPhotosForAlbum(album);
};
}
}

Resources