Search This Blog

Monday, December 15, 2008

ASP.Net Coding & Performance Tips

ASP.net Tips

from http://www.codersource.net/asp_net_simple_tips.html


1.Smart navigation

Smart navigation is a little-known Internet Explorer feature that enables the individual controls on your Web forms to maintain focus between postback, as well as allows you to suppress that flicker that occurs as you load the new page.
To turn on this little-known feature, simply set the smartNavigation property of your ASPX page to True. You can also apply the property to all project pages, by adding the tag to the following location within your Web.config file:

<--configuration system.web pages smartNavigation="true"/ /system.web /configuration -->

Note that smart navigation works on only Internet Explorer 5 and above; however, ASP.NET will automatically detect this and serve up the ?smart? code only if the target browser supports it.

Also,I'd personally advise that you test it against any third-party menu controls or scripts you may have running: it is prone to falling over on particularly advanced pages.


2.Stopping Your User from Right-Clicking


Want to prevent your user from performing any of the other commands available by right-clicking on a Web page in Internet Explorer? It?s not foolproof, but this neat little HTML edit usually does the trick.

Just alter the opening tag of your HTML to the following:

BODY oncontextmenu="return false">

When the menu is requested, the oncontextmenu event runs, and we instantly cancel it using JavaScript. This is especially potent as a method for stopping the user from viewing your source, when used in conjunction with a menu-less browser window. Great stuff!

3.Creating Images Dynamically

Ask any ASP developer who has ever tried to dynamically create his own images and he?ll tell you it?s a nightmare. In fact, it?s more than a nightmare. It?s practically hell. The only true solution? Reverting to an expensive, dodgy, third-party control to do the work for you.

With ASP.NET, however, you can develop your own dynamic images with ease. Simply create an image object and use the new GDI+ features to add objects to that image, such as text, rectangles, and ellipses. After that, you can simply stream straight back down to the client.

But covering the graphics features in depth would require at least another two books, and, unfortunately, we don?t have that much room. So, I?m going to share a sample that demonstrates creating a small ?Drawing? button, alongside a little blue-and-yellow bullet point.It?s the sort of personalized graphic you?ll find on sites such as Amazon.com.

Here's the code:

Bitmap objBitmap = new Bitmap(120, 30);
Graphics objGraphics = Graphics.FromImage(objBitmap);
objGraphics.FillRectangle(new SolidBrush(Color.LightBlue), 0, 0, 120, 30);
objGraphics.FillEllipse(new SolidBrush(Color.Blue), 3, 9, 10, 10);
objGraphics.FillEllipse(new SolidBrush(Color.Yellow), 4, 10, 8, 8);
objGraphics.DrawString("Drawing", new Font("Tahoma", 8), new SolidBrush(Color.Green), 16, 8);
Response.Clear();
Response.ContentType = "image/jpeg";
objBitmap.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
objGraphics.Dispose();
objBitmap.Dispose();


You can put it inside any event you want.

4.Clear All The Textbox Values (Reset Function)

In Classic ASP, to clear all the textboxes in a form, to start over, we just had to use a simple html 'Reset' button in the form. Sometimes that works in ASP.Net;sometimes it doesn't.

Here are a couple of ways to do this, iterating through the ASP.Net TextBox controls in a form --
Just create a Reset type subroutine - in that routine, use the following code:
in C# - it would be:

Control myForm = Page.FindControl("Form1");
foreach (Control ctl in myForm.Controls)
if(ctl.GetType().ToString().Equals("System.Web.UI.WebControls.TextBox"))
((TextBox)ctl).Text = "";

This will clear EVERYTHING from the textboxes - even if you had them pre-populated with data. A VERY simple way to just reset it to the condition at Page_Load time, just do this in the Reset SubRoutine:

Server.Transfer("YourPageName.aspx")

5.Pressing Enter key

Sometimes, you will notice, that, in an ASP.Net form, depending on the circumstances, pressing the 'Enter' key to submit the form does not work.

To force this to happen for a particular button on your page, just put this in the Page_Load routine:

Page.RegisterHiddenField("__EVENTTARGET", "button1")

Then, change 'button1' to the ID of your particular button. Understand, of course, if your cursor is inside of a MultiLine textbox, the default action of the enter key is to create a new line in the textbox, so, if this basically works anywhere outside of that scenario.
6.ASP.Net Server Controls Not Showing on pages

It's possible that ASP.Net is not registered correctly on your system.Try running aspnet_regiis from the command prompt
.

Here's the default location:

C:\WINNT\Microsoft.NET\Framework\<>\aspnet_regiis.exe -i

Windows Server 2003, you must use aspnet_regiis -i -enable. This is because of the "Web Service Extensions" feature in IIS 6

7.Where To Store Database Connection

Let's say you have a database connection (or several) that you will be using over and over. Yes, you can manually copy/type it in on every ASP.Net page - BUT - an easier way is to store it in the Web.Config file (formerly config.web) and then refer to it in the code.

In Web.Config, you would add a key to the AppSettings Section:

appSettings>
add key="MyDBConnection" value="server=YourServer;uid=Username;pwd=Password;database=DBName" />


for OleDb - use Absolute Path - Not Server.MapPath:
add key="NWOleDB" value= "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Inetpub\wwwroot\data\northwind.mdb;" />

Then, in your ASP.Net application - just refer to it like this:

SqlConnection myConnection = new SqlConnection(ConfigurationSettings.AppSettings("MyDBConnection"));


Sunday, December 14, 2008

Quick Tips For ASP.Net

Quick Tips For ASP.Net

from http://simpable.com/code/quick-tips-for-asp-net-part-one/

written by Scott Watermasysk on Thursday, February 15 2007

Just about everyone has been to a session on ASP.Net best practices, read a book or 10 on the subject, and possibly even a couple of blog posts or MSDN articles. This post is NOT one of them. It is simply a quick list of tips and suggestions for making your ASP.Net application a little better.

I jotted down the tips below over the course of the morning. It is by no means exhaustive and I hope to publish another set of tips or two shortly. If you have any other suggestions/tips, please list them below. If you are not the kind of person who likes to comment on a blog, please drop me a line at scottwater@gmail.com. I will either add them below or create another post and list them. I am also working on a set of caching tips, so if you have any of them, there will be a specific post related to caching.

Tip: Do not use the AutoPostBack attribute on the DropDownList control to simply redirect to another page.

There are probably cases when this might make sense, but for the most part it is overkill. Using the autopostback for a redirect requires extra roundtrip to the server. First the autopostback returns to the server and processes everything up to the event handling the postback. Next a Response.Redirect is issued which goes back to the client requesting the client use another page. So you end up with two separate requests + processing just to get a user to another page.

Using the onchange event of the select element, we can do this all on the client. In the sample below, I am simply redirecting to the current page with an updated querystring element. Your logic will vary, but in the case below, I am avoiding the zero index.

0) { window.location = window.location.pathname + '?t=' + this[this.selectedIndex].value;}" />

Tip: Never use the ASP.Net Label control.

Ever is a strong word, but except for some quick and dirty style hacks you should never ever use this control. Any text is rendered inside a span control which is usually unnecessary and complicates any CSS styling you may be trying to use. In most cases, you can replace the Label with a Literal and achieve the same results.

Tip: Use the ASP.Net Repeater instead of DataList, DataGrid, and DataView controls

The Repeater is the single most powerful control shipped in ASP.NET. It is versatile and lightweight. There are times (especially prototyping) when the other databound controls make sense to use, but they generate a lot of extra markup and generally complicate the page with all of their events and styling. Using the Repeater, you may write a little more code up front, but you will be rewarded in the long run.

Tip: Understand how to effectively use caching.

By now, most ASP.NET developers know about the Cache. Most examples show the virtue of caching for hours at a time. Very little data that is worth the effort to display on a web page requires caching for this long. The main reasons for caching are performance related. Memory in ASP.NET is still a very limited resource. Do not waste it by caching anything more than a couple of minutes unless it is very expensive to regenerate.

Tip: Always set a memory threshold for your AppPool.

A related tip would be to first understand the total memory available on your box: how many sites are there, is SQL running locally? Is there anything else on this box which will consistently use Memory?

In most cases, you should never set the available memory for an AppPool above 800mb's unless you can also set the 3/gb switch (then you can use about 1200mb). Allowing memory to go unchecked or set about 800mb can bring even a moderately sized site to it's knees once too much memory is used.

Tip: Use AppOffline.htm for updates

If you are making any changes to files in your bin directory, always use the AppOffline.htm file. It is very likely that while you uploading (or copy & pasting) your updates, users will see an error message. It is much better to show them one that you purposely created and can explain the situation vs. the built in ASP.NET error pages (or even your own customError page). In addition, this will help prevent the locking .dll issue that is not supposed to exist anyway.

Tip: Always check Page.IsValid in your button's EventHandler.

Just because you are using ASP.Net validation controls, do not assume the page could not be submitted with invalid data.

Also, just because you hide a control, do not assume buttons/textboxes/etc on it are not submit-able. It is perfectly fine to hide a control that a user should not access, but with very little code (or using a third party tool) users can easily make an HttpPost with any data they choose.

Tip: When redirects are permanent, use a 301 status code.

This use to be a little more manual, but with ASP.NET 2.0, it is even easier:

Response.RedirectLocation = "http://site.com/newlink.aspx";
Response.End();

Tip: To create fully qualified URLs, use the new VirtualPath class.

string relativePath = "~/somefolder/test/123.aspx"
Uri newUri = new Uri(Request.Url, VirtualPathUtility.ToAbsolute(relativePath));

Again, please add any other suggestions below. I am looking forward to reading them.

Update: It looks like there is a case for using the Label control as an html label element (for accessibility). I was unaware of this functionality and will call it out better in another tip installment. Thanks Phil and Dusty!