I've created a MvxTableViewCell subclass that I plan to reuse at many points of my App, so I want to delegate the binding task to the creator of the cell.
So far, I got this working based on some N+1 tutorial examples, mainly this code from N=17-Collect a Bull part 3 tutorial.
So at this point, creating a cell looks like this:
return new SubtitleCell("TitleText Name; SubtitleText Subject.Descripcion"))
But I don't really like bindings defined in strings, because I usually refactor a lot and this may cause troubles in the near future, so I decided to declare the binding like a normal bindable view like this:
var cell = new SubtitleCell();
var set = cell.CreateBindingSet<SubtitleCell, SubjectGroup>();
set.Bind().For(c => c.TitleText).To(g => g.Name);
set.Bind().For(c => c.SubtitleText).To(g => g.Subject.Descripcion);
set.Apply();
return cell;
This now works like before and now it's refactor-safe, but it's six times the lines of code that I had before and the binding must be defined when the instance of the cell is already created.
I think that it can be done using MvxBindingDescription because the binding text used in the first example is parsed to a IEnumerable<MvxBindingDescription>, but I was unable to find an example or documentation about it.
Can anyone point me to the right direction?
Thanks.
EDIT:
LoC is not my biggest concern, but having to instantiate each cell before defining the binding, I'd be happy to have something like this:
var set = Mvx.CreateBindingSet<SubtitleCell, SubjectGroup>();
set.Bind().For(c => c.TitleText).To(g => g.Name);
set.Bind().For(c => c.SubtitleText).To(g => g.Subject.Descripcion);
So I can apply it later maybe like this:
var cell = new SubtitleCell();
cell.ApplyBindingSet(set);
Is there something that can be done moving this way?
UPDATE:
Just noticed that the second binding example fills my log console with this error:
MvxBind:Warning: 0.40 Unable to bind: source property source not found
Cirrious.MvvmCross.Binding.Parse.PropertyPath.PropertyTokens.MvxPropertyNamePropertyToken on null-object
Both samples seems to produce the same behavior, but the warning errors only appear using fluent binding.
MvxBindingDescription won't really help with refactoring - it operates just above the text or fluent bindings and just below the reflection level of the binding engine.
If you want Expression based binding for refactoring, then you have to use Fluent binding and pay the penalty of the extra lines of code (if you consider that a penalty)
Related
In some cases, I would like to add contextual information to a message (for instance currently authenticated user), without having to include it in the message template.
I would like to accomplish this :
logger.Information("Doing stuff {Foo} with the thing {Bar}. {User}", foo, bar, user)
but without the {User} in the template.
I already know about LogContext but that seems overkill when adding contextual information to just one event.
I also know I can use the low-level API logger.Write(LogEvent evnt) to actually control which properties are included, but that seems like a bit too much code for what I am trying to accomplish.
I'm pretty sure there is a short and elegant way that is super obvious, but I haven't found it :)
UPDATE :
I found out only afterwards that this question is more or less similar : Add custom properties to Serilog
I could figure it out on my own!
You can use the fluent method .ForContext(propertyName, propertyValue) on a single call to one of the .LogXXX() methods.
For instance :
logger.ForContext("User", user)
.Information("Doing stuff {Foo} with the thing {Bar}", foo, bar)
The property added to the event only apply to the event, and they are no longer present on the next call to the logger.LogXXX() method
UPDATE
The article by Nicholas Blumhardt explains it quite well : Context and correlation – structured logging concepts in .NET (5)
If you're using the generic Microsoft ILogger you can use BeginScope;
using (_logger.BeginScope(new Dictionary<string, object> { { "LogEventType", logEventType }, { "UserName", userName } }))
{
_logger.LogInformation(message, args);
}
This is discussed here; https://blog.rsuter.com/logging-with-ilogger-recommendations-and-best-practices/
I am refactoring an MVC 3 application, and moved a set of similar items into a partial view so I can keep that template DRY. Since the pieces don't all have the exact same properties, I am creating anonymous types like this:
var model1 = new { Description = "description 1", Message = "message 1" }
and passing them to the partial view like so:
#Html.Partial("_Partial", model1)
The partial view is then attempting to render certain blocks based on existence of a specific property, i.e.
#if (Model.Description != null)
{
#Model.Description
}
My issue is that even though I can see and navigate the Model object in the watch window during execution, I get a RuntimeBinderException in the if test that states 'object' does not contain a definition for 'ShowApplied'. I can obtain the values through reflection by calling (Model.GetType().GetProperty("ShowApplied").GetValue(Model)), but would much rather use the format shown in my code sample. I have been unable to find a clean solution...
How can I pass an anonymously-typed object to a partial view and access its properties directly? I feel like there is something simple I'm missing...
Why am I able to see the Model properties while debugging, but not access them from code?
EDIT
I am specifying #model dynamic.
Using an interface requires creating non-anonymous types because, as this answer explains,
An anonymous type cannot be cast to any interface or type except for object.
Insights from the comments (thank you) imply I have 2 options, since (as the answer to the linked question points out),
Anonymous types are internal, so their properties can't be seen outside their defining assembly.
and therefore are inaccessible to the Razor binding engine.
Use #Html.DisplayFor("amount") and deal with not having IntelliSense, reference lookups, etc.
Create classes that implement a common interface and bind my partial view to that interface.
I am trying to use Dart to tersely define entities in an application, following the idiom of code = configuration. Since I will be defining many entities, I'd like to keep the code as trim and concise and readable as possible.
In an effort to keep boilerplate as close to 0 lines as possible, I recently wrote some code like this:
// man.dart
part of entity_component_framework;
var _man = entity('man', (entityBuilder) {
entityBuilder.add([TopHat, CrookedTeeth]);
})
// test.dart
part of entity_component_framework;
var man = EntityBuilder.entities['man']; // null, since _man wasn't ever accessed.
The entity method associates the entityBuilder passed into the function with a name ('man' in this case). var _man exists because only variable assignments can be top-level in Dart. This seems to be the most concise way possible to use Dart as a DSL.
One thing I wasn't counting on, though, is lazy initialization. If I never access _man -- and I had no intention to, since the entity function neatly stored all the relevant information I required in another data structure -- then the entity function is never run. This is a feature, not a bug.
So, what's the cleanest way of using Dart as a DSL given the lazy initialization restriction?
So, as you point out, it's a feature that Dart doesn't run any code until it's told to. So if you want something to happen, you need to do it in code that runs. Some possibilities
Put your calls to entity() inside the main() function. I assume you don't want to do that, and probably that you want people to be able to add more of these in additional files without modifying the originals.
If you're willing to incur the overhead of mirrors, which is probably not that much if they're confined to this library, use them to find all the top-level variables in that library and access them. Or define them as functions or getters. But I assume that you like the property that variables are automatically one-shot. You'd want to use a MirrorsUsed annotation.
A variation on that would be to use annotations to mark the things you want to be initialized. Though this is similar in that you'd have to iterate over the annotated things, which I think would also require mirrors.
Is there any example of binding any sort of collection to a TableLayout in android? I keep receiving the message/warning that binding failed for attribute ItemSource LocationQuantities. All of the other bindings to the view model work as normal, but the list doesn't bind to the TableLayout. At first I thought my problem was binding to a dictionary but I was able to bind to a dictionary with other Mvx layouts (listview etcs.)
I can't seem to find in any of the N+ code examples or anywhere else on the web where a TableLayout is actually used in an mvvmcross app. I'm sure I'm just doing something stupid simple wrong here.
<Mvx.MvxTableLayout
p1:id="#+id/PartLocationQtyTable"
p1:layout_width="fill_parent"
p1:layout_height="wrap_content"
p1:layout_below="#id/PartDetailPriceLayout"
p1:padding="5.0dp"
local:MvxBind="ItemSource LocationQuantities"
/>
I've tried the above as well as with a custom template. The above example just uses a list of strings.
Any help would be appreciated
The only obvious problem I can see with your code is that it uses ItemSource whereas all the list-based layouts use ItemsSource - see MvxTableLayout.cs#L89
Beyond that, I guess you'll also want to make sure that your templates for TableLayout are TableRows - so that they can be loaded as rows. Obviously we can't see your item templates currently as you've not included them in the question.
I've got to admit TableLayout isn't something I've ever personally used in a production project - just not something I've yet needed to use.
I'm currently working on a Rails project, and have found times where it's easiest to do
if object.class == Foo
...
else if object.class == Bar
...
else
...
I started doing this in views where I needed to display different objects in different ways, but have found myself using it in other places now, such as in functions that take objects as arguments. I'm not precisely sure why, but I feel like this is not good practice.
If it's not good practice, why so?
If it's totally fine, when are times that one might want to use this specifically?
Thanks!
Not sure why that works for you at all. When you need to test whether object is instance of class Foo you should use
object.is_a? Foo
But it's not a good practice in Ruby anyway. It'd much better to use polymorphism whenever it's possible. For example, if somewhere in the code you can have object of two different classes and you need to display them differently you can define display method in both classes. After that you can call object.display and object will be displayed using method defined in the corresponding class.
Advantage of that approach is that when you need to add support for the third class or a whole bunch of new classes all you'll need to do is define display method in every one of them. But nothing will change in places where you actually using this method.
It's better to express type specific behavior using subtyping.
Let the objects know how they are displays. Create a method Display() and pass all you need from outside as parameter. Let "Foo" know to display foo and "Bar" know how to display bar.
There are many articles on replacing conditionals with polymorphism.
It’s not a good idea for several reasons. One of them is duck typing – once you start explicitly checking for object class in the code, you can no longer simply pass an instance of a different class that conforms to a similar interface as the original object. This makes proxying, mocking and other common design tricks harder. (The point can be also generalized as breaking encapsulation. It can be argued that the object’s class is an implementation detail that you as a consumer should not be interested in. Broken encapsulation ≈ tight coupling ≈ pain.)
Another reason is extensibility. When you have a giant switch over the object type and want to add one more case, you have to alter the switch code. If this code is embedded in a library, for example, the library users can’t simply extend the library’s behaviour without altering the library code. Ideally all behaviour of an object should be a part of the object itself, so that you can add new behaviour just by adding more object types.
If you need to display different objects in a different way, can’t you simply make the drawing code a part of the object?