Need access to a global generic list in all Silverlight views - silverlight

I have a generic list that gets loaded when a certain view is first used. Now I need this list to be accessed from all views in my project.
I've been experimenting using a Public Property in the App class. Problem is, I cannot seem to access that property from the other classes/view code (trying App.Current).
How can I access a public property generic list defined in the App class?
This is in VB.
Thanks.

The best way I've found to do this sort of thing is to create a static class (called "Globals" or "Config" or something like that), and create a static property which contains the list you want to reference. So it might look something like this:
public static class Globals
{
public static List<Customer> AllCustomers {get; set; }
}
Or in VB.NET:
Private Shared m_AllCustomers as List(of Customer)
Public Shared Property AllCustomers As List(of Customer)
Get
Return m_AllCustomers
End Get
Set(ByVal Value as List(of Customer))
m_AllCustomers = Value
End Set
End Property
And you can then get/set that property from wherever you need it:
Globals.AllCustomers = new List<Customer>();
Or:
Globals.AllCustomers = New List(Of Customer)
Of course, globals like this aren't generally a great idea, but sometimes they're the simplest solution. It's also a good idea, in my opinion, to put them in classes rather than in VB.NET modules, as it adds a namespace to the value, rather than having them in the global namespace. That helps a little bit with modularity.
If you insist on making this a property of App.Current, you need to cast App.Current to the actual class you've created, namely:
var allCustomers = ((App)App.Current).AllCustomers;
But I generally avoid adding these sorts of properties to my App class, because it makes them harder to test and breaks the idea of Single Responsibility.

Related

ObjectContext in ViewModel (EF + MVVM)

I'm currently writing my first MVVM application which uses EntityFramework for data access.
The Application relies heavly on the underlying database and has to add new Data to the DB in many cases.
However, I'm uncertain about whether or not it is a good idea to call the ObjectContext inside the ViewModel.
e.g.
public class SomeViewModel : ViewModelBase
{
public IEnumerable<User> AllUsers { get; private set; }
private void SomeMethod()
{
var __entities = new DatabaseEntities();
AllUsers = __entities.Users.Where(...).ToList();
}
}
I've seen solutions like this, but there are some question coming along with it.
For example how long the ObjectContext actually lives, or if one should prefer a single, global accessable ObjectContext.
Or should calls like those not be part of the VM in the first place?
Currently I can also imagine to implement like StaticHelpers for each DB table and use Methods like GetAllUsers().
In Josh Smith's sample Application about MVVM he uses a Repository thats injected in the Constructor of each VM.
public AllCustomersViewModel(CustomerRepository customerRepository)
Despite the fact that this has to be a common issue, I found no satisfying answer on how this issue is approached for smaller applications (best practice)?
In the descripton of the DbContext class on MSDN it states "Represents a combination of the Unit-Of-Work and Repository patterns", so it can act as your Repository layer, although it doesn't have to, and it is intended to be used for a "Unit of Work" which doesn't fit using a global one for the entire app. Besides keeping a single one around for everything could cause issues with cached data and other undesirable things (memory usage, etc...).
Hope this helps.

How do I assign properties of a child object based on a property from the parent using AutoFixture? [duplicate]

I'm using AutoFixture to generate data for a structure involving a parent object and complex child objects, like this:
public class Parent
{
public int Id { get; set; }
public string Name { get; set; }
public Child[] Children { get; set; }
}
public class Child
{
public string Name { get; set; }
public int ParentId { get; set; }
}
Is there a way to automatically set the property ParentId of the generated Child object to the id assigned to the parent? Right now my solution looks like this, which isn't very pretty:
var parent = fixture.Build<Parent>().Without(p => p.Children).CreateAnonymous();
parent.Children = fixture.CreateMany<Child>(10).ToArray();
foreach (var i in parent.Children)
{
i.ParentId = parent.Id;
}
It feels like there's a better way to do this that I am missing? I looked into creating a custom ISpecimenBuilder but didn't manage to solve it that way either.
AutoFixture is based on a set of rules and assumptions about the API it may be asked to work with. Consider that it's been created and compiled without any prior knowledge of the Child and Parent classes, or any other types in a given API. All it has to work with is the public API.
Think of AutoFixture as a very dim programmer who doesn't even understand your language (not even English). The more fool-proof you can make your API, the easier it will be to use AutoFixture with it.
The problem with circular references like the Parent/Child relationship described here is that it breaks encapsulation. You'll need to create at least one of the class instances initially in an invalid state. That it's difficult to make AutoFixture work with such an API should mainly be taken as a warning sign that the API might benefit from refactoring.
Additionally, the .NET Framework Design Guidelines recommends against exposing arrays as properties - particularly writable properties. Thus, with a better encapsulated design, the API might be much easier to work with, both for AutoFixture and yourself and your colleagues.
Given the API above, I don't see any way this can be made much easier to work with. Consider how to remove the circular reference and make collection properties read-only, and it will be much easier.
For the record, I haven't written an API with a circular reference for years, so it's quite possible to avoid those Parent/Child relations.

Using getApplicationContext() vs. referencing to custom Application class in Android

I've been researching ways to store global settings for my Android application and so far the best way seems to extend the Application class and store the shared data inside it, as described here. I've discovered that instead of using (CustomApplicationClass)getApplicationContext().getSomething() i can do the same thing by referencing directly to the static method inside the class like this: CustomApplicationClass.getSomething() and both ways work just fine.
Here's a piece from CustomApplicationClass:
public class CustomApplicationClass extends Application {
private static boolean something;
#Override
public void onCreate() {
[...]
}
public static boolean isSomething() {
return something;
}
public static void setSomething(boolean something) {
this.something = something;
}
}
Now, if i want to retrieve value of "something" variable somewhere in my code, say, from my application Activity, is there a difference between:
boolean var1 = ((CustomApplicationClass)getApplicationContext()).isSomething();
and
boolean var1 = CustomApplicationClass.isSomething();
? When running the application, both work fine. Is the second way safe to use, or is it inadvisable?
I've been researching ways to store global settings for my Android application and so far the best way seems to extend the Application class and store the shared data inside it, as described here.
Except that you're not doing that.
I've discovered that instead of using (CustomApplicationClass)getApplicationContext().getSomething() i can do the same thing by referencing directly to the static method inside the class like this: CustomApplicationClass.getSomething() and both ways work just fine.
Of course. You could just as easily had CustomApplicationClass extend Object, then executed CustomApplicationClass.getSomething(). You are gaining nothing by your current approach versus just using an ordinary singleton pattern in Java, and you are losing flexibility, as an application can only have one custom subclass of Application.
Is the second way safe to use, or is it inadvisable?
The first way is pointless, since your data member and methods are static.
Either:
Make your stuff in CustomApplicationClass not be static, and then use getApplicationContext().
Refactor CustomApplicationClass to not extend Application, and then use the static data member and/or accessor methods, or switch more formally to the Java singleton pattern.
Personally, I would go with option #2.
If you check the api of android.app.Application (http://developer.android.com/reference/android/app/Application.html) then you will find on Class Overview as following:
Base class for those who need to maintain global application state. You can provide your own implementation by specifying its name in your AndroidManifest.xml's tag, which will cause that class to be instantiated for you when the process for your application/package is created.
There is normally no need to subclass Application. In most situation, static singletons can provide the same functionality in a more modular way. If your singleton needs a global context (for example to register broadcast receivers), the function to retrieve it can be given a Context which internally uses Context.getApplicationContext() when first constructing the singleton.

Silverlight serialize object with cycles in object graph

I'm having an issue serializing objects when sending them to my WCF services. My classes look like this.
public class Foo
{
public Bar Bar { get; set; }
}
public class Bar
{
public Foo Bar { get; set; }
}
This causes a cycle in my object graph. I've fixed this on the server end by using the PreserveReferencesOperationBehavior. However, I still get an error when I try to serialize the objects in Silverlight.
While I can mark my objects with [DataContract(IsReference = true)], I'd prefer not to use this method because I have a large number of classes, many of which have over 100 properties and I don't want to have to add the [DataMember] attribute to each property.
Is there any other way to tell Silverlight to preserve references?
If it matters at all, I am using EntityFramework 4 with Code First.
The infered DataContract behaviour of the serializer is present to assist in the simple DTO scenarios. If you want to do it "properly" you should be using the DataContract and DataMember attributes.
When you find you have anything other than the most simple of scenarios you just need to do things properly. The correct and only way to handle circular references is with IsReference.
Lesson here is that helpful magic pixie dust only goes so far after that you just need to put in the graft. Sorry its not the answer you were looking for.

MVVM: Handling logical child objects of models in collections

Using MVVM, one type of ViewModels include the Model they represnt as a Field.
So I do have a CompanyModel and a CompanyViewModel that has one instance of CompanyModel.
This CompanyModel has a collection of Divisions belonging to it. So CompanyModel has a List (or some collection class).
Now the CompanyViewModel would want to represent these Divisions as an ObservableCollection<DivisionViewModel>; and you you could add new Divisions in the CompanyViewModel.
What is the best way ensure that the ObservableCollection and the Models collection stay in sync? So when I add a new DivisionViewModel and save it, it automatically saves its model to the CompanyModel's List<Division>?
I have more classes like this Parent/child relations so I would love something I could reuse or implement perhaps in a AbstractViewModel class.
Note: My ViewModels implement IEditableObject
Probably the easiest way to do this is to create a new class that inherits from ObservableCollection, and which takes a source list and various initialization and mapping functions as parameters. Its signature might look something like this:
public class SynchronizedObservableCollection<TDest, TSource> : ObservableCollection
{
public SynchronizedObservableCollection(
IList<TSource> source,
Func<TSource, TDest> newDestFunc,
Func<TDest, TSource> newSourceFunc),
Func<TSource, TDest, bool> mapSourceToDestFunc
{
// Initialize the class here.
}
}
You'd then want handle the CollectionChanged event, creating new Source instances when a new Destination instance got added, deleting existing Source instances when an existing Destination instance got deleted, that sort of thing. You'd use the "new" functions above to create new instances of the various entities, and you'd use the "map" functions above in various Linq queries that would allow you to figure out, say, which instance of a viewmodel your ObservableCollection mapped to a model in your List.
You would use it in your example above like so, perhaps:
var divisionViewModels = new SynchronizedObservableCollection(
company.DivisionList,
division => new DivisionViewModel(division),
divisionVm => divisionVm.Model,
(division, divisionVm) => divisionVm.Model == division);
The exact implementation is left as an exercise to the reader :-). But I've used classes like this with some success in previous projects. Just make sure you work up some good unit tests around it, so that you know you can rely on it, and don't have to spend a lot of time hunting through event-handling callstacks.

Resources