How to fetch an integer property from a Model and use it to initialize a local variable, in Razor? - asp.net-mvc-4

I have a model containing an integer property called Pointer. I want to use that property inside the Razor view, as follows:
However I am getting an error...
How do I solve this? Is this error because of the line: int pnt = #Model.Pointer; ?

Yes, and you are generally overusing #. Your code should probably read something like:
#for (var i = 0; i < Model.Lists.ToList().Count; i++) {
var pointer = Model.Pointer;
if (i == pointer) {
var url = "/Subscriber/List/" + i;
<li>#Model.Lists.ToList()[i].ListName</li>
}
}
Apart from your actual question, I suggest you consider writing some extensions to the HtmlHelper class, i.e. to allow writing e.g. Html.SubscriberListItem(number), to keep concerns properly separated and the view clean.
Another option would be moving most of the logic to the view model (or possibly controller). I.e. there could be something like a Model.Subscribers.Link.Uri and a Model.Subscribers.Link.Text. This may even be the preferred option, depending on what your model looks like. (Perhaps the uri should be hooked up with the RoutingTable also.)
The code you've written is prone to throwing exceptions, and moving the logic out from the view will make writing safe code easier as well, if you don't mind my saying so.

Related

Is there any possibility that QAbstractItemModel::beginResetModel and endResetModel can create a performance issue?

My Dev setup:
Qt version : Qt 5.15.0
OS: Embedded Linux
I have a list of information.
Assume I have a structure called MyStruct
My model class is having a member variable of QList of above structure, to hold data for my view. Whenever I am opening the view, I am updating the QList (Note: There may or may not be a change). Updating here is something like assigning a new QList to existing one. before assignment, I am calling beginResetModel and after assignment I am calling endResetModel,
void MyModelClass::SomeInsertMethod(const QList<MyStruct>& aNewData)
{
beginResetModel();
m_lstData = aNewData;
endResetModel();
}
One thing I believe can be improved, is putting a check, if the new data is different than the existing data and then doing the above. Something like this:
void MyModelClass::SomeInsertMethod(const QList<MyStruct>& aNewData)
{
if (m_lstData != aNewData)
{
beginResetModel();
m_lstData = aNewData;
endResetModel();
}
}
Apart from that, is there any possibilities of getting a performance issue for calling beginResetModel/endResetModel? I m seeing a very small delay in the view coming up in my application.
I checked the documentation of QAbstractItemModel for above methods. Didn't get anything specific to the performance issue.
The other way, which this can be done, is by individually comparing the elements of the lists and triggering a dataChanged signal with appropriate model index and roles. But I feel, this will unnecessarily introduce some additional loops and comparisons, which again may cause some other performance issue. Correct me if I am wrong.
Is there any advantage of using dataChanged over beginResetModel/EndResetModel?
Please let me know your views on the above.

Use a Class name stored in a variable to call a Class method?

I'm probably over-thinking this/wasting time trying to avoid a bit of conditional code - so I thought I would ask. I've seen some other questions # this sort of thing but they were using php or some other language.
At the most basic, can I do something like this (I know the syntax is wrong):
Class * var = #"Playback_Up";
// call Class method to get default settings
NSMutableDictionary * dict = [var getPlaybackDefaults];
Why do I want to do this? To avoid a bunch of conditionals. I have an app where a using can select from a range of playback "types" - each type is handled by a subclass of a "Playback" class. It would be convenient to store the class names in an array and then when a selection is made (from a tableView) call the selected class, create an instance of it, etc.
Is this possible or am I digging myself into a hole here?
The correct syntax for your first line is:
Class var = NSClassFromString(#"Playback_Up");
The rest is fine, and I use this kind of technique more frequently than you might imagine.
(Except that "Playback_Up" should never be the name of a class of course.)
EDIT: Do note Paul.s's comment below. Using +class is preferred if you can hard-code the class at compile time.

How to access properties dynamically / late-bound?

I'd like to implement a method which allows me to access a property of an unknown/anonymous object (-graph) in a late-bound / dynamic way (I don't even know how to correctly call it).
Here's an example of what I'd like to achieve:
// setup an anonymous object
var a = new { B = new { C = new { I = 33 } } };
// now get the value of a.B.C.I in a late-bound way
var i = Get(a, "B.C.I");
And here's a simple implementation using "classic" reflection:
public static object Get(object obj, string expression)
{
foreach (var name in expression.Split('.'))
{
var property = obj.GetType().GetProperty(name);
obj = property.GetValue(obj, null);
}
return obj;
}
What other options do I have with C# / .NET 4 to implement something similar as shown above, but maybe simpler, more performant, etc.?
Maybe there are ways to achieve the same thing, which would allow me to specify expression using a lambda expression instead of a string? Would expression trees be helpful in any way (e.g. as shown in this question)?
Update: the object and the expression are passed into my code via a web service call. That's why I used object and string in my Get() method.
Do you actually only have the expression as a string? Is it known at compile-time, just that the types themselves aren't known (or are hard to express)? If so:
dynamic d = a;
int i = d.B.C.I;
If you really only have it as a string (e.g. as user-entered data) that makes life a lot harder, and none of the C# 4 features really help you. You could potentially evaluate it as an IronPython script or something like that...
EDIT: Okay, after the update it sounds like you're in the latter situation - in which case, I don't know of a nicer way than using reflection. Some of the built-in property binding built for UIs may help, but I don't know of a clean way of accessing it.
If you want to use C# style, you could use the Mono compiler as a service from your application. I describe how to do this here:
Mono Compiler as a Service (MCS)
As an alternative approach, you could use reflection to put all of your object's properties into an ExpandoObject then use it like a dictionary (because ExpandoObject implements IDictionary). Alternatively, you could use JSON.NET and call JObject.FromObject, which will turn a regular object into a JObject which is accessible in a dictionary-like style (and as an added benefit has recursive graph support). Lastly, you could use the same approach to dump your object into a dictionary of dictionaries.

C# 4.0 'dynamic' and foreach statement

Not long time before I've discovered, that new dynamic keyword doesn't work well with the C#'s foreach statement:
using System;
sealed class Foo {
public struct FooEnumerator {
int value;
public bool MoveNext() { return true; }
public int Current { get { return value++; } }
}
public FooEnumerator GetEnumerator() {
return new FooEnumerator();
}
static void Main() {
foreach (int x in new Foo()) {
Console.WriteLine(x);
if (x >= 100) break;
}
foreach (int x in (dynamic)new Foo()) { // :)
Console.WriteLine(x);
if (x >= 100) break;
}
}
}
I've expected that iterating over the dynamic variable should work completely as if the type of collection variable is known at compile time. I've discovered that the second loop actually is looked like this when is compiled:
foreach (object x in (IEnumerable) /* dynamic cast */ (object) new Foo()) {
...
}
and every access to the x variable results with the dynamic lookup/cast so C# ignores that I've specify the correct x's type in the foreach statement - that was a bit surprising for me... And also, C# compiler completely ignores that collection from dynamically typed variable may implements IEnumerable<T> interface!
The full foreach statement behavior is described in the C# 4.0 specification 8.8.4 The foreach statement article.
But... It's perfectly possible to implement the same behavior at runtime! It's possible to add an extra CSharpBinderFlags.ForEachCast flag, correct the emmited code to looks like:
foreach (int x in (IEnumerable<int>) /* dynamic cast with the CSharpBinderFlags.ForEachCast flag */ (object) new Foo()) {
...
}
And add some extra logic to CSharpConvertBinder:
Wrap IEnumerable collections and IEnumerator's to IEnumerable<T>/IEnumerator<T>.
Wrap collections doesn't implementing Ienumerable<T>/IEnumerator<T> to implement this interfaces.
So today foreach statement iterates over dynamic completely different from iterating over statically known collection variable and completely ignores the type information, specified by user. All that results with the different iteration behavior (IEnumarble<T>-implementing collections is being iterated as only IEnumerable-implementing) and more than 150x slowdown when iterating over dynamic. Simple fix will results a much better performance:
foreach (int x in (IEnumerable<int>) dynamicVariable) {
But why I should write code like this?
It's very nicely to see that sometimes C# 4.0 dynamic works completely the same if the type will be known at compile-time, but it's very sadly to see that dynamic works completely different where IT CAN works the same as statically typed code.
So my question is: why foreach over dynamic works different from foreach over anything else?
First off, to explain some background to readers who are confused by the question: the C# language actually does not require that the collection of a "foreach" implement IEnumerable. Rather, it requires either that it implement IEnumerable, or that it implement IEnumerable<T>, or simply that it have a GetEnumerator method (and that the GetEnumerator method returns something with a Current and MoveNext that matches the pattern expected, and so on.)
That might seem like an odd feature for a statically typed language like C# to have. Why should we "match the pattern"? Why not require that collections implement IEnumerable?
Think about the world before generics. If you wanted to make a collection of ints, you'd have to use IEnumerable. And therefore, every call to Current would box an int, and then of course the caller would immediately unbox it back to int. Which is slow and creates pressure on the GC. By going with a pattern-based approach you can make strongly typed collections in C# 1.0!
Nowadays of course no one implements that pattern; if you want a strongly typed collection, you implement IEnumerable<T> and you're done. Had a generic type system been available to C# 1.0, it is unlikely that the "match the pattern" feature would have been implemented in the first place.
As you've noted, instead of looking for the pattern, the code generated for a dynamic collection in a foreach looks for a dynamic conversion to IEnumerable (and then does a conversion from the object returned by Current to the type of the loop variable of course.) So your question basically is "why does the code generated by use of the dynamic type as a collection type of foreach fail to look for the pattern at runtime?"
Because it isn't 1999 anymore, and even when it was back in the C# 1.0 days, collections that used the pattern also almost always implemented IEnumerable too. The probability that a real user is going to be writing production-quality C# 4.0 code which does a foreach over a collection that implements the pattern but not IEnumerable is extremely low. Now, if you're in that situation, well, that's unexpected, and I'm sorry that our design failed to anticipate your needs. If you feel that your scenario is in fact common, and that we've misjudged how rare it is, please post more details about your scenario and we'll consider changing this for hypothetical future versions.
Note that the conversion we generate to IEnumerable is a dynamic conversion, not simply a type test. That way, the dynamic object may participate; if it does not implement IEnumerable but wishes to proffer up a proxy object which does, it is free to do so.
In short, the design of "dynamic foreach" is "dynamically ask the object for an IEnumerable sequence", rather than "dynamically do every type-testing operation we would have done at compile time". This does in theory subtly violate the design principle that dynamic analysis gives the same result as static analysis would have, but in practice it's how we expect the vast majority of dynamically accessed collections to work.
But why I should write code like this?
Indeed. And why would the compiler write code like that? You've removed any chance it might have had to guess that the loop could be optimized. Btw, you seem to interpret the IL incorrectly, it is rebinding to obtain IEnumerable.Current, the MoveNext() call is direct and GetEnumerator() is called only once. Which I think is appropriate, the next element might or might not cast to an int without problems. It could be a collection of various types, each with their own binder.

Dealing with multiple input parameters using wrapper class

As a sort of continuation of this, I have the following newbie question:
What difference is there in building a wrapper class that expects lots of inputs parameters and inputting those parameters directly into the final constructor?
Don't get me wrong, I think the multiple input parameter thing is pretty ugly, and I'm trying to get around it since just like the poster of that question, I need to deal with a Calculator-like class that requires a lot of parameters. But what I don't understand is what would a wrapper class for input parameters solve, since I also need to build the input class--and that's just as ugly as the other alternative.
To summarize, I don't think this:
MyClass::MyClass(int param1, int param2, int param3... int paramN)
{
this->param1 = param1;
this->param2 = param2;
this->param3 = param3;
...
this->paramN = paramN;
}
...is much different from this:
Result MyClass::myInterface(MyInputClass input)
{
//perform calculations
}
MyInputClass::MyInputClass(int param1, int param2, int param3... int paramN)
{
this->param1 = param1;
this->param2 = param2;
this->param3 = param3;
...
this->paramN = paramN;
}
And, of course, I am trying to avoid setters as much as possible.
Am I missing something here? I'd love to have some insight on this, since I'm still a rather newbie programmer.
Here is some of the reasons, one would like to use a parameter class:
Reusability: You can save the parameters in a variable and reuse them, maybe in another method.
Separation of concerns: Parameter handling, say to verify which parameters are active, which are in their correct ranges, etc., is performed in the parameter class; your calculation method only knows how to calculate, so in the future you know where is each and no logic is mixed.
You can add a new value and impact minimally in your calcultor method.
Maybe your calculator method can be applied to two different set of parameters, say on an integer and on a double. It is more readable/mantainable/faster to write the calculation logic just once and change the parameter object.
Some classes do not need to initialize every single field at the constructor. Sometimes setters are the way to go.
The biggest benefits are:
Insulation from changes. You can add
new properties to the parameter class
and not have to change the class that
uses it or any of its callers.
Code reduction when you're chaining
methods. If MyClass needs to pass
its parameters around, MyInputClass
eliminates a bunch of code.
All the other points are completely valid and sound. Here's a little reinforcement from some authoritative text:
Code Complete suggests that you limit the number of parameters of any routine to seven, as "seven is the magic number for people's comprehension." It then goes on to suggest that passing more than seven parameters increases coupling with the calling scope and that you should use a structured variable (ala MyInputClass) instead.