I'm far from new at threading and asynchronous operations, but SL seems more prone to asynchronous issues, particularly ordering of operations, than most frameworks. This is most apparent at startup when you need a few things done (e.g. identity, authorization, cache warming) before others (rendering a UI usable by your audience, presenting user-specific info, etc.).
What specific solution provides the best (or at least a good) strategy for dealing with ordering of operations at startup? To provide context, assume the UI isn't truly usable until the user's role has been determined, and assume several WCF calls need to be made before "general use".
My solutions so far involve selective enablement of UI controls until "ready" but this feels forced and overly sensitive to "readiness" conditions. This also increases coupling, which I'm not fond of (who is?).
One useful aspect of Silverlight startup to remember is that the splash xaml will continue to be displayed until the Application.RootVisual is assigned. In some situations (for example where themes are externally downloaded) it can be better to leave the assignment of the RootVisual until other outstanding async tasks have completed.
Another useful control is the BusyIndicator in the Silverlight Toolkit. Perhaps when you are ready to display some UI but haven't got data to populate the UI you assign the RootVisual using a page that has a BusyIndicator.
In my oppinion:
1st: Render start up UI that will tell the user, that the application did register his action and is runing, (Login window may be?)
2nd: Issue neccessary calls for warm up procedures in background (WCF calls and all that) and let user know about progress of tasks that are required to finish before next GUI can be made operable (main window?)
Order of operations is kind of situation specific, but please be sure to let user know what is happening if it blocks his inputs.
The selective enabling of individual controls can look interesting, but user might go for that function first and it will be disabled, so you have to make sure user knows why, or he will be confused why at start it was disabled and when he went there 10mins later it works. Also depends on what is primary function of your program and what function would that disabled control have. If application main function is showing list of books it wouldnt be nice to make that list load last.
Related
I want to make sure that the following procedure is a good one since I lack experience with WPF applications. I have done some research but did not see any that meet my requirements, especially with the multi-users at a single station.
Problem: I have an application that needs to switch users with out closing. What is the best option for accomplishing this?
The Stage: I am using a MongoDb database, C# WPF, Custom Authentication. It is a single screen with other windows for Administrative tasks.
The authentication is has two options. First is a normal username and salted password following industry practices. The second I mentioned is a short log in code that is stored the same as a password (IE a username and password in one). This because it is a very busy place and a current requirement is for it to time out quickly, say 5 seconds, so others can not enter information under someone else's credentials. Up to 8 people at a time need to be able to quickly log in and add some information. The environment is a high employee theft place.
My solution: This includes the above authentication. Once logged in, the information is loaded into an ApplicationState public static object that has binding between properties and some of the objects on the screen, example displaying who is logged in. When a Command is issued it is checked against the permissions loaded into the ApplicationState to verify adequate permissions exist. The timer is on another thread, like here: http://www.codeproject.com/Articles/42884/Implementation-of-Auto-Logoff-Based-on-User-Inacti
Review: I spent a day researching and designing this solution. I could not find anyone that had the requirements I have. With my lack of experience with WPF and C#, I was not sure of the vocabulary to use in the search and my research. The other option was to rebuild the MasterWindow on every log in, but that seemed to be a bad idea. Is there another way to implement this or will this suffice? I have not completed coding it, but my tests are working.
You are asking a quite broad question here, with a number of design decisions involved which are not necessarily dependent on one another. It is a little bit hard to give a 'correct' answer here, so just a number of thoughts:
When using WPF, it really makes sense to dig into the MVVM pattern. You have probably heard of it when doing research on WPF. (If you're using it already, never mind). There's a bit of a learning curve, but it frees you of quite a few design decisions. In your case, having a ViewModel which exposes the user related properties (Username, commands for logging on and of, etc...) allows you to easily handle the account switching without worrying about the view being updated or something like that. WPF binding mechanisms will do that for you. Do some research on MVVM and INotifyPropertyChanged, if you haven't done so already.
Working with global hooks to track user action seems like a bit of overkill to me. I would consider resetting the timeout on any user action which affects the ViewModel (Add data, remove data, etc.). If this is not sufficient, than before using global OS level hooks, I would work with events on your applications window. You could subscribe to the MouseMove event of your window and reset the timeout-timer there. That should do, because as I understand the requirements, there won't be anything happening outside of your application. Global hooks usually involve a lot of P/Invoke, which is to be avoided if possible.
Apart from that, you're approach seems reasonable as far as I can tell... Though it is not an exhaustive answer, I hope it gives you some input for the next steps.
i'm building an application using a pattern similar to the MVC. The situation is the next: in the context of the model making changes to the associated repository. If the change throw an exception what is the correct way to present the information about the error to the user?
In the previous version of my program when i have spaguetti code organization (model, view, controller overlaped), launching a messagebox telling the user about the error wasn't weird because i was doing almost everything from the views. Now in this new version i want to do the things correctly, so i guess that is bad doing anything that has a visual representation in the model layer.
Some time ago i ask what is the correct way to capture exceptions. The specific point i was refering was to scale up exceptions from an inner code to an upper layer vs capture them in the most upper layer. Almost all the response were that isnt a good approach scale exceptions(capture and throwing again to be captured by a responsable entity), and is better to capture in the most upper layer.
So i have this conflict in my head. I was thinking that is inevitable to maintain the separation of concerns to scale up, but that is in conflict with those previous advices.
How can i proceed?
A common pattern is to have a generic place to put errors in your existing model.
One easy way to do this is to have your model classes all inherit from a base model class that has a property of type IEnumerable<ErrorBase>, or some other type of your choosing.
Then, in your presenter, you can check the error collection and display as necessary.
As far as having exceptions bubble up, the approach I use (almost regardless of what type of application I'm building) is to only handle exceptions at lower levels if you are going to do some special logging (like logging important local variables), or if you can do something intelligent with that exception. Otherwise, let it bubble.
At the layer right before your presenter (or web service class, or whatever), that's when you can capture your exceptions, do general logging, and wrap them (or replace them with) a "sanitized" exception. In the case of the UI, you just make sure you don't reveal sensitive data and perhaps display a friendly message if possible. For web services, you turn these into some kind of fault. Etc.
The upper most layers aren't "responsible" for the bubbled exceptions, they're simply responsible for making sure those don't show up to the end users (or web service client, or whatever) it a form you don't want them to... in other words, you're "presenting" them appropriately.
Remember, separation of concerns is a paradigm that you should follow as a rule of thumb, not an edict that owns all. Just like leaky abstractions, there are leaky paradigms. Do what makes sense and don't worry about it too much. :)
I have a Silverlight Windows Phone 7 app that pulls data from a public API. I find myself doing much of the same thing over and over again:
In the UI, set a loading message or loading progress bar in place of where the content is
Get the content, which may be already in memory, cached in isolated file storage, or require an HTTP request
If the content can not be acquired (no network connection, etc), display an error message
If the content is acquired, display it in the UI
Keep the content in main memory for subsequent queries
The content that is displayed to the user can be taken directly from a data source, such as an ObservableCollection, or it may be a query on a data source.
I would like to factor out this repetitive process into a framework where ideally only the following needs to be specified:
Where to display the content in the UI
The UI elements to show while loading, on failure, and on success
The URI of the HTTP request
How to parse the HTTP response into the data structure that will kept in memory
The location of the file in isolated storage, if it exists
How to parse the file contents into the data structure that will be kept in memory
It may sound like a lot, but two strings, three FrameworkElements, and two methods is less than the overhead that I currently have.
Also, this needs to work for however the data is maintained in memory, and needs to work for direct collections and queries on those collections.
My questions are:
Has something like this already been implemented?
Are my thoughts about the topic above fundamentally wrong in some way?
Here is a design I'm thinking of:
There are two components, a View and a Model.
The View is given the FrameworkElements for loading, failure, and success. It is also given a reference to the corresponding Model. The View is a UserControl that is placed somewhere in the UI.
The Model a class that is given the URI for the data, a method of how to parse the data, and optionally a filename and how to parse the file. It is responsible for retrieving the data and notifying the View whenever the current status (loading/fail/success) changes. If the data downloaded from the network is different from the cache, the network data takes precedence. When the app closes or is tombstoned, the model writes the data to the cache.
How does that sound?
I took some time to have a good read of your requirements and noted some thoughts to offer as a sounding board.
Firstly, for repetetive tasks with common behaviour this is definitely the way to approach it. You are not alone in thinking about this problem.
People doing a bunch of this sort of thing may have created similar abstractions however, to my knowledge none have been publicly released.
How far you go with it may depend if you intend it to be just for your own use and for those with very similar requirements or whether you want to handle more general cases and make a product that is usable by a very wide audience.
I'm going to assume the former, but that does not preclude the possibility of releasing it as an open source project that can be developed further and/or forked.
By not trying to cater for all possibilities you can make certain assumptions about the nature of the using implementation and in particular UI design choices.
I think overall your thinking in the right direction. While reading some of your high level thoughts I considered some things could be simplified (a good thing) and at the same time delivering a compeling UI.
On your initial points.
You could just assume a performance isindeterminate progressbar is being passed in.
Do this if it's important to you, but you could be buying yourself into some complexity here handling different caching requirements - variance in duration or dirty handling. Perhaps sufficient to lean on the platforms inbuilt caching of urls (which some people have found gets in their way).
Handle network connectivity, yep this is repetitive and somewhat intricate. A perfect candidate for a general solution.
Update UI... arguably better to just return data and defer decisions regarding presentation and format of data to your individual clients.
Content in main memory - see above on caching.
On your potential inputs.
Where to display content - see above re data and defer presentation choices to client.
I would go with a UI element for the progress indicator, again a performant progress bar. Regarding communication of failure I would consider implementing this in a Completed event which you publish. Then through parameters you can communicate the result and defer handling to the client to place that result in some presentation control/log/whatever. This is consistent with patterns used by the .Net Framework.
URI - yes, this gets passed in.
How to parse - passing in a delegate to convert a stream or string into an object whose type can be decided by the client makes sense.
Loc of cache - you could pass this if generalising this matters, or hardcode it's path. It would be more useful to others if passed in (consider if you handle folders/creation).
On the implementation.
You could go with a UserControl, if it works for you to be bound by that assumption. It would be more flexible though, and arguably equally simple/elegant, to push presentation back on the client for both the data display and status messages and control hide/display of the progress bar as passed in.
Perhaps you would go so far as to assume the status messages would always be displayed in a textblock (if passed) and shift that housekeeping from each of your clients into your generic class.
I suspect you will benefit from not coupling the data format and presentation still.
Tombstone handling.. I would recommend some testing on the platforms in built caching of URLs here and see if you can identify whether it's durations/dirty conditions work for your general cases.
Hopefully this gives you some things to think about and some reassurance you're heading down the right path. There are many ways you could go about this. Which is the best path ultimately will be driven by your goals.
I'm developing a WP7 application which is basically a client of an existing REST API. The server returns data in JSON. With the help of the library JSON.NET (http://json.codeplex.com/) I was able to deserialize it directly to my .NET C# classes.
I store locally the data to handle offline scenario of my application and also to prevent the call on the server each time the user launch the application. I provide two ways to refresh the data: manually and/or after a period of time. To store the data I use Sertling (http://sterling.codeplex.com/), it’s a simple but easy to use local database for Silverlight/WP7.
The biggest challenge is to handle the asynchronous communication with the server. I provide clear UI feedbacks (Progressbar and /or loading wheel) to let know to the user what’s going on.
On a side note I’m using MVVM Light toolkit and SL Unit Testing to do integration test View Model => my local Client code => Server. (http://code.google.com/p/nunit-silverlight/wiki/NunitTestsWp7)
In my WPF application I need to do an async-operation then I need to update the GUI. And this thing I have to do many times in different moment with different oparations. I know two ways to do this: Dispatcher and BackgroundWorker.
Because when I will chose it will be hard for me to go back, I ask you: what is better? What are the reasons for choosing one rather than the other?
Thank you!
Pileggi
The main difference between the Dispatcher and other threading methods is that the Dispatcher is not actually multi-threaded. The Dispatcher governs the controls, which need a single thread to function properly; the BeginInvoke method of the Dispatcher queues events for later execution (depending on priority etc.), but still on the same thread.
BackgroundWorker on the other hand actually executes the code at the same time it is invoked, in a separate thread. It also is easier to use than true threads because it automatically synchronizes (at least I think I remember this correctly) with the main thread of an application, the one responsible for the controls and message queue (the Dispatcher thread in the case of WPF and Silverlight), so there's no need to use Dispatcher.Invoke (or Control.Invoke in WinForms) when updating controls from the background thread, although that may not be always recommended.
As Reed said, Task Parallel Library is a great alternative option.
Edit: further observations.
As I said above, the Dispatcher isn't really multithreaded; it only gives the illusion of it, because it does run delegates you pass to it at another time. I'd use the Dispatcher only when the code really only deals with the View aspect of an application - i.e. controls, pages, windows, and all that. And of course, its main use is actually triggering actions from other threads to update controls correctly or at the right time (for example, setting focus only after some control has rendered/laid-out itself completely is most easily accomplished using the Dispatcher, because in WPF rendering isn't exactly deterministic).
BackgroundWorker can make multithreaded code a lot simpler than it normally is; it's a simple concept to grasp, and most of all (if it makes sense) you can derive custom workers from it, which can be specialized classes that perform a single task asynchronously, with properties that can function as parameters, progress notification and cancellation etc. I always found BackgroundWorker a huge help (except when I had to derive from it to keep the Culture of the original thread to maintain the localization properly :P)
The most powerful, but also difficult path is to use the lowest level available, System.Threading.Thread; however it's so easy to get things wrong that it's not really recommended. Multithreaded programming is hard, that's a given. However, there's plenty of good information on it if you want to understand all the aspects: this excellent article by our good fellow Jon Skeet immediately jumps to mind (the last page of the article also has a good number of very interesting links).
In .Net 4.0 we have a different option, Task Parallel Library. I haven't worked with it much yet but from what I've seen it's impressive (and PLINQ is simply great). If you have the curiosity and resources to learn it, that's what I'd recommend (it shouldn't take that much to learn after all).
BackgroundWorker is nice if you're doing a single operation, which provides progress notifications and a completion event. However, if you're going to be running the same operation multiple times, or multiple operations, then you'll need more than one BackgroundWorker. In this case, it can get cumbersome.
If you don't need the progress events, then using the ThreadPool and Dispatcher can be simpler - especially if you're going to be doing quite a few different operations.
If C# 4 is an option, however, using the Task Parallel Library is a great option, as well. This lets you use continuation tasks setup using the current SynchronizationContext, which provides a much simpler, cleaner model in many cases. For details, see my blog post on the subject.
I am in the middle of development of a WPF application that is using Entity Framework (.NET 3.5). It accesses the entities in several places throughout. I am worried about consistency throughout the application in regard to the entities. Should I be instancing separate contexts in my different views, or should I (and is a a good way to do this) instance a single context that can be accessed globally?
For instance, my entity model has three sections, Shipments (with child packages and further child contents), Companies/Contacts (with child addresses and telephones), and disk specs. The Shipments and EditShipment views access the DiskSpecs, and the OptionsView manages the DiskSpecs (Create, Edit, Delete). If I edit a DiskSpec, I have to have something in the ShipmentsView to retrieve the latest specs if I have separate contexts right?
If it is safe to have one overall context from which the rest of the app retrieves it's objects, then I imagine that is the way to go. If so, where would that instance be put? I am using VB.NET, but I can translate from C# pretty good. Any help would be appreciated.
I just don't want one of those applications where the user has to hit reload a dozen times in different parts of the app to get the new data.
Update:
OK so I have changed my app as follows:
All contexts are created in Using Blocks to dispose of them after they are no longer needed.
When loaded, all entities are detatched from context before it is disposed.
A new property in the MainViewModel (ContextUpdated) raises an event that all of the other ViewModels subscribe to which runs that ViewModels RefreshEntities method.
After implementing this, I started getting errors saying that an entity can only be referenced by one ChangeTracker at a time. Since I could not figure out which context was still referencing the entity (shouldn't be any context right?) I cast the object as IEntityWithChangeTracker, and set SetChangeTracker to nothing (Null).
This has let to the current problem:
When I Null the changeTracker on the Entity, and then attach it to a context, it loses it's changed state and does not get updated to the database. However if I do not null the change tracker, I can't attach. I have my own change tracking code, so that is not a problem.
My new question is, how are you supposed to do this. A good example Entity query and entity save code snipped would go a long way, cause I am beating my head in trying to get what I once thought was a simple transaction to work.
A global static context is rarely the right answer. Consider what happens if the database is reset during the execution of this application - your SQL connection is gone and all subsequent requests using the static context will fail.
Recommend you find a way to have a much shorter lifetime for your entity context - open it, do some work, dispose of it, ...
As far as putting your different objects in the same EDMX, that's almost certainly the right answer if they have any relationships between objects you'll want them in the same EDMX.
As for reloading - the user should never have to do this. Behind the scenes you can open a new context, reloading the current version of the object from the database, applying the changes they made in the UI annd then saving it back.
You might want to look at detached entities also, and beware of optimistic concurrency exceptions when you try to save changes and someone else has changed the same object in the database.
Good question, Cory. Thumb up from me.
Entity Framework gives you a free choice - you can either instanciate multiple contexts or have just one, static. It will work well in both cases and yes, both solutions are safe. The only valuable advice I can give you is: experiment with both, measure performance, delays etc and choose best one for you. It's fun, believe me :)
If this is going to be a really massive application with tons of concurrent connections I would advise using one static context or one static, core context and just few additional ones just to support the main one. But, as I wrote just few lines above - it's up to your requirements which solution is better for you.
I especially liked this part of your question:
I just don't want one of those
applications where the user has to hit
reload a dozen times in different
parts of the app to get the new data.
WPF is a really, really powerful tool and basically times when users have to press buttons to refresh data are gone forever. WPF gives you a really wide range of asynchronous, multithreading tools such as Dispatcher class or Background worker to gently refresh desired data in the background. This is really great, because not only you don't have to worry about pressing various buttons, but also background threads don't block UI, so data is refreshed transparently from user's point of view.
WPF together with Entity Framework are really worth the effort of learning - please feel free to ask if you have any further concerns.