Pros and Cons of registering user controls in web.config vs. asp page - asp.net

Can someone please let me know the pros and cons of registering user controls in web.config vs. on top of asp pages?
I am looking for performance issues in particular. Does having all the controls registered in web.config make the pages slower to load (even the pages that do not use these controls)?

Web.config Pros
Only 1 place to add extra bit of code
Web.config Cons
Sometimes, I forget to update web.config on production environment since I never copy the web.config from staging area to live site.
On every page pros
When you deploy/publish pages and/or copy pages from dev/test/staging to live server, you don't need to worry about updating web.config
One very page cons
Its on every page, so if something changes, it's a pain to go through every page and fix it
You have to add it manually to each page
I'd recommend doing it in the web.config. It's less work for you since you don't need to remember to add it to every page. Although, if you have a ton and lots are only used on a single page, then you could do a bit of both to keep your web.config a bit less cluttered. I usually put my controls in web.config, if I use them in more than one page. If it's just used on a single page, then I usually just declare it in my asp.net page.

Old question, but finally an answer on performance! There is no difference:
http://weblogs.asp.net/scottgu/archive/2006/11/26/tip-trick-how-to-register-user-controls-and-custom-controls-in-web-config.aspx#1056687
The good news is that there isn't any performance difference between
registering them in a web.config file vs. at the top of a page.
The runtime performance is exactly the same (they get compiled down to
the same instructions in both scenarios).
Compilation should also compile at the same performance.

Not a heck of a lot cons to putting it into the web.config. It just can't be done with a drag and drop, so many just don't do it. Keeps the page less cluttered and makes change easier in the long term.

Related

Managing/removing unnecessary scripts in live Kentico site

We're building a Kentico 8.2 site using ASPX+portal model. Looking at the rendered HTML on my live site I can see a lot of unnecessary Javascript that Kentico has dumped into my page. What's more this is occurring at the top of my page at the top of the form element.
For example, it's rendering the ASP.NET __doPostBack JS function even though I'm not using any controls that require it. Other scripts are being added as WebResource.axd and ScriptResource.axd includes.
At a glance it would seem these scripts constitute the Microsoft AJAX framework used with UpdatePanel etc. My assumption is that they are there to add portal manager functionality when using the page in the Kentico UI. Presumably they are also used with certain built-in web parts.
However, I am only using custom web parts on my live site so all these scripts are doing nothing and are just slowing down my page and causing poor performance testing results.
I've tried hiding the <ajaxToolkit:ToolkitScriptManager /> and <cms:CMSPortalManager /> controls on my master page when rendering the live site, but this causes templates that have a <cms:CMSWebPartZone /> to break.
Does anyone know how to ensure this bloat is removed when not required? Or at the very least cause these scripts to be rendered at the end of the page so they don't interfere with performance too much?
Unfortunately, building sites within Kentico using ASPX and ASPX+Portal Pages will automatically generate additional markup such as __doPostBack, WebResource.axd and ScriptResource.axd.
I wouldn't recommend removing any of the default code in your Masterpage. This will cause things to break (as you've experienced).
However, having this markup in place shouldn't cause a massive issue in page performance. Understandably, this isn't ideal.
What I do to lessen the hit is the following:
Disable the ViewState wherever possible. For example, either at Page Template or Webpart/User control level.
Move the ViewState to the bottom of the page (in Kentico Settings), so the page is less "top heavy".
Ensure you are caching everything you can. For example, site furniture used by your webparts and templates (images/js etc) at IIS level and at Kentico level using their API.
Reading this article from the Kentico documentation provides some more information in greater depth: Optimizing website performance
If you really want "full control" over the HTML rendered, Kentico does allow you to create templates using MVC. But this won't give you the flexibility to modify Page Templates by moving around web parts within the CMS Administration. I presume you have chosen the Portal Page approach for this very reason.
I hope this helps.
In addition to #sbhomra's great answer I have a few questions, suggestions and comments.
How many seconds or milliseconds are you talking about with performance? If you think you'll gain a few milliseconds back, it's not worth your effort to try to rebuild all the functionality. If you're talking a second or two, there about 15 different things you can change within settings and your code to gain it all back. Think about how much code you're going to write, maintain and upgrade just to gain a second or less back?
The WebResource and SciptResource load resources that are compiled into libraries within the website. So if someone created an external library and that library was loading an image that was compiled into it, you'd get that WebResource.axd reference on your site. You'd have to physically remove those libraries from the Kentico instance.
Although I don't recommend it strictly because you lose so much functionality and have so much extra unnecessary code, MVC will give you the control you're looking for.

ASP.NET #OuputCache Directive "Inheritance"

As I mention in an earlier question, I am having trouble with the performance of a web site... Some SQL queries are killing the server. But, as the title of this post mention, I looked at the OutputCache page directive to improve performance of the site.
Although, I came across some questions regarding this directive:
1- If I have a web-user control that declares an OuputCache directive in a page that has one too, which one will "win" ?
2- What's the best pratice regarding the duration ? I'd love to have a sliding window too.
Thanks for your help and please visit http://www.developerit.com
On a request where neither are cached, both the page and the control will be created, and then added to the output cache. If the page is cached, the control will not be created, regardless of whether it's in the cache or not--its markup is contained in the cached copy of the page. If the page is not cached and the control is, the cached markup of the control will be used in the page.
Here's a good article on Output caching: https://web.archive.org/web/20211020111708/https://www.4guysfromrolla.com/articles/121306-1.aspx.
Generally, you seem to be looking at Page and Fragment caching. What you want to do is cache the Page, if you can, as that will give you the best performance benefit. But, if you have regions on the page that must change dynamically per user, eg: you are saying 'Hi {username}' at the top of the page, then you need to look at Fragment caching.
Fragment caching is not as effective as page caching, since the output has to be stitched together from cached info and dynamic info, but it's usually still MUCH better than NO caching!
It's a bit of an art, to tweak the caching depending on what the page does and the load on the database, but it can make a page load many Orders of Magnitude faster than non-cached.
FYI - if the db queries are killing the site you may want to also look at taming them and/or caching their output individually, so that you don't have to keep hitting the database for the same information.
Also understand the 'varyByParam' for caching is pretty useful too - say you have a page in 3 languages, you can cache a page for each language by using the varyByParam, as long as your Url some sort of language component that the varyByParam can pick up.
HTH,
Lance

Building ASP.NET application - Best Practices

We are building an ASP.NET application and would like to follow the best practices. Some of the best practices are:
Server side Code:
Use catch blocks to trap & log low level errors too.
Use Cache objects to populate dropdowns etc. where we won’t expect the changes in the underlying data/database.
In case of error logging framework, provide emailing alerts along with logging the errors.
HTML code:
- Don’t write inline CSS.
- Place the JavaScript code (If needed by the page) at the end of the page unless the page needs it for load time actions.
Now coming to the point, Would you please share these best practice points if you have a comprehensive list of them already?
Some of the best practices that I've learned over time and written up for use at my company...many are mainly applicable to WebForms and not MVC.
Don't write .NET code directly in
your ASPX markup (unless it is for
databinding, i.e. Evals). If you
have a code behind, this puts code
for a page in more than one place and
makes the code less manageable. Put
all .NET code in your code-behind.
SessionPageStatePersister can be used in conjunction with ViewState
to make ViewState useful without
increasing page sizes. Overriding
the Page's PageStatePersister with a
new SessionPageStatePersister will
store all ViewState data in memory,
and will only store an encrypted key
on the client side.
Create a BasePage that your pages can inherit from in order to
reuse common code between pages.
Create a MasterPage for your pages
for visual inheritance. Pages with
vastly different visual styles should
use a different MasterPage.
Create an enum of page parameter key names on each WebForm
that are passed in via the URL, to
setup strongly-typed page parameters.
This prevents the need for hard-coded
page parameter key strings and their
probable mis-typing, as well as
allowing strongly-typed parameter
access from other pages.
Make use of the ASP.NET Cache in order to cache frequently used
information from your database.
Build (or reuse from another project)
a generic caching layer that will
wrap the ASP.NET Cache.
Wrap ViewState objects with Properties on your Pages to avoid
development mistakes in spelling,
etc. when referencing items from the
ViewState collection.
Avoid putting large objects and object graphs in ViewState, use it mainly for storing IDs or very simple DTO objects.
Wrap the ASP.NET Session with a SessionManager to avoid development
mistakes in spelling, etc. when
referencing items from Session.
Make extensive use of the applicationSettings key/value
configuration values in the
web.config - wrap the
Configuration.ApplicationSettings
with a class that can be used to
easily retrieve configuration
settings without having to remember
the keys from the web.config.
Avoid the easiness of setting display properties on your UI
controls, instead use CSS styles and
classes - this will make your styles
more manageable.
Create UserControls in your application in order to reuse common
UI functionality throughout your
pages. For example, if a drop down
list containing a collection of
categories will be used in many
places in the site - create a
CategoryPicker control that will data
bind itself when the page is loaded.
Use Properties on your UserControls to setup things like
default values, different displays
between pages, etc. Value type
properties can be defined on your
UserControls and then be set in your
ASP.NET markup by using class level
properties on UserControls.
Make use of the ASP.NET validation controls to perform simple
validations, or use the
CustomValidator to perform complex
validations.
Create an Error handling page that can be redirected to when an
unhandled exception occurs within
your website. The redirection can
occur via the Page_Error event in
your Page, the Application_Error
event in your Global.asax, or within
the section within the
web.config.
When working with pages that use a highly dynamic data driven
display, use the 3rd party (free)
DynamicControlsPlaceholder control to
simplify the code needed to save the
state of dynamically added controls
between postbacks.
Create a base page for all your asp.net pages. This page will derive from System.Web.UI.Page and you may put this in YourApp.Web.UI. Let all your asp.net pages dervice from YourApp.Web.UI.Page class. This can reduce lot of pain.
Use Application_OnError handler to gracefully handle any error or exception. You should log the critical exception and send the details of the exception along with date-time and IP of client to the admin email id. Yes ELMAH is sure way to go.
Use ASP.NET Themes. Many developers don't use it. Do use them - they are a great deal.
Use MembershipProvider and RoleProvider. And Never use inbuilt ProfileProvider - They store everything in plain strings. It will drastically slow-down the performance while performing R/W
Use Firebug for client-side debugging. Try to follow YSlow standards for web-applications. Use YSlow extension for FireBug.
Use jQuery for client-scripting.
Never store User Authentication information in session or don't use sessions to judge if user is logged on. Store only minimum necessary information in sessions.
Have a look at PostSharp. Can improve maintainability of your code and make you more productive.
Never ever Deploy asp.net application under debug configuration on production. Find out here what scottgu has to say about this.
User Web Deployment projects. It can transform web.config sections and replace with production server setings. It will merge all compiled code-behind classes into one single assembly which is a great deal.
Use Cookie-less domains to serve static resources like images, scripts, styles etc. Each client request is sent along with whole bunch of cookies, you don't need cookies while serving pictures or scripts. So host those resources on a cookie-less domain.
Minify scripts, stylesheets and HTML response from the server. Removing unnecessary line-breaks and white-spaces can improve the time-to-load and bandwidth optimization.
Forms:
Set Page.Form.DefaultFocus and Page.Form.DefaultButton to improve user experience
Check Page.IsValid in your Save button handler before proceeding.
General:
Understand and implement the techniques found in the article "TRULY Understanding ViewState"
Use Page.IsPostBack in your page events to stop code from running unnecessarily.
Use hyperlinks instead of posting and using Response.Redirect whenever possible.
a. Understand and use the second parameter of Response.Redirect (it "Indicates whether execution of the current page should terminate")
Use the Page Lifecycle properly.
Use the Per-Request cache (HttpContext.Items) instead of Cache where it makes sense.
Web.Config:
Deploy with <compilation debug="false">
Register your controls at the web.config level instead of the page level (i.e. #Register).
Themes:
When using Themes, put your static images in the Theme as well.
a. Don't link to the images directly from your markup, link to them from a skin file or css file in your Theme instead.
ex: <asp:Image SkinID="MyImage" runat="server" ImageUrl="Images/myImage.gif" />
I don't think try/catch blocks are always appropriate for low-level methods. You want to catch (and log/alert, even better!) any errors before they get to the user, of course. But it is often better for a low-level method to just lets its errors get raised up to a higher level. The problem I have seen with low-level error trapping is that it often lets a larger operation continue, but then a result that is not quite correct gets presented to the user or saved to the database, and in the long run it's much more difficult to fix. It's also just a lot of extra clutter in your code to put a try/catch at every level if you're not going to "do anything" with the error until it's raised up to a higher level.
Here are some similar questions that may help you.
.NET best practices?
Best way to learn .NET/OOP best practices?
This should probably be community wiki as well.
I would recommend a couple of books if you are interested in pursuing a journey to become a better, more productive developer. These books are language agnostic and as you can see by the user reviews, very very helpful.
Code Complete 2
Pragmatic Programmer
If you are looking for a .NET specific book, you may appreciate the following book:
Microsoft Application Architecture Guide [available online for free outside of print format]
ASP.NET
If you don't use Session state, don't
forget to turn off it.
Use Server.Transfer instead of Response.Redirect if possible.
Set expiration parameter in IIS.
Use GZip to compress the text files.
Use Server-Side and Client-Side validation together.
Use Url Rewriter or Routing to make friendly url for SEO.
Design
Write each class and its properties
of your CSS file in the same line. (To decrease the file size)
Use CSS Sprites. (To decrease request)

ASP.NET nested masters pages with CompilationMode="Never", a recepie for disaster? Bug in ASP.NET?

While working on a quite big web application project, I decided that it could gain a little bit of fresh air by marking some of the pages and controls with the CompilationMode="Never" #Page attribute. So far so good, working as expected and then it happened. A corner case scenario that I am going to explain behaved unexpectedly to put it nicely. This scenario is nested master pages.
A quick teaser before continuing. How deep nesting do you think you could go if you mark the top master page as CompilationMode="Always", and all others beneath it with CompilationMode="Never"? No, its not infinite, or some internal number that ASP.NET has. Its 2. Why? - I have no idea, and I was hoping some of you smart guys could enlighten me?
I have attached a project with 5 nested master pages to demonstrate what I am talking about: Nested Master Pages Web Application Test Project.
Another corner case that is working unexpectedly as well - if you have 5 nested master pages, change the second to have CompilationMode="Always" and all others to have CompilationMode="Never". You will notice that the 3rd master pages is being applied twice!
Please help me understand if something I am doing is incorrect, or confirm the issue.
ASP.NET Runtime Version: 2.0, .NET: 3.5
EDIT:
The project attached has all master pages set to CompilationMode="Never". The ASPX page displays as desired. Change the first master (Site.master) to have CompilationMode="Always" to see what I am talking about.
UPDATE (1/21/2010): Good news: after more investigation, it turns out that this issue was fixed in VS2010. The fix was made post Beta 2, so it will be part of the next public build. I don't have an exact date, but it should not be too far out.
Yes, I seem to recall this coming up before, and indeed some scenarios involving nester master pages and CompilationMode="Never" are broken.
Looking at an old mail thread, I think it only happens for certain combinations. It looks like it’s broken for (where NoCompile means compilationMode=never):
NoCompile Page / Compile Master / NoCompile Master
NoCompile Page / NoCompile Master / Compiled Master
At the time, we did not fix this because the fix was non trivial and the scenario is not common.
Note that when it comes to NoCompile pages, most of the benefit is using it for end node aspx pages, and not master pages. Generally, NoCompile pages run a bit slower than compiled pages. Their benefit is that they don't have a first time compile hit, and they use less memory. Also, they can be fully unloaded under memory pressure. That's why they make good sense when you have a super large number of end point pages (Sharepoint uses them). But on master pages (where most apps only have a small number shared by many pages), that benefit would be minimal. And of course you can't have code in NoCompile pages, which is the main reason that few people use them.
So the quick summary is: you're right, it's a bug! :) And the recommended workaround is to avoid CompilationMode=never for master pages.

Conditional Display in ASPX Pages on Sharepoint

I wonder what the best practice for this scenario is:
I have a Sharepoint Site (MOSS2007) with an ASPX Page on it. However, I cannot use any inline source and stuff like Event handlers do not work, because Sharepoint does not allow Server Side Script on ASPX Pages per default.
Two solutions:
Change the PageParserPath in web.config as per this site
<PageParserPaths>
<PageParserPath VirtualPath="/pages/test.aspx"
CompilationMode="Always" AllowServerSideScript="true" />
</PageParserPaths>
Create all the controls and Wire them up to Events in the .CS File, thus completely eliminating some of the benefits of ASP.net
I wonder, what the best practice would be? Number one looks like it's the correct choice, but changing the web.config is something I want to use sparingly whenever possible.
So in that case I would wrap it up in a feature and deploy it via a solution. This way I think you will avoid the issue you are seeing. This is especially useful if you plan to use this functionality within other sites too.
You can also embed web parts directly in the page, much like you do a WebControl, thereby avoiding any gallery clutter.
What does the ASPX page do? What functionality does it add? How are you adding the page into the site? By the looks of it this is just a "Web Part Page" in a document library.
I would have to do a little research to be 100%, but my understanding is that inline code is ok, providing it's in a page that remains ghosted, and thereby trusted. Can you add your functionality into the site via a feature?
I would avoide option 1, seems like bad advice to me. Allowing server side code in your page is a security risk as it then becomes possible for someone to inject malicious code. Sure you can secure the page, but we are talking remote execution with likely some pretty serious permissions.
Thanks so far. I've successfully tried Andrew Connel's solution:
http://www.andrewconnell.com/blog/articles/UsingCodeBehindFilesInSharePointSites.aspx
Wrapping it into a solution is part of that, but the main problem was how to get the code into that, and it's more leaning towards Option 2 without having to create the controls in code.
What I was missing:
In the .cs File, it is required to manually add the "protected Button Trigger;" stuff, because there is no automatically generated .designer.cs file when using a class library.
Well, it's a page that hosts user controls. It's a custom .aspx Page that will be created on the site, specially because I do not want to create WebParts.
It's essentially an application running within Sharepoint, utilizing Lists and other functions, but all the functionality is only useful within the application, so flooding the web part gallery with countless web parts that only work in one place is something i'd like to avoid.

Resources