Thursday, July 29, 2010

ASP.NET webforms best practices

  • Don’t write .NET code directly in your ASPX markup (unless it is for databinding, i.e. Eval statements). If you also have a code behind, this will put your code for a page in more than one place and makes the code less manageable. Put all .NET code in your code-behind. Things can get complex and difficult to debug very quickly when you’re looking at code executing in two different places.
  • 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. This will make your pages smaller and download faster if you have a lot of ViewState data for some reason, however it will increase your memory usage on the server – so tread carefully. See example below for how to use SessionPageStatePersister.
public override PageStatePersister GetStatePersister() 
{
return new SessionPageStatePersister(this);
}

  • Create a BasePage that your pages can inherit from in order to reuse common code between pages. Simple object oriented design principles – if you have common functions between pages, like security for example – put it in a base class that inherits from System.Web.Page, and have your pages inherit from that base page.
  • Create a MasterPage for your pages for visual inheritance. Don’t use ASP server-side includes. Pages with vastly different visual styles should use a different MasterPage. Don’t use a Master page for code inheritance.
  • Make use of the ASP.NET Cache in order to cache frequently used information from your database. Build (or reuse) a generic caching layer that will wrap the ASP.NET Cache. If you’re loading the same list from the database into a drop down every time a page loads, you should be pulling that list from the cache based on how dynamic it needs to be.
  • Wrap ViewState objects with Properties on your Pages to avoid development mistakes in spelling, etc. when referencing items from the ViewState collection. For example, you should only have ViewState["key"] once in your page per property. See example below.
private int SampleId
{
    get { return ViewState["SampleId"] == null ? 0 : (int)ViewState["SampleId"]; }

    set { ViewState["SampleId"] = value; }
}
  • Avoid putting large objects and object graphs in ViewState, use it mainly for storing IDs or very simple DTO objects. This is the reason people always complain about huge viewstate – they’re storing something like DataSets in ViewState (terrible idea). If you stick to small objects with a limited number of properties or just integer IDs, your ViewState data will not be unmanageably large and ViewState is totally usable.
  • Wrap the ASP.NET Session with a SessionManager class to avoid development mistakes in spelling, etc. when referencing items from Session. Just another way to cut down simple development mistakes.
  • 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 strongly-typed configuration settings without having to remember the keys from the web.config. If you have settings, behaviors, etc. that need to change between different deployments of your application, those should be control via settings in the web.config. For example, we’ll often get requests like ‘We want feature X to go live at the end of the month” – so build, test, and deploy the update ahead of time. But, add a web.config value that controls whether or not the feature appears i.e. FeatureXEnabled=”False”, on the day of go live just flip it to “True”.
  • Avoid the easiness of setting display properties on your UI controls, instead use CSS styles and classes – this will make your styles more manageable. Just a general web development best practice.
  • 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. This is my #1 time-saving best practice, yet I’m always surprised how often I see the same drop down list with the same data getting used the same way on 20 different pages – yet the same type-unsafe databinding logic is duplicated 20 times!
  • 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. This is a great way to get even more mileage out of reusing your UserControls – watch out for increased complexity of your UserControl logic though.
  • Make use of the ASP.NET validation controls to perform simple validations, or use the CustomValidator to perform complex validations.
  • Create an user-friendly error handling page that can be redirected to when an unhandled exception occurs within your website. Log any exceptions that come to this page. The redirection can occur via the Page_Error event in your Base Page, the Application_Error event in your Global.asax, or within the error handling section in the web.config. Basically, whichever method you pick – make sure you’re not letting any exceptions go unhandled or unlogged!
  • When working with pages that use a highly dynamic data driven display, use the 3rd party (free)DynamicControlsPlaceholder control created by Denis Bauer to simplify the code needed to save the state of dynamically added controls between postbacks. This little control has saved me countless hours of pain in creating pages with highly dynamic UserControls. One gotcha – if you use event handling delegates in a UserControl, you have to hook them up on every postback, little messy but not a big deal though usually. Event handlers are the only “state” that isn’t saved between postbacks if you use this control.
  • Turn ViewState off on controls and UserControls that don’t need it.

    Friday, July 23, 2010

    Sending Email using ASP.NET 4

    Sending and email would be an integral part of any web application and with .NET framework its very simple - you just need few lines of codes! Now here we go into the details:

    For sending emails we will look into classes provided in the System.Net.Mail namespace. Previously in .NET 1.x these functionalities were in System.Web.Mail namespace which has now been deprecated. There are a bunch of classes defined in this namespace but the ones that we should be concerned about are:

    1. MailMessage - represents an email message; has properties like From, To, Subject, Body, and so on
    2. SmtpClient - sends a specified MailMessage instance to a specified SMTP server.
    Having know the basics you can follow the following steps to complete the task at hand:
    1. Create a MailMessage object
    2. Assign its properties
    3. Create an instance of the SmtpClient class
    4. Specify details about the SMTP server to use (if they're not already specified within Web.config - Yes! you can provide the details of SMTP server in Web.config file but the details of it are out of scope for our task at hand - just the basics here)
    5. Send the MailMessage via the SmtpClient object's Send method
    Below is a sample page to send an email with its aspx and code behind pages included.



    The aspx page:
     DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title>title>
    head>
    <body>
        <form id="form1" runat="server">
        <div>
            Message to:
            <asp:TextBox ID="txtTo" runat="server">asp:TextBox>
            <br />
            Message from:
            <asp:TextBox ID="txtFrom" runat="server">asp:TextBox>
            <br />
            Subject:
            <asp:TextBox ID="txtSubject" runat="server">asp:TextBox>
            <br />
            Message Body:
            <br />
            <asp:TextBox ID="txtBody" runat="server" Height="171px" TextMode="MultiLine" Width="270px"><asp:TextBox>
            <br />
            <asp:Button ID="Btn_SendMail" runat="server" onclick="Btn_SendMail_Click" Text="Send Email" />
            <br />
            <br />
            <asp:Label ID="Label1" runat="server" Text="Label">asp:Label>
        div>
        form>
    body>
    html>

    Code behind:
    using System;



    using System.Web.UI.WebControls;
    using System.Net.Mail;
    public partial class SendMail : System.Web.UI.Page
    {
        protected void Btn_SendMail_Click(object sender, EventArgs e)
        {
            MailMessage mailObj = new MailMessage(
                txtFrom.Text, txtTo.Text, txtSubject.Text, txtBody.Text);
            SmtpClient SMTPServer = new SmtpClient("localhost");
            try
            {
               SMTPServer.Send(mailObj);
            }
                catch (Exception ex)
            {
                Label1.Text = ex.ToString();
            }
        }
    }

    Wednesday, July 21, 2010

    Regular Expressions aren't just regular stuffs for expressing!

    Regular expressions are strings formatted using a special pattern notation that allow you to describe and parse text. Many programmers (even some good ones) disregard regular expressions as line noise, and it’s a damned shame because they come in handy so often. Once you’ve gotten the hang of them, regular expressions can be used to solve countless real world problems.
    Regular expressions work a lot like the filename “globs” in Windows or *nix that allow you to specify a number of files by using the special * or ? characters (oops, did I just use a glob while defining a glob?). But with regular expressions the special characters, or metacharacters, are far more expressive.
    Like globs, regular expressions treat most characters as literal text. The regular expression rage, for example, will only match the letters r - a - g - e, in that order. But regular expressions sport an extensive set of metacharacters that make the simple glob look downright primitive.

    Meet the metacharacters: ^[](){}.*?\|+$ and sometimes -

    I know, they look intimidating, but they’re really nice characters once you get to know them.

    The Line Anchors: ‘^’ and ‘$’

    The ‘^’ (caret) and ‘$’ (dollar) metacharacters represent the start and end of a line of text, respectively. As I mentioned earlier, the regular expression rage will match the letters r- a - g - e, but it will match anywhere in a line (e.g. it would match “I’m rage”, or even “barrage”). The ‘^’ character is used to anchor the match to the start of the line, so ^rage would only find lines that start with rage. Similarly, the expression rage$ would only find r - a - g - e at the end of a line (but would still match ‘barrage’).
    If we combine the two line anchor characters we can search for lines of text that contain a specific sequence of characters. The expression ^rage$ will only match the word rage on a line by itself - nothing more, nothing less. Similarly the expression ^$ is useful for finding empty lines, where the beginning of the line is promptly followed by the end.

    The Character Class: ‘[]‘

    Square brackets, called a character class, let you match any one of several characters. Suppose you want to match the word ‘gray’, but also want to find it if it was spelled ‘grey’. A character class will allow you to match either. The regular expressiongr[ea]y is interpreted as “g, followed by r, followed by either an e or an a, followed by y.”
    If you use [^ ... ] instead of [ ... ], the class matches any character that isn’tlisted. The leading ^ “negates” the list. Instead of listing all of the characters you want to included in the class, you list the characters you don’t want included. Note that the ^ (caret) character used here has a different meaning when it’s used outside of a character class, where it is used to match the beginning of a line.

    The Character Class Metacharacter: ‘-’

    Within a character-class, the character-class metacharacter ‘-’ (dash) indicates a range of characters. Instead of [01234567890abcdefABCDEF] we can write [0-9a-fA-F]. How convenient. The dash is a metacharacter only within a character class, elsewhere it simply matches the normal dash character.
    But wait, there’s a catch. If a dash is the first character in a character class it is not considered a metacharacter (it can’t possibly represent a range, since a range requires a beginning and an end), and will match a normal dash character. Similarly, the question mark and period are usually regex metacharacters, but not when they’re inside a class (in the class [-0-9.?] the only special character is the dash between the 0 and 9).

    Matching Any Character With a Dot: ‘.’

    The ‘.’ metacharacter (called a dot or point) is shorthand for a character class that matches any character. It’s very convenient when you want to match any character at a particular position in a string. Once again, the dot metacharacter is not a metacharacter when it’s inside of a character class. Are you beginning to see a pattern? The list of metacharacters is different inside and outside of a character class.

    The Alternation Metacharacter: ‘|’

    The ‘|’ metacharacter, (pipe) means “or.” It allows you to combine multiple expressions into a single expression that matches any of the individual ones. The subexpressions are called alternatives.
    For example, Rage and Random are separate expressions, but Rage|Randomis one expression that matches either.
    Parenthesis can be used to limit the scope of the alternatives. I could shorten our previous expression that matched Rage or Random with creative use of parenthesis. The expression Ra(ge|ndom) matches the same thing. I probably would use the first expression in practice, however, as it is more legible and therefore more maintainable.

    Matching Optional Items: ‘?’

    The ‘?’ metacharacter (question mark) means optional. It is placed after a character that is allowed, but not required, at a certain point in an expression. The question mark attaches only to the immediately preceding character.
    If I wanted to match the english or american versions of the word ‘flavor’ I could use the regex flavou?r, which is interpreted as “f, followed by l, followed by a, followed by v, followed by o, followed by an optional u, followed by r.”

    The Other Quantifiers: ‘+’ and ‘*’

    Like the question mark, the ‘+’ (plus) and ‘*’ (star) metacharacters affect the number of times the preceding character can appear in the expression (with ‘?’ the preceding character could appear 0 or 1 times). The metacharacter ‘+’ matches one or more of the immediately preceding item, while ‘*’ matches any number of the preceding item, including 0.
    If I was trying to determine the score of a soccer match by counting the number of times the announcer said the word ‘goal’ in a transcript, I might use the regular expression go+al, which would match ‘goal’, as well as ‘gooooooooooooooooal’ (but not ‘gal’).
    The three metacharacters, question mark, plus, and star are called quantifiers because they influence the quantity of the item they’re attached to.

    The Interval Quantifier: ‘{}’

    The ‘{min, max}’ metasequence allows you to specify the number of times a particular item can match by providing your own minimum and maximum. The regex go{1,5}alwould limit our previous example to matching between one and five o’s. The sequence {0,1} is identical to a question mark.

    The Escape Character: ‘\’

    The ‘\’ metacharacter (backslash) is used to escape metacharacters that have special meaning so you can match them in patterns. For example, if you would like to match the ‘?’ or ‘\’ characters, you can precede them with a backslash, which removes their meaning: ‘\?’ or ‘\\’.
    When used before a non-metacharacter a backslash can have a different meaning depending on the flavor of regular expression you’re using. For perl compatible regular expressions (PCREs) you can check out the perldoc page for perl regular expressions. PCREs are extremely common, this flavor of regexes can be used in PHPRuby, andECMAScript/Javascript, and many other languages.

    Using Parenthesis for Matching: ‘()’

    Most regular expression tools will allow you to capture a particular subset of an expression with parenthesis. I could match the domain portion of a URL by using an expression like http://([^/]+). Let’s break this expression down into it’s components to see how it works.
    The beginning of the expression is fairly straightforward: it matches the sequence “h - t - t - p - : - / - /”. This initial sequence is followed by parenthesis, which are used tocapture the characters that match the subexpression they surround. In this case the subexpression is ‘[^/]+’, which matches any character except for ‘/’ one or more times.

    Want to know more?
    I’ve only touched the surface on what can be done with regular expressions. If want to learn more, check out Jeffrey Friedl’s book Mastering Regular Expressions. Friedl did an outstanding job with this book, it’s accessible and a surprisingly fun and interesting read, considering the dry subject matter.
    Check out my follow up to this article where I take a look at some of the most useful regular expressions for common programming tasks. And once you understand the basics read on to learn all you need to know to become a regex pro.

    .NET for dummies series

    Soon I'll be posting several articles over upcoming months about varisou topics in .NET and ASP.NET from a learners perspective.

    Hope it will be helpful to all.

    Sunday, July 18, 2010

    Productive things that one can do while not working!

    Here are the list of stuffs that you can indulge in while not working and still be productive.

    1. Check delicious popular tags like ‘useful,’ ‘tutorials,’ ‘tips,’ ‘howto,’ ‘advice,’ ‘entrepreneurship,’ etc. for interesting, educational articles to read.
    2. Watch one of the thousands of educational videos streaming at TED.com,Academic Earth and Teacher Tube.
    3. Read an online book list and find a new book to grab next time I’m at the library.  Here’s another list.  And another.  And another.
    4. Read a classic book online for free at Project GutenbergPlanet eBook, or the E-books Directory.
    5. Research a new Do It Yourself project at DIY NetworkInstructables,eHow, or WikiHow.
    6. Add to, delete from, or just generally sort my ongoing to-do list atRemember The Milk.
    7. Create a cool graphical mind map of some of my recent ideas at bubbl.us.
    8. Email a close friend or family member I haven’t spoken to in awhile.
    9. Backup my recent photos, documents, and other important files online using Microsoft’s free 25 gig SkyDrive.
    10. Use Wikipedia’s random article function to pick a random article to read.
    11. Touch up on my math and science skills over a the Khan AcademyMIT OpenCourseWare, or LearningScience.org.
    12. Send a paper greeting card directly to a friend or relative at enGreet.
    13. Start learning a new language online for free at BBC Languages orLivemocha.
    14. Watch one of the insightful 6 minute and 40 second presentations atIgnite Show.
    15. Use Memorize Now to memorize a cool joke, or poem, or whatever.
    16. Use Media Convert to convert video files I have on my computer into a format I can view on my iPhone or iPod later on.
    17. Listen to an educational podcast over at Odeo or via iTunes on iTunes U.
    18. Read one of the academic journals at the Directory of Open Access Journals.
    19. Share my favorite mp3s, photos, videos, etc. with friends and family usingDropbox.
    20. Get a free college education online using this guide from Lifehacker (or read one of the other useful articles on Lifehacker).
    21. Inspire and spark my creative mind by looking at a rolling slideshow of the highest rated photos on Flickr for the last 7 days.
    22. Catch up on a short history lesson at HyperHistory or The Internet History Sourcebooks Project.  Or find out what happened today in history.
    23. Take a fun, educational online quiz at Quizlet.
    24. Play an educational online game at LumositySporcleGames for the Brain, or Math Run.
    25. Add a little gentle rain to my environment using RainyMood.com and then simply meditate and relax in my computer chair for 10 minutes.
    26. Sell old stuff I no longer need on eBay and make a little extra cash.
    27. Find a new musical artist to listen to based on music I like at Grooveshark,Pandoralast.fm, or Deezer.
    28. Find out what’s happening in our world from quality international news sources like BBC News and Reuters.

    This article has been referenced from here.