Clever caching using generics? - asp.net

Are there any clever layers out there to sit on top of the System.Web.Caching.Cache class to handle simple scenarios to fetch items using generics.
I'd like to maybe provide a delegate function to retrieve an item, and be able to fetch an item with a strongly typed GetItem and a delegate function to retrieve an item if it isnt found.
For instance
CleverCache<K, T>
T GetItem(K)
RegisterDelegate(FetchItemDelegate<K,T>)
I'd also like a nice way to handle a cache that only ever handles a single object.
The ASP.NET Cache object just seems really primitive. It just seems like a hashtable with a timeout. They may as well just call it HashtableWithTimeout for all I care. I want some better astraction. Is this the kind of thing that the caching application block will do for me?
Yes I know this is fairly simple code, i just dont have time for any wheel reinventing right now.

You may want to look into some more sophisticated cache providers that can wrap the ASP.NET cache, such as the Enterprise Library's caching block. It provides a much more robust and rich caching story for object lifecycle, invalidation, retrieval, etc.
The ASP.NET cache deserves more credit than you give it - it's actually a very powerful base. Alone, it doesn't do anything complex as you have pointed out, but it is well-designed and robust enough to support some pretty cool stuff.

You may want to look into SharedCache and Microsoft Velocity as improvements to the basic caching available in ASP.NET. I don't know how extensively strong typing is designed into either - but from the samples and documentation I've seen it's better than the ASP.NET Cache.

Related

ASP.NET Profile Provider: is it a value-add?

I've been trying to write an open-source profile provider to work against PostgreSQL (I was frustrated with the limitations and incompleteness in the other projects I'd seen available), but the documentation and examples of how people use it was surprisingly sparse. Even the SO tag for asp.net-profiles has a little over 100 questions associated.
The more I dig in to making it work, the less and less practical it seems; the value added does not seem to justify the complications associated; additionally, it only seems to work on a limited scope of web projects without a bunch of extra work.
I feel like I'm being led to the conclusion that it is not a popular technology, and that there are better ways to persist a more robust user-based information set.
Is my take on this fundamentally flawed? Is this widely used? I'm on the cusp of abandoning my profile provider as it seems to offer little of value.
I have always eschewed the ASP .NET Membership provider in favor of a custom implementation of IPrincipal for one simple reason. I've almost never needed the out-of-the-box functionality it provides.
Any custom implementation means creating your own implementation of MembershipProvider. Amongst other methods that I have never implemented, it includes wonders like RequiresQuestionAndAnswer and MaxInvalidPasswordAttempts. It forces an implementation upon you that you might not need and will take you more time to complete properly.
Sure, you could cheat and put a NotImplementedException in methods that you're not particularly bothered about, but what right-minded coder would feel comfortable with that in a production system? :D
I really like a lot of Microsoft's stuff, but my experience is that a lot of their "out-of-the-box" solutions are fine in vanilla mode, but the wheels tend to come off when you travel off the beaten path. A bit of cherry-picking is therefore required. My advice? Leave this one on the vine.
No, the Profile system in asp.net is not widely used, primarily because of the reasons you mention. It's just not useful for a lot of people.
The easiest solution is to simply create a profile table in your app, then key it on the ProviderUserkey of the Membership system.

Reduing the layer complexity of a Cairngorm based application

Could tools like SWFAddress be used in some clever ways to alleviate an existing client-server architecture. I see possibilities to even introduce REST-like pattern mapping or something like that.
What I am currently doing is following all the Cairngorm guidleines, which has already led to a bunch of commands which all make sense, but inclusing the business delegates, and all that stuff, I am getting into a hard time extending and refactoring the application (and actually layers were supposed to help, tight ... maybe I am not doing it quite right, I admit).
Anyway, what I thought of was somehow reducing the number of application events flying around, and the number of commands responding to them. Actualy, I am quite OK even coupling the view with some logic, if I can get rd of some layer complexity.
What I mean by that: perhaps, I could bind a button click to a url pattern (or use SWFaddress to change the url globally). On the other end, I wll be waiting for changes of the url, reformat it, and pass it onto a service delegate, which has the necessary mappings in mind, so it knows what method to call, or it could even pass the url directly to an HTTPSErvice. The delegate will then deal with the server response, and update the model, which through the bindings will update the view.
I am not going to completely ditch commands. I thing that they are good for scheduling of the internal interactions (within the client itself), but I'd like to abstain from using them for communication with the server.
Am I on the right path ?
Are you apposed to switching to an alternate framework than Cairngorm? You just described perfectly what most people's complaints are about it. I think it mostly exists from the throw back days of Flex development...
Most of the developers I know use a more "modern" framework, usually focusing on Dependency Injection (DI).
Here is a good starting point in analyzing the various frameowkrs in use today:
http://www.adobe.com/devnet/flex/articles/flex_framework.html
and for for further reading...
I personally prefer Swiz, and use it in all my projects. It still focuses on the command pattern, but alleviates a lot of the layer complexity, as you described.
If your questions was how can I make Cairngorm less like... well Cairngorm... then I'm afraid I can't help you there. :)
Cheers and good luck!

Should I cache instances of frequently accessed classes

New to .net and was wondering if there is a performance gain to keeping an instance of, for example a DAL object in scope?
Coming from the Coldfusion world I would instanciate a component and store it in the application scope so that every time my code needed to use that component it would not have to be instanciated over and over again effecting performance.
Is there any benefit to doing this in ASP.Net apps?
Unless you are actually experiencing a performance problem, than you need not worry yourself with optimizations like this.
Solve the business problems first, and use good design. As long as you have a decent abstraction layer for your data access code, then you can always implement a caching solution later down the road if it becomes a problem.
Remember that any caching solution increases complexity dramatically.
NO. In the multi-tier world of .asp this would be considered a case of "premature optimization". Once a sites suite of stubs, scripts and programs has scaled up and been running for a few months then you can look at logs and traces to see what might be cached, spawned or rewritten to improve performance. And as the infamous Jeff Atwood says "Most code optimizations for web servers will benifit from money being spent on new and improved hardware rather than tweaking code for hours and hours"
Yes indeed you can and probably should. Oftentimes the storage for this is in the Session; you store data that you want for the user.
If it's a global thing, you may load it in the Application_Start event and place it somewhere, possibly the HttpCache.
And just a note, some people use "Premature Optimisation" to avoid optimising at all; this is nonsense. It is reasonable to cache in this case.
It is very important to do the cost benefit analysis before caching any object, one must consider all the factors like
Performance advantage
Frequency of use
Hardware
Scalability
Maintainability
Time available for delivery (one of the most important factor)
Finally, it is always useful to cache object which are very costly to create or you are using very frequently i.e. Tables's Data (From DB) or xml data
Does the class you are considering this for have state? If not, (and DAL classes often do not have state, or do not need state), then you should make it's methods static, and then you don't need to instantiate it at all. If the only state it holds is a connection string, you can also make that property field a static property field, and avoid the requirement of instantiating it that way.
Otherwise, take a look at the design pattern called Flyweight

ColdFusion App today -- Flex next year. Considerations to maximize re-use of logic tier next year?

I have started design of a ColdFusion application that is entirely web based. Not much use of Flash forms, or AJAX.
The first version is a strict web app. Version 2 will be a Flex front end.
I want to design and build things so that the Flex layer can use existing logic. It's okay if it means I have to do extra work in version 1. I would like to harden the logic code once and not re-factor.
What are things worth considering / designing / implementing now that would greatly aid in being able to design an app in this way?
One big suggestion, depending on where you're coming from (as it's a rather big question), would be to leverage the ColdFusion component (CFC) as much as possible; the CFC architecture is excellent, versatile and powerful, it integrates quite nicely with Flex (and will do so even better in coming versions of Flex and CF), so to the extent you can design your component tier with that in mind, you'll be glad you did.
It's been a while since I wrote CF code, but on the last big project I did with it, I spent a good deal of time designing a functional tier out of CFCs to be used by the plain ol' Web app, much as it sounds like you're doing -- and then later, when it came time to bolt on an Ajax UI for a subsection of the site (it could've been Flex, but in my case, it happened to be a YUI implementation), I created a facade layer of publicly exposed CFCs whose job it was to wrap and expose a specialized subset of the functionality provided by the first tier. Doing so allowed me to leverage and extend existing code in a way unique to the services that needed it, without having to expose the underlying (first tier) CFCs directly.
I'm sure other folks will have many more (and probably more detailed) suggestions, but that's the one big one I have for you first off -- learn, know and use the CF component. Good luck!
I agree with Christian that the best thing you can do is put everything as far as database logic or any other logic for the application in CFC's, and more specifically, I would suggest using webservices. The main reason for this is that it will allow you to eventually have your cf code, which is all of your database persistence and logic on a different server than where you serve the flex applications from, and would allow code reuse for other applications as well. The nice thing too about writing your cfc's as webservices is that you can use them either as webservices or directly as components in Flex using AMF (remote object). Now of course how much those benefits really apply to you depends on your situation, but its a good plan to follow.
But the main suggestion is to think of your application as having a presentation layer and a logic and persistence layer. If you are making a decision, it goes in the logic layer. If you are showing a screen or doing anything with presentation, it goes in that layer. Keeping those things separate will allow you to more easily switch out your presentation layer to flex later on.
Also, it can be useful to trap any errors thrown and return messages as results (with any results, like in a structure) from all methods. Flex has a nasty habit of telling you something went wrong, but not passing along the error information. This will help you to debug and handle any errors that get thrown much easier.
Check out Matt Woodward's presentation on the topic, it's very informative:
And a few general things to add to the answers everyone else provided:
Encapsulate your data interaction in CFCs (typically in Services which delegate to Gateways and DAOs)
In most cases, you'll want to create "bean" CFC's to represent your business objects (users, widgets, etc), these are what will transfer to Flex as ActionScript classes. You'll need to add cfproperty tags to them to make them serializable to ActionScript (case- and order- sensitive!), so pay attention to that when you create them to prevent having to deal with it later, and use one of the code generation tools like the Adobe CF Extensions for Eclipse or Illudium PU36 to do it for you.
Create a remote facade CFC (or set of CFCs depending on how big the app is) that delegates methods to your Services - this is where you set the access for your methods to "remote" - generally the only place you want to do this (it will feel like you're doing a lot of delegating but it pays off to have all your remote services centralized)
As you develop with HTML, treat your remote facade CFCs as your API and make your HTML views as "dumb" as possible. Think of it this way: any logic you write in your CF view will have to be replicated in your Flex view. If you build the project only using your remote API, you'll have a pretty good feel for how Flex will interact with the application.
Check out ColdSpring, it offers a lot of great features for managing all the objects you're going to create!
I don't claim to be an architecture expert and I know I've thrown around a lot of jargon here to keep it short, but some Googling around CF blogs should turn up a lot of info about the design patterns I've mentioned. Good luck!

Is data binding a bad idea?

Another discussion (we've been having a lot of them these days!) in our work is whether data binding is a bad idea or not.
Personally, I think it is a Bad Thing™.
My reasons are thrice:
It circumvents my well architectured MVP framework - with databinding, the view communicates bi-directionally with a model. Ewww.
It promotes hooking up view controls to datafields at design time. In my experience, this leads to vital code (binding column A to Field X) being obscure and hidden away in some designer file. IMO this code should be explicit and in-your-face, so that it is easy to modify and see what is going on, without having to use a clunky designer interface.
Relating to Point #1 this direct binding makes it harder to isolate each component (view, model, controller/presenter) and unit-test.
The pros are that it is easy to set up, and you can take advantage of some nice features (validation etc) which come with the plumbing already done for you.
But for me, databinding becomes much more of a hindrance when dealing with a large data-centric application.
Any thoughts?
As we say in the UK, "It's Horses for courses"
First off all, I agree with you! But...
For enterprise level applications, then spending the extra time on the system architecture, modelling and standards will give you a robust and sustainable system.
But it will take longer to develop (or at least longer to get to an initial release) and this may not be appropriate for every system or every part of the system.
Sometimes you just need to "get it done and done quick". For internal applications, back office systems and maintenance applications that are rarely used or very dynamic (the spec's change often) then there is little justification in building the Rolls Royce solution for this. It's better to get the developer spending time on the CRITICAL part of the system.
What you have to avoid / prevent is using these "one click framework" solutions on the MISSION CRITICAL area's of the system where the big transaction rate area's and where data quality and integrity is critical. Spend quality time shaving the milliseconds off on the most heavily used area's on the system!!
Another discussion (we've been having a lot of them these days!) in our work
is whether data binding is a bad idea or not.
Personally, I think it is a Bad Thing™.
Strong opinion, but imho, you bring out all the wrong reasons.
It circumvents my well architectured MVP framework - with databinding, the view communicates bi-directionally with a model. Ewww.
I guess it depends on the implementation of the data binding.
In the early years of my programming career, I used to do a lots of VBA for MS Access programming and Access forms had indeed this direct binding to tables/fields in database.
Most of the general purpose languages/frameworks have databinding as a separate component, do not use such a direct binding and are usually considered as a easy generic dropin for a controller in MVC pattern sense.
It promotes hooking up view controls to datafields at design time. In my experience, this leads to vital code (binding column A to Field X) being obscure and hidden away in some designer file. IMO this code should be explicit and in-your-face, so that it is easy to modify and see what is going on, without having to use a clunky designer interface.
I guess you are talking about the binding in WinForms?
My experience with win forms comes from a long ago, so I might be pretty out of date here.
It sure is a convenience feature, and I would strongly argue against it, unless you are writing really simple modal context CRUD style interfaces.
Relating to Point #1 this direct binding makes it harder to isolate each component (view, model, controller/presenter) and unit-test.
Again - assuming the view (a widget in WinFoms?) is tied together with databinding awareness, you are right.
But for me, databinding becomes much more of a hindrance when dealing with a large data-centric application.
Quite contrary - if data binding is implemented as an independent component (eg. bindings in Cocoa or JFace DataBinding, or JGoodies Binding), that acts as a controller between View and a Model, taking care of all the nitty-gritty of event handling and conversion and validation, then it is just so much more easier to use, change and replace than your custom controller code doing just the same thing.
The only downside of a general purpose data binding framework is that if the binding is off and/or misconfigured, the interactions between bound pieces are just notoriously difficult to debug due to the level of abstraction inside the data binding code... So You better not make any mistakes! ;)
I've used databinding in some pretty large systems and find that it works pretty well.
Seems that I do things a bit differently from you though ...
... I don't databind to the model, instead to a dedicated view class that works as an adapter between the model's structure and what I need on screen. This includes things like providing choices for comboboxes & listviews, and so on.
... I never set up the binding using the UI. Instead, I have a single method (usually called Bind() or BindXYZ() that hooks everything up in one place.
My Model remains agnostic, knowing nothing about databinding; my Presenter sticks to the workflow coordinate it's designed for; my Views are now also simple classes (easy to test) that encapsulate my UI behavior (is button X enabled, etc) and the actual UI is relegated to a simple helper on the side.
I have had a few unshakable realizations about data binding over the last few years:
The claim that the data binding allows for the business and presentation to be designed in isolation of each other is actually really quite far from what actually goes on in reality. Usually the deficiencies in the technologies become readily apparent and then all you have done is break apart the UI from the UI-specific business and the resulting separation often becomes far more unwieldy than a all-in-one approach.
Most data binding engines (HTML / WPF / or whatever) all make assertions on the technical business model, and since the designer is not usually equipped to make said assertions, the developer ends up having to touch the view. Not only that, the view shouldn't be making assertions about the business model---if anything, it should be the other way around.
Most of the time, the view model / controller / model / view are all "coupled" and then all you have really done is "move code around" rather than just simply using code behind. With that said, I do find the most pragmatic approach is often to just use data binding sparingly with code behind and forget about MVVM/MVC esque patterns.
Developers often put view level concerns on the view model and then start to use data binding as a crutch rather than a proper approach. for example, I have seen so many view models controlling visibility of UI elements.
Admittedly, data binding is useful for "small systems". I have observed that the performance, complexity and maintainability dramatically suffer as an application grows in richness.
Memory usage techniques with data binding can often become a real hazard. WPF for example uses a LOT of trickery to avoid issues and often developers can still shoot themselves in the foot. Unless you are using something like Sencha for HTML (I think), you will find your memory foot print on your applications start to suffer even with a modest amount of data.
I have found that data binding / UI patterns in general sometimes tend to break down a little when dealing with hierarchical and situational data / presentation.
My personal outlook on data binding is that it is a tool that can be easily abused yet has some compelling uses. You can say the same for any technique, pattern, or guideline. Like anything, too much of something tends to become a problem. I tend to like to try and use the most pragmatic approach for the situation. Prefer consistency when it is pragmatic to do so, but consistently be pragmatic. In other words, you don't have to go down the path of developing for two years and only then come to the conclusion that the code base has become a grotesque smelly mammoth in a china shop full of orphan kittens.
...
#Point 1: Isn't the data binding engine the controller, if you really want to think in patterns? You just do not program it yourself, which is the whole point of using data binding in the first place.
No. DataBinding when used correctly is a Good Thing™.
No; but see #2 and #3. Make the Presenter expose the properties/well-defined sources to bind. Do not expose the Model. Nothing is circumvented.
I agree. I do not use any of the standard ASP.NET data-sources. Instead I use GenericDataSourceControl which is wired to a "select method" that returns well-defined types. The DataSource consumers in the View only knows of these Presenter-types; nothing more.
No. Relating to #1. The Presenter exposes the properties/well-defined sources to bind. These can be tested without the view for correctness (unit tests), and with the view for correctness of application (integration tests).
(My Experience is using ASP.NET WebForms, which may differ from other data-binding scenarios.)
#Timbo:
Yes and no.... but from a TDD perspective I'd like to cordon-off each controller so that I can test it in isolation. Also, say we want to run each edit via an EditCommand (so that we support Undo, for example) - for me, this rules out databinding.
#Guy:
Yes, this is exactly my POV. For me, databinding is great for very simple apps, but we don't do any of those!
I feel that in many frameworks, data binding is just an excuse to do things the easy way. It often results, as does almost any designer-generated code, in too much code which is too complicated and can't be easily tweaked. I've never come across a task I couldn't do just as well (if not better) and, in most cases, just as quickly, by data binding as by writing the code myself.
I have used databinding on large enterprise systems inconjunction with a framework. In my case it was CSLA.
It worked so well, and was extremly fast to get the view working. CSLA has lots of support for databinding and validation built in though.
If it breaks the MVP patturn, so what? if it works better and faster and is easier to manage. However, I would argue that it doesn't break the patturn at all... You can hook up databind in the presenter as it has a reference to the view and also to the model.
for example this is what you would put in your presenter and it would populate the list box or whatever control you want.
myView.list.datasource = myModel.myCollection;
Also I would like to point out the databinding shouldn't be taken as an all or nothing approch. Many times I use databinding when i have a simple and easy UI requirment to map to my object model. However, when there is special functionality needed I might put some code in the presenter to build up the view as I need it rather than using databinding.
Alan
I quite agree with you, data binding have drawbacks...
In our application, if not used carefully, it leads us sometimes to bad data consistency...
But there may be some elegant ways work with databinding with large forms?
Please give me your opinion here:
How to use a binding framework efficiently

Resources