Advanced donut caching: using dynamically loaded controls
Yesterday I solved one caching problem with local community portal. I enabled output cache on SharePoint Server 2007 to make site faster. Although caching works fine I needed to do some additional work because there are some controls that show different content to different users. In this example I will show you how to use “donut caching” with user controls – powerful way to drive some content around cache.
About donut caching
Donut caching means that although you are caching your content you have some holes in it so you can still affect the output that goes to user. By example you can cache front page on your site and still show welcome message that contains correct user name.
To get better idea about donut caching I suggest you to read ScottGu posting Tip/Trick: Implement "Donut Caching" with the ASP.NET 2.0 Output Cache Substitution Feature.
Basically donut caching uses ASP.NET substitution control. In output this control is replaced by string you return from static method bound to substitution control. Again, take a look at ScottGu blog posting I referred above.
Problem
It is clear that outputting mark-up for these views as string is pretty lame to implement in code at string level. Every little change in design will end up with new version of controls library because some parts of design “live” there.
Solution: using user controls
I worked out easy solution to my problem. I used cache substitution and user controls together. I have three user controls:
- LogInControl – this is the proxy control that checks which “real” control to load.
- AnonymousLogInControl – template and logic for anonymous users login area.
- AuthenticatedLogInControl – template and logic for authenticated users login area. This is the control we render for each user separately because it contains user name and user profile fill percent.
Anonymous control is not very interesting because it is only about keeping mark-up in separate file. Interesting parts are LogInControl and AuthenticatedLogInControl.
Creating proxy control
The first thing was to create control that has substitution area where “real” control is loaded. This proxy control should also be available to decide which control to load. The definition of control is very primitive.
<%@ Control EnableViewState="false" Inherits="MyPortal.Profiles.LogInControl" %>
<asp:Substitution runat="server" MethodName="ShowLogInBox" />
But code is a little bit tricky. Based on current user instance we decide which login control to load. Then we create page instance and load our control through it. When control is loaded we will call DataBind() method. In this method we evaluate all fields in loaded control (it was best choice as Load and other events will not be fired). Take a look at the code.
public static string ShowLogInBox(HttpContext context)
{
var user = SPContext.Current.Web.CurrentUser;
string controlName;
if (user != null)
controlName = "AuthenticatedLogInControl.ascx";
else
controlName = "AnonymousLogInControl.ascx";
var path = "~/_controltemplates/" + controlName;
var output = new StringBuilder(10000);
using(var page = new Page())
using(var ctl = page.LoadControl(path))
using(var writer = new StringWriter(output))
using(var htmlWriter = new HtmlTextWriter(writer))
{
ctl.DataBind();
ctl.RenderControl(htmlWriter);
}
return output.ToString();
}
When control is bound to data we ask to render it its contents to StringBuilder. You need to implement your data binding logic in DataBind() method override. Now we have the output of control as string and we can return it from our method. Of course, notice how correct I am with resources disposing. :)
The method that returns contents for substitution control is static method that has no connection with control instance because hen page is read from cache there are no instances of controls available.
Conclusion
As you saw it was not very hard to use donut caching with user controls. Instead of writing mark-up of controls to static method that is bound to substitution control we can still use our user controls.
Nice! Although I really think that the LoginView control should have this behaviour by default, you delivered a good solution to this framework flaw.
very innovative trick !!!
Nikunj Dhawan
I not yet manage this technique. Can you advise me other websites about this?
Thanks for your information, very useful for beginners like me.
Damn – I was prepared this day could kill my hair in frustration.. and then I saw this.
THANKS.
Pingback:How to avoid the exception “Substitution controls cannot be used in cached User Controls or cached Master Pages.” | Gunnar Peipman - Programming Blog
Villa Stresov was rebuilt in 1996 as a first-class extravagant property by the Bulgarian-American family of Marianne Djidrova Nielsen, a granddaughter of the Stresovs, and Philip R. Nielsen, her other half, in its initial Swiss layout applied 70 several years earlier. Nonetheless, if you are shopping for cost-effective high-end and personal privacy in an alpine environment although already becoming close to ski lifts, hill tracks, retailers, eateries, and other Borovets sights, your best option of Bulgaria ski chalets is the 5-celeb Villa Stresov. If you are trying to find a girl with the very same political views, worths, and concepts that you have, you require to search for special someone from Europe. But as a whole, you will discover that even more European ladies in its entirety are friendly and open to discussion than the same number of American females as a whole. Since all the women that participate in are specifically interested in European/ Mediterranean men and vice versa, this occasion has a very high success rate. When it concerns high heels they are teasing and lovely, they make women really feel unique and empowered in addition to extremely confident despite when or just how they are worn.
Ukraine, nothing lasts for life, dating love changes ukrainian time and dating also go away if partners are not interested in keeping it. The site has a set of questions which contains over 80 concerns to match you with suitable companions. For downhill skiers and snow boarders, Borovets offers 18 efficiently maintained and lift-equipped ski works, totaling even more than 40 kilometers in size, descending from a considerable stage of 2,560 meters over sea degree, with an optimum vertical decrease of one,420 meters. It also has snow weapons for creating snow, and some slopes are brightened for winter sports at night. Ski works are easily accessible for novices, intermediates and ingenious skiers, created with multilingual indicators and global markings. However the slopes supply runs and tracks for all sort of skiers, from beginner to the authorities, whilst the ski works are cared for in extraordinary trouble. We are not the kind of site that sells Eastern European mail order brides. The site of Butchart began its life as a commercial quarry near the millenium, nevertheless, once the sedimentary rock had actually been tired, the owner of Portland Cement’s better half changed the pit into a big flower garden with different areas committed to different self-controls.
The ‘Bukit Timah Core’ specializes in education and learning and entertainment tasks, however, it is the ‘Centre Core’ that really thinks the gem in the yards’ crown. Divided into 3 areas with each one designated a various job within a fairly tiny area (128 acres), the initial of these is referred to as the ‘Tanglin Core’ and is centred around heritage and home entertainment – as epitomised by the presence of lots of a seasonal kiosk and an old statue. They vary in dimension from small seeps to massive swimming pools, and they differ considerably in their mineral material. You will discover a vast array of resorts, vacation homes and villas to select from for your accommodations needs, as appropriately as stores, nightclubs and eateries. Researchers also think that we’re wired to find young people much more eye-catching than old age, specifically when it concerns selecting a companion; besides, if you choose a lady also old to birth your youngsters, your line passes away out, evolutionarily speaking. With this mindset, you would never ever place a lady on a pedestal. These kinds of features produce it simple to establish an excellent connection with a European woman. Originally developed as an ornamental item to come with Emperor Frederick the Great of Prussia’s palace in Postdam, Sanssouci Park is considered one of Versailles great competitors in the European gardening arena.
Blossoms Dating is just one of the oldest Asian dating sites with over 50,000 members. Once over the sea wall surface, they encountered much less resistance. Over the years, the services are much better and better. They are devoted to their family members and to their culture. The aforementioned Mughal design bears some similarity to its European counter get rid of CharmingDate.com the stringent technique of geometry that it abides by, especially where the forms and measurements of its many flowerbeds are worried. Sultanahmet is just one of one of the most historical parts of Istanbul and the conference factor of the Byzantine and Ottoman realms. In the here and now modern-day and fashionable parts of Istanbul, it would be erroneous to assume all traces of background and the previous Constantinople realm have vanished. So several ghosts, phantoms and spirits have actually been reported in Savannah that the American Institute of Parapsychology called it America’s Most Haunted City in 2002. The Pirates’ House was preferred among seafarers in the 19th and 18th centuries, and local tale has it that Captain Flint from Robert Louis Stevenson’s preferred publication “Treasure Island” passed away in the bar.