KnockoutJS Starter

So, what is knockout? A javascript library. At its core, a javascript library that can be included in a web site/application too add js functionality and enhance user’s experience. Knockout – A MVVM (model-View-ViewModel) library.

image

A Model is an object that usually most directly represent a real-world object in the business system. It contains properties and functions that have business like names and reactions.

Such as an Automobile:
properties: MaxSpeed(Number), TireSize(Number), Manufacturer(String)
functions: Honk() and DriveForward()

A View is the HTML markup that describe the layout, elements (buttons, textboxes), colors and other visual pieces. No logic or code embedded in it. It’s completely declarative.

A ViewModel a connection between the View and the Model. (???) If you are making a ViewModel for a View that was designed to display automobiles, it might have properties such as: AutomobileCollection(Array), SelectedAutomobile(Obj), and functions: AddAutomobile(), SortAutomobile() etc.

Binding: connecting the properties and events of user interface elements (HTML) to functions and properties of an object such as ViewModel. Example: Connect a [AddAutomobile] button (and/or other buttons) with ViewModel’s AddAutomobile() method.

Installation

Step 1: make sure you have a text editor (we use VS 2012), web server, web browser

Step 2: Create a starter site. Download from http://html5boilerplate.com/ a starter site that will be used for this exercise. Open it in VS 2012.
image

Also, update the index.html to:
image

Step 3: Download knockout!

Use Nuget Manager to download and install KnockoutJS
image

The knockout files will be copied under the /Scripts folder. Copy them to under /js so all JavaScript files are under the same roof.
image

Step 4: Create main application javascript file – App.js – and place in /js.
Add the reference to the 2 javascript files in the starter HTML file
image

(Include javascript file at the end of the HTML file so the visual components can be displayed first)

Step 5: Run the app.
image
Verify in Filddler2 that the browser did download the two js files.
image

Now build an Inventory Management application

(1) Defining a namespace in App.js – just add the following two lines
// defining a name space “myApp”.
window.myApp={};

(2) Creating Model (class) under the namespace

Define a [Product] class under the namespace [myApp]
image

// Usage
// create an instance of the Product class
var productA = new myApp.Product();
// “set” the ‘sku’ property
productA.sku(‘12345’)
// “get” the ‘sku’ property value
var skuNumber = productA.sku();

(3)  Creating a view for the Model – now that we have a product, we want to let user visually see the product on the screen.

Add these HTML t index.html’s “content” div.
image

(4) Creating a ViewModel to manage out Models (/JS/ProductsViewModel.js)
Similar to creating the Product class. ViewModel’s contains functions/methods that manipulate models (class), for example, AddProduct( ), RemoveProduct( ) etc.
image

(5) In JS, the data structure used for maintaining list of objects is array. Knockout uses “Observable Array”This types of array raises event when it changes. The event allows Knockout to keep our UI up-to-date whenever Observable Array changes.

Add a new property to our new ViewModel –
image|

(6) Add/removing models from an Observable Array (still, update the ProductsViewModel.js)

addNewProduct : first instantiate a new Product, then make it the currently selected product.
doneEditingProduct is to commit the save action.
image

Logic for removing: checking for null, and then pull out of the collection

image

Add 3 buttons to the index.html ad bind the click event to the functions defined in the ProductsViewModel.js
image

Step 7: Editing Model properties. The current index.html s display only, but we need a way to enter products info so we can add/update them. So update the index.html so it’s a form with input elements.

image

Step 8 – Setting up master-details view
First we need to show/hide the 3 buttons based on whether there is any product selected. So set the visible property based on the selectedProduct() function.
image

hide/Show button depending on whether there is selected product.
image

Now we need to provide our users a way to view the master list of products that they’re managing. Often we see grids, tables, unordered lists, or other widgets designed to display list of objects, but knockout is powerful enough that we can use simple HTML to provide a view into productCollection.

We’re going to provide a basic list-view using a select element. Knockout provides a [options] binding that allows us to bind an observable array to a select element.

11:41pm, 01/15/2013, Page 20

Add these two to the ProductsViewModel – don’t know why, but will see later.
image

In HTML, add this <select>….</select>, using “options” to bind to the productCollection.
image

optionsText – which property of each element in the Observable Array we want to appear in the select element’s options? It’s like a bind field.

What if you want to bind to sku + ‘ ‘ + description? (bind to two fields), then you need to add a [Computed Observables] to the productsViewModel, like this:
image

Then you can use the new property in the optionsText:
image

Step 9: Applying Binding – for this app to run, need to kick off the binding process. Need to wait (1) the scripts are loaded and (2) viewmodels initialized before the process is invoked. Add this to App.js

(Application still not working – got error (sku id undefined) – will check again after finishing this book)
image

Page 23: Top features you need to know about

One of the best part about Knockout is extensibility.

Subscribables
Under the cover of observable, observable arrays and computed observables is subscribable. It’s simply an object that has three methods and an array of subscription.
methods:
(1) subscribe – adds a Subscription callback for a certain topic to be invoked when subscriptions are “notified”. The default topic (event???) is “changed”.
(2) notifySubscribers: This calls all subscriptions for a certain topic and passes on argument to all the subscription;s callbacks.
(3) extend – applies an extender to the subscribable object.

Observable
one of the first objects that leverages the Subscribable functionality. Most simple, powerful of the knockout family.

Skipping the rest of them book. Sample codes are hard to understand. Move on to another one and maybe come back later to review.

01/16/2013, 09:14pm

Posted in Uncategorized | Leave a comment

Use Code First with an Existing Database

Benefits: You can create database schema first, and then use [Visual Studio Power Tool] (need separate installation; it’s a plug-in to VS 2012) to “reverse engineer” the database into code first models in your solution.

1. First come here to install EF Power Tool (need to re-start VS 2012 after installation)
http://visualstudiogallery.msdn.microsoft.com/72a60b14-1581-4b9b-89f2-846072eff19d

2. Launch VS 2012, and create a new MVC 4 internet project.

3. Next, assuming you have an existing database: DSP in SQL 2008, with all the tables, primary keys and foreign key defined.
image

4. You can start to “reverse engineer”. First right click your MVC web site project ==> Entity Framework –> Reverse Engineer Code First.
 
image 

5. in the [Connection Properties] window, enter the server info/credentials/and database name, and click OK.
image

6. At lower left you will see it working hard to convert the tables into classes/entities:
image

7. When done, in the [Model] folder, you will see the DbContext class created:
 image

and a connection string is added to web.config
image

It defines all DbSet for all entities/tables.
image

and all models (tables) are created too:
image

For example, the dspBackup.cs:
image

In the /Models/Mapping folder, a separate *.CS file is created for each model. It defines the key, and relationship between models and other properties related to the model.

image

8. Now you can start using EF to code your actions!!!! Such a great feature.

09:38 pm, 01/14/2013

Posted in Uncategorized | Leave a comment

O’Reilly Programming ASP.NET MVC 4 (6)

Chapter 16 – Logging

Enabling custom error in MVC – in Web.Config, change the [customError] to:
[on] – enable custom error – display custom error pages (page that does not tell you much about  the error)
[off] – display the default error diagnostic error page
[RemoteOnly] – for remote clients, display custom error. Else, display diagnostic error page.
image

MVC provide HandleErrorAttribute ([HandleError…..]) that can use to catch error at the action or class level.
e.g., at the action level:
image

at the class level
image

** Global Error Handler

You can apply the [HandleError] at the site level by registering it as a global error handler.

// go to /app_start/FilterConfig.cs and find RegisterGlobalFilters() method.
image

Update the method to add your own custom error handling
image
This will catch all DataExceptions in the web site, and send user to [DatabaseError] View.

There is a specific order how errors are handled (the default: in the order they’re listed); you can use this method to define which one runs first.
image

The [HandleError] only handle 500 error. you need to define your 404 error.

If you enable custom error page, and also define [HandleError], then [HandleError] take precedence.

Logging and Tracing

You can create a class: that logs error in Event log.
image
In your action, log the error as follows:
image

Rather than add LogException to each try/catch block, you can override the OnException() method of your controller. But this is still too cumbersome.

image

Best way to do it to just define in one place. 

Define a class that inherit the [HandleErrorAttribute] class, and add logging code in it.
image

In FilterConfig.cs
image

Change to CustomHandleError()
image

Over 08:57pm, 01/14/2013

Posted in Uncategorized | Leave a comment

O’Reilly Programming ASP.NET MVC 4 (5)

Chapter 12 – Caching

Types of Caching – server-side caching, client-side caching

** Request-Scope caching – use HttpContext.Items to set or get data for the current Request
HttpContext.Items[“IsFirstTimeUser”]=true;
bool IsFirstTimeUser = (bool)HttpContext.Items[“IsFirstTimeUser”];

** User-Scoped caching (Session-scoped)
HttpContext.Session[“username”]=”Abudi”;
string name=HttpContext.Session[“username”];

Session timeout limit: (default is only 20 minutes)
image

Application-Scoped Caching
Application[“Message”]=”welcome!!”;
string message=(welcome) Application[“Message”];

Can consider to save drop down lists that rarely changes in Application cache.

A better approach is to use HttpContext.Cache to cache.

ASP.NET removes cached items when:
(1) the cache expires.
(2) the cache’s dependency changes (such as data updated)
(3) the server runs on low resources and must reclaim memory.

Cache expiration:
(1) Sliding expiration –
(2) Absolute expiration –

Cache dependency – based on XML, file, database etc.

Output Caching – HTML pages etc. MVC provides [OutputCache] attribute.
Example:
image

Cache Location: Any (default), Client, DownStream, server, None or ServerAndClient.

There are some cache data that you can save at the client side (browser), and some cannot. For example, you cannot cache user’s name on the server side cache.
image

VaryByParam
image

VaryByParam=”*” means ay combination of Param.

Cache Profile – Define the Cache properties in web.config, and then use it in the code. E.g., define a NAMED cache profile:
image

01/12/2013, 09:13pm, Page 255

Donut Caching
Cache an entire page but continue to generate specific portions of the page. (Partial caching)

WEB Form use <asp:Substitution> such as :
image

In MVC, you can define an extension method: @Html.Substitution (which uses Response.WriteSubstitution() to write the HTML) and use it like this:
image

All contents will be cached except for the @Html.Substitution(…) part.

Advanced: Windows Caching Solution: Velocity / Windows AppFabric (aka MS Application server)

Client-Side Caching Technique
HttpCacheability.NoCache – requires a server re-validation.
HttpCacheability.Private – cache on client side, not by shared (proxy server) cache.
HttpCacheability.Server – ache on server
HttpCacheability.ServerAndNoCache – cache on server
HttpCacheability.Public – cache at client and shared server
HttpCacheability.ServerAndPrivate – cache at client and server only.

HTML 5 defines “ApplicationCache” (or AppCache) for developers to access browser content cache. Good thing to use!!!

3 steps to implement AppCache :

Step 1: Define a CACHE MANIFEST file

(a list of file names and their cachebility etc.)
Sample:

CACHE MANIFEST <—must start with this line
# Generated on 04-23-2012:v2 <—# is comment line
# Cached entries.

CACHE: <—browser can cache these files
/favicon.ico
home.html
site.css
images/logo.jpg
scripts/application.js
# Resources that are “always” fetched from the server

NETWORK: <—browser must fetch these files from server (never cache these files)
login.asmx

# Serve index.html (static version of home page) if /Home/Index is inaccessible
# Serve offline.jpg in place of all images in images/ folder
# Serve appOffline.html in place of all other routes
FALLBACK:
/Home/Index /index.html <—if file not available, server this file instead
images/ images/offline.jpg
* /appOffline.html

Step 2: Reference the manifest

Reference the file in <HTML> tag, so the browser kows that you have a MANIST file defined.
image

Step 3: Server the MANIFEST Correctly

You need to server this MANIST file to the browse using the correct MIME type:
text/cache-manifest

Another HTML 5 feature – Local Storage. Think of it as Super Cookie. Allow you to persist large amount of data to the user’s cache.
Two types:
(1) localStorage – file based; available indefinitely
(2) sessionStorage – stored in memory and will erase once page closed.

Save – Code sample:
localStorage.setItem(“userName”, “john”);
localStorage.setItem(“age”, 32);
or
localStorage[userName”] = “john”;
localStorage[“age”] = 32;

Read – Code Sample:
var userName = localStorage.getItem(“userName”);
var age = parseInt(localStorage.getItem(“age”));
or
var userName = localStorage[“userName”];
var age = parseInt(localStorage[“age”]);

Remove
localStorage.removeItem(“userName”);

Clear all
localStorage.clear();

default max: 5MB

You can try the same syntax with sessionStorage as both are very similar

Chapter 13 – Client-Side Optimization techniques

* having fewer resources to download cut down load times
* re-arranging the resources in your page can make a difference

* Rules:
1. make fewer HTTP request – MVC 4 provides bundling feature
2. use CDN:
3. Put stylesheet on the top
4. Put scripts at the bottom
5. Make scripts and style external
6. Minify javascript and style (popular tools: JsMin and YUI Compressor)

Page 289

To Use MVC Minification and Bundling,

Step 1: Go to /App_Start/BundleConfig.cs, to create/update ScriptBundle or StyleBundle, each with a unique name, and with each bundle you can include as many files/script as you want.

image

Step 2: In your View (such as /Shared/_Layout.cshtml), render the script/style by name.

image

(Note: Follow the “style top” and “script bottom” rile!!!”)

Bundling will resolve the issue of browser caching javascript or style files.

Chapter 14 – Advanced Routing

Glimpse –> help debug routing failures.

When a routing engine parses a URL, it extract the values at each placeholder and use them to populate an instance of the RouteData class.
image

image

Does it ({site}) mean the web site host name? (e.g., www.yahoo.com)
image
image

By default, MVC gives preference to physical files on the server over the “virtual” routes defined in the route table.
You can set RouteCollections.RouteExisingFiles = true to disable this.

Ignore routes:
routes.IgnoreRoute(“{resource}.axd/{*pathInfo}”);
routes.IgnoreRoute(“php-app/{*pathInfo}”);

(place this before you add MapRoute() method)

Route Constraints
Limit the options for id to Ford, Toyota or Honda
image
id must be numbers:
image
id must be only 3 digit numbers:
image

Attribute-based routing – place route attribute on actions – not very exciting
image

Chapter 15 – Reusable UI Component
Page 317

Partial Views are files that have the same *.cshtml or vb.cshtml extension but are created under the /Views/Shared/ folder. To render, call @Html.Partial(“_partialviewname”)

Install [Razor Generator] to enable reuse of view – it convers a *.cshtml view into a C# class, and then compile the C# class so you can re-use the view in different web site project.

1. Install [Razor Generator] from Tools –> Extension and Update
1. Next to your main MVC project, create a new MVC Project (can be a library project too). This new MVC project will not really be used as a MVC project. Under the new MVC project’s /View folder, create a new view called GenericError.cshtml. Update the property of this new view, so the [Custom Tool] field says: RazorGenerator.

After that, a *.cs file will be generated under the *.cshtml file.

image
 
There are other thing that you have to do to le the main MVC project to see this view. Not sure if it’s worth the time to go deeper.

Page 331, 01/14/2013, 07:31 pm

Posted in Uncategorized | Leave a comment

O’Reilly Programming ASP.NET MVC 4 (4)

Chapter 7 – ASP.NET WEB API

ASP.NET WEB API leverages web standards (HTTP, JSON and XML) and conventions to provide a simple way to build web services.

Web API Controller can live anywhere. E.g., you can create a folder [Api] at the web root. You can also save them in [Controllers] folder. Just right click the folder and add a API Controller.
image

Registering Api Routes. Even with a MVC project, the Web Api is already defined in WebApiConfig.cs
image

ApiController rely on names that corresponds to the standard HTTP actions.
GET/PUT/POST/DELETE

$.getJSON() uses GET
$.ajax() uses POST
image

If you do not want to name your Api actions “GET…” or “POST….”, you can use Data Annotation, such as:
image

Chapter 8 – Advanced Data

00:01am, 01/12/2013, Page 153

MVC can use ADO.NET, Linq 2 SQL, EF or NHibernate.

POCO (Plain Old CLR Object) 
A .NET class that is used to represent a business entity (model) class. The class focuses on key business attributes (properties) and behaviors (methods) of a business entity and its associated entities, without requiring any specific database code.

Main goal of POCO – design the application’s business model to have persistence ignorance (PI). This design approach allows the application;s business model to evolve independently of its data access model – business the business model does not contain any database code.
image

You will create dozens or hundreds of classes like this in an application. It makes sense to create a base entity class that contains common properties and methods. Example of a base entity class:

image

Repository Pattern – a data access pattern that promotes a more loosely coupled approach to data access. Instead of having a controller or the business model containing the data access logic, a separate class or set of classes call a repository takes on the responsibility of persisting the application;s business model.

A sample repository class: (Similar to OpenWindow’s data access approach)
image

Use DI to pass the repository to the controller, an the controller use it to perform database access. Every repository will have its own Insert/Update/Delete/GetAll methods.  access:
image

OR Mapper – a data access pattern that supports mapping entities between classes and DB model.

EF Overview

EF support stored procedure so you still can manipulate data by directly using SP.
Example of EF: Declare a DbContext instance, use it to add products, and then SaveChanges().
image

EF Data access approach: Database First, Code First and Model First. Currently, Code First does not support mapping to stored proc. You can use ExecuteSqlCommand() or SqlQuery() to execute the SQL.

Handling Database Concurrency

Pessimistic Concurrency – place a read-only lock when the record is retrieved, and unlock only update is completed.

Optimistic concurrency – add a timestamp field to the table, and tracks the last time it is modified. Better!!! Always do that in important entity classes!!

EF supports Optimistic Concurrency, you need to:
(1) add a timestamp field property (and mark it [TimeStamp] attribute) to an entity.
(2) handling OptimisticConcurrencyException return from DbContext. (Try/Catch)

Example: Add a Timestamp property. Mark it [Timestamp]
image
image

Building A Data access Layer using EF
rules:
1. Table name are the plural forms of the entity class/POCO name
2. Column names are derived from the property names
3. Primary keys are based on property names named ID or {ClassName}ID
4. The default connection string matches name of the DbContext class.

EF Data Annotations, interesting ones are:
[Column] – column name, ordinal position, and data type to map to
[ComplexType] – No keys and cannot be maintained by EF
[DatabaseGenerated] – mark a property to be generated by DB
[Foreign Key] – foreign key
[Key] – uniquely identifying a key
[MaxLength]
[MinLength]
[NotMapped]
[Required]
[StringLength]
[Table] table name
[TimeStamp] a property that is checked before updating/deleting

Overriding Conventions – use your own property name and make it a key
image

You can also remove the convention in the DbContext class
image

In EBuy, there is a base entity class that other entity class inherit. The base entity class contains common properties and method.

DbContext class – this class must contain properties for each entities in the domain model.
image

Sorting, Filtering and Paging Data

Define a function that submits form
image
image

BeginForm:
image

This is a hidden value; you can use #CurrentPage to access the value
image

You can use image as links – bind “click” action to “#Previous” or “#Next” – a common practice.
image

If you are accepting multiple parameters, good idea to create a class for easy management.
image

Chapter 9  — Security

MVC with Windows Authentication. Create a new MVC app with “Intranet Application” template. In the web.config, you will see :
<authentication mode=”Windows”/>

AuthorizeAttribute

Order – the order in which action filter is executed
Roles – get or sets the roles required to access the action
Users – gets or sets the users allowed to access the action.
image
image

Allow anonymous users to access this action
image

What happens when you log in:
image

To self-register a user
image

Change password
image

Json login method – if the login post is from Ajax
image

Ajax register
image

01/12/2013, 07:09pm, page 247

Posted in Uncategorized | Leave a comment

O’Reilly Programming ASP.NET MVC 4 (3)

Chapter 6 – Enhancing Your Site With AJAX

Partial rendering – making a request from your page to server, to replace a portion of your web page. For example, you have a HTML file (myfile.html)that contains this line:
image

And you want to load this file (line) into the place (another HTML file) where the id “container” is.
image

You can use this to insert it:
$(‘#container’).load(‘myfile.html’);

In the end you get this:
image

In asp.net MVC, to let the server return a partial view, you use Partial() to return a PartialViewResult. (in most other situations you use View() to return a ViewResult)

In this example, in the controller first query the auction instance based on the id parameter, and then pass the instance to the View for display.
image

The “Auction.cshtml” view:
image

Migrations: To enable migrations of your model, in the package manager consoles, type in
enable-migrations or
enable0migrations –ContextTypeName EbuyDataContext  <—If your project has more than one context type defined.

image

To enable automatic migrations,
(1) delete the “Migration Folder”, and
(2) re-run enable-migrations specifying the –EnableAutomaticMigrations parameter.
image

So hopefully after that you can modify your model and the VS will automatically migrate your change to Database.

Two command that you can use:

Add-migration – add the existing changes to the next migration.
update-database – apply pending migration.
—————————————————————————————-
Return complete view: image
Return partial view: image

You can now use the following jQuery to load the content from a MVC action:
function showAuctionByID(id) {
    $(‘#auction’).load(‘/Auctions/PartialAuction/’ + id);
}

And if you use razor to generate the route, it would be:

function showAuctionByID(id) {
   $(‘#auction’).load(‘@Url(“PartialAuction”, “Auctions”)/’ + id);
}

Pass a list of auctions, and then in a foreach loop, print out the details of each auction (by calling a Partial View of auction details)
image

Javascript Rendering

JSON Data

ASP.NET MVC offers native JSON support in the form of the JsonResult action result. Simply use Json() method to return a JSON result!!!

For example, this simply returns the data (auction instance) as a JSON format.
image

You will get this JSON file after accessing /Auctions/Details/5:
image

By default, MVC disallows returning of JSON data from a GET request. (to prevent JSON hijacking) The “JsonRequestBehavior.AllowGet” is to enable it. (For POST it is always allowed)

Requesting JSON data

Use $.ajax() to call action URL, and use success function to handle the response.

For example,
function updateAuctionInfo(auctionid) {
$.ajax({
   url: “/Auctions/JsonAuction/” + auctionId,
  success: function (result) {
    $(‘#Title’).val(result.Title);
    $(‘#Description’).val(result.Description);
    $(‘#CurrentPrice’).html(result.CurrentPrice);
   }
});
}

Client-Side Templates

Now we use mustache.js javascript Library (or javascript client-side library) as a template to generate HTML.

Page 120, 01/10/2013, 00:34am

Step 1 – To use mustache.js template, first update your Auction.cshtml view to this:
image

(Changing @Model.Title to {{Title}}) because we will shift the responsibility of databinding to the client side, so {{Title}} is a placeholder for javascript to bind the data.

Side note: Your DataContext Class (EBuyDataContext) name need to have the same name as the connection string (in web.config) so EF knows which connection string to refer to.
image
in Web Config:
image

Then after you migrate the model (update-database), the tables will be created.
image

Step 2 – compile the client template, or convert the template HTML into an executable Javascript function. (good idea to compile it once and save the compiled function in a variable)

Finally, invoke the compiled template by passing it the data that we wish to convert into HTML (BINDING).
———————————————————————————

So, first download mustache.js from GITHUB web site. it should always be the latest version. The current version is 0.7.2. Do not download from NUGET – for some reason it’s only 0.4.2. Download mustache.js (just this one single file) and save to your MVC project’s /Scripts folder.
image

Then in your _Layout.cshtml (master page), add this script reference so you can use Mustache anywhere.
image

image

You will get this. Click each link and the bottom part will refresh.
image

Good example!!

Reusing Logic Across AJAX and Non-AJAX Requests

To let the Auction() action serve both the View() and PartialView() using Request.IsAjaxRequest()
image

To decide whether it’s a JSON request, look for in the request parameter of format=json.
image

After that, in your JSON request, make sure to always add a …..?format=json in the URL.

Better yet, define an “extension method” for Request so we can call it from anywhere.
image

So you can do this to check if it’s JSON request: (still need …?format=json on the client side)
image

Very convenient!!! So this is your final action:
image
It is good, but does it mean that for every different action we have to repeat this????? Luckily, we have action filters!!! Action Filter is a DataAnnotation that can apply to a action before and after it’s executed (but before returning data).

So we need to move this View/PartialView/JSON decision into a new action filter, and overriding the OnActionExecuted() method. This filter class needs to implements System.Web.Mvc.ActionFilterAttribute type.

This is the Action Filter:

image

In your action code, it’s much cleaner!!! Plus you can reuse the same data annotation in different actions!!! Very good for cross-cutting concern.
image

Page 128, 01/10/2013, 09:04pm

Sending Data to the Server

$.ajax() is to use Ajax to retrieve data from server.

Now, on how to sending data to the server via Ajax. Two ways:
(1) through URL query string parameters (HTTP GET) and
(2) form post data (HTTP POST)

using $.post(), jQuery will serialize the object to JSON, and attach it as the request form post data.

In your View (or HTML): a.html
image

Post the JSON object to this action and save in DB:
image

After that, a records is saved by accepting the posted JSON data!
image

Sending and Receiving JSON Data Effectively
Good practice – to create a DTO (data transfer object) that is easy to convert to JSON. DTO should be simple data structures and avoid multi level relationships. You can have multiple DTO’s for various responses. You can even have multiple DTO’s for the same entity.

Sample:
image

01/11/2013, 11:17pm, Page 139

Posted in Uncategorized | Leave a comment

O’Reilly Programming ASP.NET MVC 4 (2)

Chapter 3 – Working with Data

Use // to comment out lines in view
image

Two ways to use HTML helper to create labels and controls based on model properties:
image

HttpGet creates a web form for [Create]
HttpGet processed the posted [Create] form.

image

In the parameters list of the post method, use the Auction as the parameter type – so we can capture the inputs as a complete [Auction] instance.
image

Code First – Entity Framework 5

Database interaction is performed via the simple model classes: POCO (Plain old CLR Objects).

Creating a DAL with EF Code First

At the center of the EF Code First, is the System.Data.Entity.DbContext class tht acts your gateway to the DB. Need to create a class that derives from it. Such as:
image

Check if the model is valid.
image

Add a Model Error manually. And then check ModelState.
image

This approach tends to break the app’s separation of concerns. Namely, controllers should not contain business logic. So, we use [Data Annotation] to specify business rules.
Required, StringLength
image

Range
image

Range – if a specific type
image

Error Messages:
image

Field-specific errors:
image

To make it easier, you can just do this:
image

Or, easiest of all, just add this as the first line of the BeginForm() method:
image

All validation messages will be displayed on top of the form; the input box is highlighted in red too.
image

image

Or, you can define a shorter error message next to the fields.
image

Page 69, 01/07/2013, 09:30pm

Chapter 4 – Client Side Development

jQuery
Get windows width:
$(window).width() and $(window).height()
Set window width:
$(window).width(“480px”) and $(window).height(“500px”)

To get a reference to the desired element, do this through (1) its ID, (2) its class name or (3) one of its attributes.

Selecting a DOM object with the id “myDiv” and set its content to “Hello JQuery!”
$(“#myDiv”).text(“Hello jQuery!”); // selecting tag by id
$(“.normal”).text(“Hello jQuery”); // selecting tag by class name

”>” indicate a parent child relationship
image
image

Hook up function call with object event.
image

$(function () {
//………
} );

Is the same as the window.onload event
image

Change css style of a DOM object:
image

Append to an element
image

Remove <p></p> and anything in between.
image

.prepend() – insert aft the beginning of the matched element
.before() – insert before the matched element
.after() – insert after matched element
.html() – replaces all the HTML inside the matched element

AJAX

Enable a page to request or submit data without doing a refresh or postback. (synchronous). jQuery us $.ajax(“www.myaddress.com”)

image

jQuery uses GET by default, and $.ajax() is async by default. You can also do this:
image

Enable client side and unobstrusive validation by configuring these:
image
(enabled by default)

You can include all jQuery references in _layout.cshtml
image

You then use DataAnnotation to specify the validation rules for your model properties.
image

And then in your view, you print a validation summary near top of your form, and an “*” next to each of your form controls.
image

Custom message for required field.
image

image

With the unobstrusive validation, you don’t see messy javascript anymore, but instead you see CSS classes defined for the object.
image

Page 87, 01/08/2013, 09:44pm

Chapter 5 – Web App Architecture

Controller: intercepts user input, coordinate view and model, handle communication between model and data layer.
model: data attributes (properties), business logic, behavior and validation
view: render the UI (HTML, CSS), binds to the model

Use {CompanyName}.{ApplicationNanme}…. as root namespace.

IOC – Inversion of Control – promote loosely coupled layers, components and classes by inverting the control flow of the application

two approach: (1) dependency injection and (2) service location
Dependency Injection: Using the constructor to accept the object passing from the caller.
image

Use Ninject because of its popularity.

An Article on Action Filter

http://msdn.microsoft.com/en-us/magazine/gg232768.aspx

Action Filter – good for cross cutting concerns
An attribute that, when attach to a controller class or controller method/action, provides a declarative means to attach some behavior to a requested action. By writing a action filter, you can hook up the execution pipeline of an action method to a requested action. You can take out logic from a controller that does not belong to the controller. Ideal for cross-cutting concerns.

ASP.NET MVC come with a few pre-defined action filters such as HandleError, Authorize and OutputCache. You use HandleError to trap exceptions thrown during the execution of methods on the target controller class.

You will mostly concern about IActionFilter and IResultFilter.
image

You can write your own custom action filter to perform pre-action and post-action processing.

For example, you create this custom Action Filter:
image

To use it:
image

END

Page 111, 01/08/2013, 11:41pm

Posted in Uncategorized | Leave a comment

O’Reilly Programming ASP.NET MVC 4 (1)

Chapter 1 – Fundamentals

Model – core business logic and data.
View – transforming a model(s) into a visual representation.
Controller – controls the application logic and acts as the coordinator between the view and the model.

New to MVC 4

  1. Async controllers – you can tell the framework to free up the thread that is processing your request, letting it perform other processing tasks while waiting; once finishes, the process picks up what’s left off and returns the same response as if nothing happens .
  2. Display modes – apply display mode to add mobile support.
  3. Bundling and minification – bundle the js scripts and CSS and minify them for faster download.
  4. Web API – web service on top of MVC

Create a EBuy MVC application

Create a new web application in VS 2012.
image

MVC 4 project template –
Intranet-based: Windows authentication
Internet-based:  With AccountController (login etc.)

In this test app, we choose Internet Application.

Note: A Nuget package may contain a mixture of assemblies, contents, tools to aid in development. Nuget will add the dll’s to the target project’s [Reference] list, copy any content into the application’s folder structure.

Convention Over Configuration

Instead of relying on explicit configuration settings, ASP.NET MVC simply assumes that developers will follow certain conventions as they build their applications. E.g., 3 special folder: Controllers, Models and Views.

If MVC cannot find the route, it returns a 404 NOT FOUND.

Defining the route:
image

Good practice to add the property name before the value, such as “name” and “url”.

Despite the fact that every controller action needs to return an ActionResult, you will rarely be creating them manually. Instead, you use helper methods (such as the followings).

Content() – Returns a ContenResult that renders an arbitrary text.
File() – Returns FileResult that renders a file, such as PDF
HttpNotFound() – Returns an HttpNotFoundResult that renders a 404 HTTP status code response.
JavaScript(): Returns a JavaScriptResult() that renders javascript, such as :function hello() {alert(‘’Hello World’}”.
Json(): Returns a JsonResult() such as {“Message”: hello World!}
PartialView(): Returns a PartialViewResult() that renders only content part of a view.
Redirect(): Returns a RedirectResult that renders a 302 status code. e.g., “302 http://www.ebay.com”.
RedirectToAction()
View(): Returns a ViewResult()

Old way of processing parameters in Action (Method): Get the value from [Request], and parse them.
image

The better way (model binding): Assume the parameters are passed as parameters to the Action, and use them. (the parameter names have match the ones used in the Request).
image

MVC looks the parameters/values in Route Data, query strings, form post values and even JSON.

For example, if you have a URL:
/Home/Auction/5, then you can get the id by using a parameter.
image

Model Binding – Complex Object

Even better, you can simply use the Model instance as a parameter
image

Action filter – such as the [Authorize] that is placed on top of an Action. It can be used to take care of cross-cutting concern such as security or logging.
image

Page 26, 01/05/2013, 10:46pm

Razor

<div>This page renders at @DateTime.Now</div>
<div>This page renders at 12/7/1941 7:38:00 AM</div>

@if(User.IsAuthenticated) {
  <span>Hello, @User.UserName!</span>
} else {
  <span>Please @Html.ActionLink(“Log in”)</span>
}

<ul>
@foreach(var auction in auctions) {
  <li><a href=”@auction.Href”>@auction.Title</li>
}
</ul>

Code Nuggets

Simple expressions that are evaluated and rendered inline. Can be mixed with text and look like:
Not Logged In: @Html.ActionLink(“Login”,”Login”)

This will produce this HTML:
Not Logged In: <a href=”/Login”>Login</a>

Code Blocks

Section of the view that contains strictly code rather than a combination of markup and code. Define by @{……………….} Cannot mix with HTML markup. Such as
@{
LayoutPage=”~/Views/Shared/_Layout.cshtml”;
View.Title=”Auction “ + Model.Title;
}

Code blocks do not render any HTML to the view. Just run code to process business logic.

Variables defined in the top of the view can be used throughout the view, such as these two:
image

Layout

In a Layout, you have a RenderBody() to render the main contents. and Any number of RenderSection(“Sectionname”) to render other HTML codes.

View is like this:
image

Partial Views

You can create a partial view (Auction.cshtml) and place it under /View/Shared, and call it
@Html.Partial(“Auction”,auction)

The “Auction” is the view name –> Auction.cshtml
the “auction” is the model that’s passing to the partial view.

Displaying Data

ViewData and TempData to pass model between M/V/C.

ViewData[“MyName”] is the same as ViewBag.MyName

ViewData.Model is a special property – it is the model instance that’s passed from the action.

In the action you can create a new model object, and then pass it to the view by just include it as the second parameter: (company, which is an instance of CompanyInfo class)
image

Then in the View, you can do this to receive the “company’ model
image

The second parameter represents the object that will be assigned to the ViewData.Model property.

Strongly Typed Views

Even better, use @model in the beginning of the view to indicate the type of the page’s model explicitly. Such as
image

By doing this you do not need to cast the model type in the view.

HTML ad URL Helpers

Many of them, but in general:
HTMLHelper helps you generate HTML
URLHelper helps you generate URL

Note: In C#< adding namespace to web.config does not save you from adding “using <namespace>” in code behind!!

image

E.g., you still have to include “using Ebuy………” in each of your code behind. So no need to update the web.config.

You define a model called Auction in Model folder.

image

Then in the AuctionsController’s details action, create a new Auction instance, pass it to the view.

image

Now create a Details view based on the [Auction] model.
image

After that, run the site and you will see this after entering the URL:
image

Security

Cannot use the tradition way of security configuration by updating web.config. MVC provide [Authorize] attribute to do this. Add [Authorize] on top of a method that needs authentication.

image

You can make the whole controller [Authorize], and then allow anonymous at the action level.
image

Chapter 2

MVC does not use ViewState anymore – feel free to use cache, session state, or HttpContext.Items API.

Create a HTML list in Web Forms:
image

In MVC:
image

HTML link in Web Form:
image

In MVC:
image

@Html.ActionLink(auction.Title, “Details”, “Auction”);
This will generate this HTML:
<a href=”/Auction/Details/”>My Auction Title</a>

Page 57, 01/07/2013, 07:55pm

Posted in Uncategorized | Leave a comment

Web API notes on Stephen Walther’s post

http://stephenwalther.com/archive/2012/03/05/introduction-to-the-asp-net-web-api.aspx

To expose a list of products from the web server as JSON so you can retrieve it using jQuery, options:
1. ASMX web services
2. WCF web service
3. ASHX generic handler
4. WCF Data Services
5. MVC Controller actions
6. Now, Web API

Create a new [Web API] project, right click [Controller] folder, add a new [API controller].

image

Now you have a MovieController class that inherits ApiController

We’re creating a movie database app and us jQuery to update/insert/add/delete it.

First create a [Movie] class in the [Models] folder.

image

In the controller code, add a new get method to return a movie if the id = 1
image

if you enter the Web API URL. (It’s using the HTTP GET method)
image

You get a JSON results back from the Web API
image

Note:

[RouteConfig.cs] defines the route for a regular MVC request.

image

[WebApiConfig.cs] defines the route rules for Web API call.
image

Write a HTML file with jQuery call to get the movie info:
image

What you get in the browser:
image

Now retrieve a list of movies. In your APi controller classes, add a new action method:

image

Since we’re not using GET, so it will not be invoked by Web API, so let’s add a new route rule for this.

image

The ListMovies does not work. Keep working on it later.

 

01/03/2013, 11:05pm,

Posted in Uncategorized | Leave a comment

Professional ASP.NET MVC 4 (7)

Chapter 11 – ASP.NET Web API

Leverage your existing MVC experience with controllers, actions, filters, model binders, dependency injection and the like.

MVC and web API both use controllers, but web API does not use the Model-View-Controller pattern.

image

Controller returns raw objects, instead of views. Objects returned are transformed into the best matched format that the requestor asks for.

** MVC controllers always dispatch to actions by [Action Name], while Web API controllers by d HTTP Verb (POST/GET/PUT/DELETE).

In Web API, you can use [HttpGet] or [HttpPost] to indicate the action type, although you’re likely to use the Verb name as part of the method name, such as GetTotalAmount().

e.g., GET() and GetValues() are both reachable by GET verb.

ApiController is defined in the name space of System.Web.Http.

Web API assumes that basic types (string, int etc.) are from non-body values, and complex types are from the body. Incoming values not in the body are handled by model binding system similar to MVC. Incoming and outgoing bodies, are handled by a new concept called formatters.

Web API’s HttpResponseMessage = MVC’s ActionResult

Web API automatically convert the result to a structured response in the desired format USING a feature called  [Content Negotiation].

image

In WebApiConfig.cs, you can configure access to routes, filters for all requests, parameter binding rules, default services used by Web API, http message handlers and a property bag which can holder user defined values.

Web API use parameter binder to provide individual values for parameters.

Filtering requests

APIs’
image

Example: Products Controller

Chapter 12 – Dependency Injection

What id dependency? A class depend on knowledge of another class.

image

Use [interface] to de-couple the dependency.

image

Solution:
Service Locator – omitted.
Dependency Injection – below.

Most common is [Constructor Injection].

image

How do you implement it? Use a [Dependency Injection Container]. it’s a software library that acts as a factory for components.

More or less, all containers have configuration APIs that allow you to map types – when someone asks for type T1, build an object of type T2 for them.

Posted in Uncategorized | Leave a comment