Thursday, February 5, 2015

Introduction to ASP.NET MVC 3

Chapter 1. Introduction to ASP.NET MVC 3

- Visual Studio: Web Developer FREE Edition
- ASP.Net MVC 3 is present in "Visual Studio 2010 SP1"
- ASPX View Engine: It is a legacy view engine and is present for Backward compatibility.
MVC Design Pattern
       * Separates responsibilities of components in UI Layer.
       * Doesn't dictate which DALayer is to be used.
       * Doesn't dictate how domain layer should look like.
       * Doesn't care if your application has Layers or not.
       * It is design pattern for building UI and nothing more.
       * View is just a presentation template.
       * Controllers are responsible for responding to UI events.

Goals of ASP.Net MVC
       * Embracing WEB:
       * Runs on top of ASP.Net. Thus Modules, handlers, caching and diagnostics are reused from ASP.Net
       * Extensible
       * Testable
 
- ViewBag is dynamic object
- @ sign tells Razor engine to consider subsequent text as code.
- It is not necessary to have Models in the Models folder. They can be anywhere. Including all the projects referenced by MVC Project.


- Strongly Typed Model:  By default View treats @Model as dynamic. One can make @Model strongly typed by providing a directive which specifies type of model.




Chapter 2. Controllers

- Routing: Routing returns first matched entry.
- All public methods in Controller class are Actions. So they could be reached by client. So be careful in marking methods in Controllers as public.
- Action Results
ActionName: This attribute could be applied to a Controller method to alias it's Action Name.
AcceptVerbs: This attribute specifies Http verbs which could be used to Reach that Action.
- Action Filters: apply pre and post processing logic to Controller action and its logic.
                 : are components which contain cross cutting logic








Chapter 3. Razor Views

Difference between Response.Write and @. @ Also html encodes text.
- If Razor engine is treating piece of text as code, whereas you want it to be treated as html then there are two ways. 1. Surround the text with tags OR 2. Prefix the text with @:
- Layout views are Master pages for Razor views
- @* : Acts as comments in the Razor
- Views\_ViewStart.cshtml: This file mentions which Layout file is to be used for current application
- _ViewStart.cshtml is hierarchical.
- Individual views can alter inherited Layout.
- Code Sample: 











Partial Views: This is similar to User controls in ASP.Net Web Forms
- ChildActionOnly: This attribute for a Controller Action ensures that attributed Controller Action isn't viewable by user directly by entering URL. 




Chapter 5. Working with Data (Part 2)


- Data Validation Attributes: System.ComponentModel.DataAnnotations defines Attributes for Data Validations. Following are commonly used validation attributes.          * Required
      * StringLength
      * Regex
      * Range

Custom Validation: There are two ways
          1.  Custom Attributes deriving from ValidationAttribute.


          2.  Model class can implement IValidatableObject.


Chapter 6. Ajax and Javascript with ASP.Net MVC 3



- Putting Script tags at the bottom of the Html Page helps performance.
Razor Helpers: Reusable logic could be put in Razor Helpers.
                            : A RazorHelper in a view is available in that view only. To make this RazorHelper available across multiple Views, move this RazorHelper to Extention Method of HtmlHelper OR by making a reusable RazorView by adding that RazorView to a class in AppCode
Ajax.ActionLink: Builds an anchor tag. When user clicks on this anchor tag, a Ajax request is sent to server. This request could be linked to Actions in the Controllers.
Unobtrusive Javascript: Only rule is "Html files do not contain any javascript code. All javascript code is contained in external file marked as script file.
- If you refer other javascript files from current javascript file as follows, Visual Studio will include functions defined in other javascript file in Intellisense.
            ///
- Custom Editor Template is a partial View.  When a Template for a type T is required, MVC searches for a template named T. So when Editor for DateTime is required MVC will search for template named DateTime.




Chapter 7. Security 


- MVC 3 provides two Types of Authentication out of box.
              1. Forms Authentication :
                             * For Public websites
                             * Customizable
                             * Typically relies on Cookies
                             * SSL is required to make web site secure.                          
               2. Windows Authentication (Integrated Authentication) : 
                          Good for Intranet Apps. Gives Single Sign On experience to users. 
                          Users need to be on same Windows Domain.
- Authorize attribute (without parameter) on Controller Action tells MVC that only authenticated users should be allowed to use this Action.  A role name could be sent to Authorize attribute and then that users in that role would only be allowed to use that Action.
ASP.Net Membership : Provides functionality for User Account Management. Default Provider is SQL Server, which saves User data in SQL Server. This Provider allows to create a user, Delete a user, Change Password etc.
aspnet_regsql: This utility adds/removes Membership Providers tables to a database.
- When using Windows Authentication, Roles map to groups created on server or Active Directory.
- Forms Authentication on Plain HTTP: Username password entered by user will be sent to Server as plain text. So if somebody is sniffing the network or capturing network traffic, he will be able to capture username and password. Solution to this is to use HTTPS, which encrypts username and password.
- This blog explains how to work with SSL at development time.
http://www.hanselman.com/blog/WorkingWithSSLAtDevelopmentTimeIsEasierWithIISExpress.aspx
XSS (Cross Site Scripting): Malicious user will use website to load malicious script or ActiveX Control or Html into user's browser. They will try to do this by getting to your site and trying to get your site to accept some input from a form input or a query string and have your site echo back that input into a page without proper encoding. 


- Microsoft provides AntiXSS library. It has Sanitizer.GetSafeHtmlFragment (body) method in it. This method has white list of allowed html tags. If input body contains any tag which is not part of this white list will be filtered by this method.




Chapter 8. ASP.Net Infrastructure for MVC


- Output Caching : Allows to store (cache) output of Controller Action in memory.
OutputCache attribute of Action : Use this attribute to Output cache result of Action.
- Best Practice : Do not enable Output Caching unless performance is monitored.
Localization : Two setting impact how application behaves under different cultures
        * Thread.CurrentCulture property impacts formatting (e.g. DateTime.Now.ToString())
        * Thread.CurrentUICulture impacts resource loading
 ASP.Net can set cultures according to HTTP headers
        * Http Header: Accept-Language
        * Use globalization section in web.config
- Logging Options
        * ASP.Net Health Monitoring
        * Log4Net
        * Microsoft Application Block: Logging
        * elmah (code.google.com/p/elmah)
- Machine wide web.config file contains section. Which tells how various health monitoring events should be treated. It contains following sections.
        * Where can a event be written.
        * Categories of Events


        * Specifies what events go to what event providers. Maps EventMapping to Providers.




Chapter 9. TDD and Unit Testing

TDD Cycle
        * Red: Write a Failing Test
        * Green: Write Code to Pass test
        * Refactor : Refactor code to improve design


- StrucutreMap-Mvc is IoC (Inversion of Control) Container for MVC.



Chapter 10. Configuration and Deployment

- The Views folders has local web.config
HandleErrorAttribute this filter ensures that Custom Error page is shown. This filter respects setting in web.config.
aspnet_regiis : utility registers ASP.Net with IIS. Exact command is "aspnet_regiis.exe -i". Working folder for this command needs to be .Net Folder.

No comments:

Post a Comment