mvvmlight windows 8 metro async load data in viewmodel constructor - c#

I am using the MVVMLight framework in a metro app. I began by loading data in my ViewModel constructors and everything worked fine. Towards the end of the build I introduced some extra exception handling in the app.xaml.
TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException;
This began to throw a lot of errors about tasks not being awaited properly.
I moved the ViewModel constructor data load calls into my page LoadState method and awaited them there and all works fine. However, I have read that this is possibly bad practice.
Should I introduce an async call to the ViewModel constructor somehow instead? Interested what best pratice may be? Maybe I should remove the exception handler!
A similar question has been asked here:
MVVM view model and async data initialisation

Not sure where you saw that Data call load in LoadState would be a bad practice, in most case you would not even be able to load the data before load state since you would need whatever parameter is passed by LoadState. Also even of the parameter is not needed I personally prefer to load data in LoadState because starting loading it in the constructor mean that you are going to take some of the cpu time while the page is loading so it will take the page a little longer to load. The only reason I see to load it in the constructor would be so that the data is loaded at design time (because the view model cosntructor will be called but not LoadState) but for that you can just add a condition (ViewModelBase.IsInDesignModeStatic) to call load in the constructor for design time

First, a couple of rules:
Ensure that all Tasks are awaited
Never write async void except for event handlers.
That taken care of, check if you still have some errors. Chances are you already had some errors but they haven't surfaced.

Related

how to force Show() to execute now, not after others methods

In the baseform of a winform project the code for connecting to the database is moved from the load event to the show event.
In the show event there is a call to Update() before fetching data, this makes the form appear much faster which is more pleasant for the users.
But now I found code on some places like this for example :
FormRitDetail ritDetail = new FormRitDetail();
ritDetail.PrimaryKeyValue = ritID;
ritDetail.Show();
ritDetail.SendSaleEmail(cancelSale);
ritDetail.Close();
This worked perfect while the code for fetching data was in the load event, but now it gives an error which I have tracked down. In the SendSaleEmail method the data is not fetched yet.
The fetching happens in the Shown() event, but it seems that c# does the call to SendSaleEmail first, and than the call to Show().
How can I force c# to do the methods in the order as I write them ?
I can do a call to ritDetail.Update() after the ritDetail.Show() I know that, but I would like a general solution that does not involves writing additional code everywhere the show() method is called.
Is this possible ?
In the baseform of a winform project the code for connecting to the database is moved from the load event to the show event.
There is your real problem. You depend on an event to get executed to get into a valid object state. That's called temporal coupling. It's what makes you experience the current problem.
A general guideline is to never execute business logic within events. Instead create separate methods for that. Those methods can in turn be executed from the event handlers.
The other problem is that you need to load and show a form just so send a send email? At least I interpret your question as that the form will just open, execute and close. Move that code to a new class which just that responsibility.
So the answer to your question is:
Do not depend on UI events ensure that business data is loaded. It can be loaded directly but not yet populated into the form until it's ready.
Forms have a UI responsibility. They should not be responsible of business logic. Create separate classes.
Update
Regarding the actual problem, I just checked reference source for the Form class. The Show() method just changes the internal state (using SetWindowLongPtr WinApi function). Thus nothing is done until the message pump processes that message.
There is no guarantee that it's done before the next method call (i.e. SendSaleEmail).

Issues Proffering Language Service

I have found two ways of proffering a language service on the internet.
The first way involves using a IOleComponentManager and registering a timer to call my service during idle times.
The second way involves casing my service as an IServiceContainer and adding a ServiceCreatorCallback to "proffer the service on demand".
Supposedly the second way is now the "preferred way" of doing things. Unfortunately, when I use this method, OnSynchronizeDropdowns never gets called on my TypeAndMembersDropdownBars implementation.
In addition, when my LanguageService finds errors in the file, it uses ParseRequest.Sink.AddError() to add errors to the error list. When proffering "On Demand", these errors don't show up in the GUI, even though I see them being added when I debug through the code.
I know that my language service is being registered, because syntax highlighting, "Go to Defintion", and "Find All References" still work.
Here is the code I'm using to "proffer my service on demand":
IServiceContainer serviceContainer = this as IServiceContainer;
ServiceCreatorCallback callback = new ServiceCreatorCallback(CreateLanguageService);
serviceContainer.AddService(typeof(MyLanguageService), callback, true);
Can anyone tell me why some functionality of my LanguageService does not work when proffering it on demand? Am I missing something, or is that way just not meant for a fully functional language service?
It looks like at least the missing functionality requires using the IOleComponentManager method that registers a timer to call the language service during idle periods.
Using dotPeek, I found that OnSynchronizeDropdowns() gets called from OnCaretMoved() for synchronizing the selected item when you click around in the editor. OnCaretMoved() itself appears to only be called from the LanguageService.OnIdle() method, which I believe requires the use of the idle timer.
After digging some more, I also found that the error list requires that the ParseRequest.Reason be set to ParseReason.Check, otherwise it ignores the call. Digging through the code some more, the only place I found that parse reason being used was in Source.OnIdle().
Update: I believe I have confirmed that registering an idle timer is required for these two pieces of functionality. From MSDN on LanguageService.OnIdle:
Note
This method is not called unless you set up your own timer and call
this method from the timer handler.
The base method calls OnCaretMoved if the caret has moved since last
time OnIdle was called. The base method then calls the OnIdle method
on the Source object for the current view. If the current Source
object cannot be obtained, the base method does nothing at all,
including not calling OnCaretMoved.

How to process time consuming serverside initialization in MVC?

I currently started a little project, expieriencing the world of JS and HTML5.
I tried a few months ago, already, but I stopped, because I've had not enough time to create a MVC single page application from scratch. There were too many concepts and patterns, that had to be understood and I would have regretted losing all that knowledge from lack of use on my daily work. Use it or lose it!
Yesterday I just found this post on John Papa's blog and I thought that would be great to use as a start. Basically it's an MVC template, called HotTowel, which implements already great concepts like data-binding, minification and so forth. I would experience the code as far as I needed for the moment and would experience it further, as soon as I'd need to.
I'd like to build an application for fetching data from my works existing data model project. In our Silverlight application, we bootstrap it through preloading and initializing dictionaries and other properties and calling async Init() methods (e.g. for downloading XML files containing custom codes and put them into dictionaries). MEF is used to get rid of unhandy dependencies.
As far as I understood server side initialization has to be done in the Application_Start() method in the Global.asax file. I wonder how I'd await async calls in this method? What's the best practices? My queries on the client side heavily rely on these classes to be initialized. What options are there?
My thoughts were the following:
Application_Start() fires and forgets the async initialization process. If I'd perform a request (on a controller I guess) before the initialization finished, I'd have to wait for the callback of the initialization process and start queries as soon as it arrives. Advantage of this'd be, that initialization runs, while the user already can navigate through the application.
I'd implement some kind of lazy initialization. I'd process the initialization as soon as the first request is made. That may take long for the first request, though.
I'd run the initialization process synchronously in Application_Start(). The major disadvantage of this I've seen so far is, that the browser window seems freezed to the user. I'd be comfortable with this solution, if it was possible to let the user keep track of the current initialization status (some kind of splash screen).
Though I don't know how any of them would work concretly and would be glad if any of you could give me some advices for how and where to start.
You can use a Task<MyDataModel> to represent the data.
static Task<MyDataModel> dataTask;
public static Task<MyDataModel> LoadDataModelAsync()
{
var ret = new MyDataModel();
await ret.Init();
return ret;
}
Kick it off in Application_Start (or a static constructor):
dataTask = LoadDataModelAsync();
Then each of your actions that needs it can await for it to complete:
MyDataModel data = await dataTask;
...
If it's already complete, the await will detect that and continue (synchronously).

C# - Creating new objects on buttonclick?

I'm learning some C# and in the tutorials, they usually put most of the code on the button clicks for the sake of teaching. For example, if they were going to show a streamreader, they would do:
StreamReader sr = new StreamReader();
..inside the button's click function.
Is this a bad programming habit? From javascript, I remember reading a warning on some code I wrote that said something about creating a function inside a timeout event. Should all variables and objects be declared outside of the button click function?
I'm learning some C# and in the tutorials, they usually put most of the code on the button clicks for the sake of teaching
The reason that putting code inside a click handler would be bad is that a click handler is specifically related to the UI, and the rest of your code might not be.
A stream reader reads from a stream. Code that processes a stream should be grouped with it. Code that handles the fact that you clicked on the UI has nothing to do with reading from a stream, so it should be separated.
Generally you should group your code so that parts of your code that are logically similar are together, and that parts of your code that deal with entirely different things are separated. This will give you "high cohesion". It is related to the Single Responsibility Principle.
Should all variables and objects be declared outside of the button click function?
Absolutely not. If it makes sense to create a specific object when handling a UI event, do so.
However as I mentioned before, if you're dealing with non-UI things inside a UI click handler you're doing too many things at once. Split out your streaming code into another method, another set of methods, or into another object. This will make it easier to read your code, it will make your code have a better chance of being reusable, and it will make it easier to edit your code.
UI logic and flow is notorious for being kludgy and requiring a lot of work-arounds and special handling. It is also the area of your app that you will get the most feedback on, so it will undergo the most change. Everyone will have an opinion on how your UI should work, including non-technical users. If you guard yourself against this by separating your UI logic from the logic in the rest of your app, then those changes will be much easier to make.
You can create instances within your handlers, this is common practice as everything is taking place on the UI thread within your handlers. In addition once the method completes that variable will go out of scope and get marked for garbage collection.
It all depends on how long you need the object to live, if you wont use it outside the button event then it probably should be there so it gets garbage-collected when the event is finished, if you do need to use your objects outside then using a field in your class should be fine.
No it is not a bad idea to create instances in event handlers, but if there is any code that you may want to call multiple places in your code, it is best to that part of code to a separate method instead of trying to simulate button click events

handling GUI element properties per app state

I was thinking of centralizing this functionality by having a single method that gets passed an AppState argument and it deals with changing the properties of all GUI elements based on this argument. Every time the app changes its state (ready, busy, downloading so partially busy, etc), this function is called with the appropriate state (or perhaps it's a bit field or something) and it does its magic.
If I scatter changing the state of GUI elements all over the place, then it becomes very easy to forget that when the app is in some state, this other widget over there needs to be disabled too, etc.
Any other ways to deal with this sort of thing?
Emrah,
Your idea is good. You need to limit the state structure and this is the only way to ensure reliable UI. On the other hand do not follow the "one function" idea to strictly. Rather continuously follow its direction, by creating a function and then do progressively refactoring all attributes to a single "setter" function. You need to remember about a few things on your way:
Use only one-way communication. Do not read the state from controls since this is the source of all evil. First limit the number of property reads and then the number of property writes.
You need to incorporate some caching methodology. Ensure that caching does not inject property reading into main code.
Leave dialog boxes alone, just ensure that all dialog box communication is done during opening and closing and not in between (as much as you can).
Implement wrappers on most commonly used controls to ensure strict communication framework. Do not create any global control framework.
Do not use this ideas unless your UI is really complex. In such case using regular WinForms or JavaScript events will lead you to much smaller code.
The less code the better. Do not refactor unless you loose lines.
Good luck!
Yes, this is the most time consuming part of the GUI work, to make a user friendly application. Disable this, enable that, hide this, show that. To make sure all controls has right states when inserting/updateing/deleteing/selecting/deselecting things.
I think thats where you tell a good programmer from a bad programmer. A bad programmer has an active "Save"-button when there is nothing changed to save, a good programmer enables the "save"-button only when there are things to save (just one example of many).
I like the idea of a UIControlstate-handler for this purpose.
Me.UIControlStates=UIControlstates.EditMode or something like that.
If having such object it could raise events when the state changes and there we put the code.
Sub UIControlStates_StateChanged(sender as object, e as UIControlStateArgs)
if e.Oldstate=UIControlStates.Edit and e.NewState=UIControlStates.Normal then
rem Edit was aborted, reset fields
ResetFields()
end if
select case e.NewState
case UIControlStates.Edit
Rem enalbe/disable/hide/show, whatever
Case UIControlStates.Normal
Rem enalbe/disable/hide/show, whatever
Case UIControlStates.Busy
Rem enalbe/disable/hide/show, whatever
Case Else
Rem enalbe/disable/hide/show, whatever
end select
end sub
#Stefan:
I think we are thinking along the same lines, i.e. a single piece of code that gets to modify all the widget states and everyone else has to call into it to make such changes. Except, I was picturing a direct method call while you are picturing raising/capturing events. Is there an advantage to using events vs just a simple method call?

Categories

Resources