ObservableCollection needs three more methods/properties. Does some other collection have them? - mvvm

I have looked around a bit for this--can't find the proper collection
Here is the signature of my desired ViewModel. There are some interesting
alternatives out there David Hill's CollectionViewModel or ObservableDictionary(Of TKey, TValue) on codeplex. But for now, I would like a built-in collection (for SL4) that handles this. Thanks
public class myViewModel: INotifyPropertyChanged
{
public ObservableCollection<MyDataType> MyCollection;
private ObservableCollection<MyDataType> _myCollection;
public CurrentItem<MyDataType>() { return _myCollection.CurrentItem;}
public int GetCurrentIndex() { return _myCollection.CurrentIndex;}
public SetCurrentIndex(int Index) { _myCollection.CurrentIndex = Index;}

There isn't a built-in collection that provides this. However, you could just store the currentIndex value as a private int inside your ViewModel, and refer to it for the current index methods, as well as use it for CurrentItem<T>().

But do we really need something like this? You can always bind to "ViewModel.MyCollection/" to get the currently selected item

Related

what is the use of encapsulation here

What is the use of constructor here ?
This is script A :
[SerializeField]
private LobbyFunction _lobbyFunction;
public LobbyFunction LobbyFunction
{
get { return _lobbyFunction; }
}
This is script B:
private void Start()
{
GameObject lobbyCanvasGO = CanvasManager.Instance.LobbyFunction.gameObject;
if (lobbyCanvasGO == null) return;
}
what if I choose not to use the encapsulation ? no error , I guess .Any help would be greatly appreciated ,thanks!
edit: I guess using encapsulation here make the var read- only , only get... and therefore increase the security , people from outside can't change the value ,is it the ans?
This is no constructor but a Property
A property is a member that provides a flexible mechanism to read, write, or compute the value of a private field. Properties can be used as if they are public data members, but they are actually special methods called accessors. This enables data to be accessed easily and still helps promote the safety and flexibility of methods.
In your case it is for granting Read-Only access to the private backing field _lobbyFunction so no other class can change its value since only the class "A" containing _lobbyFunction itself is allowed to assign it.
Btw the way you have it it is equivalent to simply write
public LobbyFunction LobbyFunction { get; private set; }
without the need for a backing field. Then still only the containing class "A" itself is allowed to assign a value while everyone else can read it.

Best practice for setting default values for model properties in Domain Driven Design?

What's the best way to set default properties for new entities in DDD? Also, what's the best way to set default states for complex properties (eg. collections)?
My feeling is that default values should be in the models themselves as they are a form of business rule ("by default, we want X's to be Y & Z"), and the domain represents the business. With this approach, maybe a static "GetNew()" method on the model itself would work:
public class Person {
public string Name { get; set; }
public DateTime DateOfBirth { get; set; }
public bool IsAlive { get; set; }
public List Limbs { get; set; }
public static Person GetNew() {
return new Person() {
IsAlive = true,
Limbs = new List() { RightArm, LeftArm, RightLeg, LeftLeg }
}
}
}
Unfortunately in our case, we need the collection property to be set to all members of another list, and as this model is decoupled from its Repository/DbContext it doesn't have any way of loading them all.
Crappy solution would be to pass as parameter :
public static Person GetNew(List<Limb> allLimbs) {
return new Person() {
IsAlive = true,
Limbs = allLimbs
}
}
Alternatively is there some better way of setting default values for simple & complex model properties?
This is an instance of the factory pattern in DDD. It can either be a dedicated class, such as PersonFactory, or a static method, as in your example. I prefer the static method because I see no need to create a whole new class.
As far as initializing the collection, the GetNew method with the collection as a parameter is something I would go with. It states an important constraint - to create a new person entity you need that collection. The collection instance would be provided by an application service hosting the specific use case where it is needed. More generally, default values could be stored in the database, in which case the application service would call out to a repository to obtain the required values.
Take a look at the Static Builder in Joshua Bloch's Effective Java (Second Edition). In there, you have a static builder class and you chain calls to set properties before construction so it solves the problem of either having a constructor that takes a ton of arguments or having to put setters on every property (in which case, you effectively have a Struct).

Size of class with static member and accessor

I have a question regarding efficiency. I am writing an app for windows phone 7 and care a lot about memory, as I am using extremely long lists.
My question is, what is the size of a class that apart from using normal properties like int, string etc, has also a static int property and an accessor property for the forementioned static field? I need to use a static field, but cannot access it using databinding, thus my question.
An example:
private static int _property1;
public int Property1
{
get { return _property1; }
}
public int property2;
public int property3;
I would be really grateful for your answers.
Here you have static field _property1, which will be shared between all the instances of class, means it will create only one copy of _property1, if someone changes the value of static field it will reflect to every place. So it will increase the efficiency regardless you need to restrict the other users to set/reset static variables..

Bind /action/1,2,3 to List<int>

In my API, I'd like to have routes like GET /api/v1/widgets/1,2,3 and GET /api/v1/widgets/best-widget,major-widget,bob-the-widget
public class WidgetsController : MyApiController
{
public ActionResult Show(IEnumerable<int> ids)
{
}
public ActionResult Show(IEnumerable<string> names)
{
}
}
I've got routes set up to get me to the action, but I can't figure out how to turn 1,2,3 into new List<int>(){1, 2, 3} and so on. Of course, I could just take a string and parse it in my action, but I'd like to avoid going that route.
One thing that came to mind was to put something in the OnActionExecuting method, but then I wasn't sure exactly what to put in there (I could hack something together, obviously, but I'm trying to write something reusable.)
The main questions I have are how to know whether I need to do anything at all (sometimes the ValueProviders upstream will have figured everything out), and how to handle figuring out the type to cast to (e.g., how do I know that in this case I need to go to a collection of ints, or a collection of strings, and then how do I do that?)
By the way, I had the idea of implementing a ValueProvider as well, but got lost on similar questions.
I can't figure out how to turn 1,2,3 into new List(){1, 2, 3} and so on.
To avoid polluting each controller action that needs to receive this parameter I would recommend a custom model binder:
public class IdsModelBinder : DefaultModelBinder
{
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var result = base.BindModel(controllerContext, bindingContext);
var ids = bindingContext.ValueProvider.GetValue("ids");
if (ids != null)
{
return ids.AttemptedValue
.Split(',')
.Select(id => int.Parse(id))
.ToList();
}
return result;
}
}
and then register the model binder in Application_Start:
ModelBinders.Binders.Add(typeof(IEnumerable<int>), new IdsModelBinder());
and finally your controller action might look like this (and from what I can see in your question it already does look like this :-)):
public ActionResult Show(IEnumerable<int> ids)
{
...
}
and the custom model binder will take care for parsing the ids route token to the corresponding IEnumerable<int> value.
You could do the same with the IEnumerable<string> where you would simply remove the .Select clause in the corresponding model binder.
if your URL was
/api/v1/widgets/Show?names=best-widget&names=major-widget&names=bob-the-widget
This would bind neatly by itself :)
No need to override modelbinders in this case.
The querystring-variable names will bind to your Show-method_
public ActionResult Show(IEnumerable<string> names)
Hope this helps!
I'm relatively new to ASP.Net MVC and so I'm not sure if there is an easier way of doing this or not, however my approach would be to do something like the following:
public class WidgetsController : MyApiController
{
public ActionResult Show(string ids)
{
List<int> parsedIds = new List<int>();
foreach (var id in ids.Split(','))
{
parsedIds.Add(int.Parse(id));
}
return Show(parsedIds);
}
private ActionResult Show(List<int> ids);
}
You might also want to add some more sophisticated error handling for cases where the IDs entered can't be parsed, but thats the general approach I would use.

Reading integers from AppSettings over and over

Some I do quite a lot of is read integers from AppSettings. What's the best way to do this?
Rather than do this every time:
int page_size;
if (int.TryParse( ConfigurationManager.AppSettings["PAGE_SIZE"], out page_size){
}
I'm thinking a method in my Helpers class like this:
int GetSettingInt(string key) {
int i;
return int.TryParse(ConfigurationManager.AppSettings[key], out i) ? i : -1;
}
but this is just to save some keystrokes.
Ideally, I'd love to put them all into some kind of structure that I could use intellisense with so I don't end up with run-time errors, but I don't know how I'd approach this... or if this is even possible.
What's a best practices way of getting and reading integers from the AppSettings section of the Web.Config?
ONE MORE THING...
wouldn't it be a good idea to set this as readonly?
readonly int pageSize = Helpers.GetSettingInt("PAGE_SIZE") doesn't seem to work.
I've found an answer to my problem. It involves extra work at first, but in the end, it will reduce errors.
It is found at Scott Allen's blog OdeToCode and here's my implementation:
Create a static class called Config
public static class Config {
public static int PageSize {
get { return int.Parse(ConfigurationManager.AppSettings["PAGE_SIZE"]); }
}
public static int HighlightedProductId {
get {
return int.Parse(ConfigurationManager.AppSettings["HIGHLIGHT_PID"]);
}
}
}
Advantage of doing this are three-fold:
Intellisense
One breakpoint (DRY)
Since I only am writing the Config String ONCE, I do a regular int.Parse.
If someone changes the AppSetting Key, it will break, but I can handle that, as those values aren't changed and the performance is better than a TryParse and it can be fixed in one location.
The solution is so simple... I don't know why I didn't think of it before. Call the values like so:
Config.PageSize
Config.HighlightedProductId
Yay!
I know that this question was asked many years ago, but maybe this answer could be useful for someone. Currently, if you're already receiving an IConfiguration reference in your class constructor, the best way to do it is using GetValue<int>("appsettings-key-goes-here"):
public class MyClass
{
private readonly IConfiguration _configuration;
public MyClass(IConfiguration configuration)
{
_configuration = configuration;
}
public void MyMethod()
{
int value = _configuration.GetValue<int>("appsettings-key-goes-here");
}
}
Take a look at T4Config. I will generate an interface and concrete implementation of your appsettings and connectionstringsections of you web/app config using Lazyloading of the values in the proper data types. It uses a simple T4 template to auto generate things for you.
To avoid creating a bicycle class you could use the following:
System.Configuration.Abstractions.AppSettings.AppSetting<int>("intKey");
https://github.com/davidwhitney/System.Configuration.Abstractions