Simple Application using Knockout.js, jQuery and ASP.NET MVC 4.0 with WEB API

Based on: http://www.dotnetcurry.com/ShowArticle.aspx?ID=847

Create a new database Company and run the script to create a new table [EmployeeInfo]
image

Create a new Internet MVC 4 project, name it [MVC40_Knockout_App], and download knockout,js from NuGet. (or update KO version)

Use EF Power Tool’s Reverse Engineer to import the Company database into the project. After that, under /Models you can see the DbContext file, and the [EmployeeInfo] model class. Also a [CompanyContext] has been added to the web.config. Build the project so the [Employeeinfo] class is visible to the controller wizard.
image
image
Create a new API controller:
image
In the new API controller you get GET/POST/PUT/DELETE method which you can access via jQuery/Ajax.
Next, create a new empty  EmployeeController
Add this method:
image
Add a new view Create.cshtml – empty view, no model. Update the CSS file per instructed.
Next, make sure add the KO and KO Mapping to the Create.cshtml
image
Make sure you include the new “KO” bundle in the _Layout.cshtml.
image
Copy the HTML (Create Employee Form) into Create.cshtml. Compile and browse, and you should the form page:
image
great example On ASP.NET MVC/Knockout!!!
00:37am, 01/29/2013

Advertisements

Github Bootstrap documentation (1)

Button Group
image
You get:
image

Multiple Button Groups (Button Toolbar)
btn-toolbar = btn=group + btn-group + btn-group….
image
You get:
image
If you want the button to stack vertically, add btn-group-vertical
image
You get:
image
Button Dropdown Menus
image
You get
image
Button of all sizes
btn-large, btn-small or btn-mini
Button Dropdown with divider on the top level button
image
You get:
image
Labels and Badges
image
You get:
image
Alert boxes
image
You get:
image
09:27pm. 01/27/2013

Twitter Bootstrap Web Development How-to (2)

BT Tabs (nav-tabs, or nav-pills)
image
Tab —
image
Pills —
image
Home page carousel
There are many TB plug-ins, one of them carousel.
Download 5 images (jpg) that are 1200×480 and save in /Images folder. Copy index.html to hero.html.
In index.html first remove the whole “hero-unit” div.
image
Then add images and tags:
image
image
You get:
image
Mouse over the image will pause the carousel.
Add the “slide” animation:
image
Add arrow to carousel
image
You see this arrow on the left and right:
image
Add a image title (lower left corner)
image
You see:
image
It adds a shade/background
image
12:40pm, 01/27/2013

Twitter Bootstrap Web Development How-to (1)

Downloading and Setup
Create an MVC 4/Internet application, BS1, use Nuget to download Twitter Bootstrap
image
After installation
image
Go to Bootstrap Github and download a sample html page – Basic marketing (hero.html). Rename to index.html. Update the path to CSS and javascript and image. You will see this:
image
Look at the HTML and see the layout:
image
How the bootstrap button is made:
image
image
And the larger button
image
btn-primary: blue
btn-large: make the button large
image
You can use different button classes to achieve different look:
image
image

Layout
Create a copy of index.html and name it layout.html
TB uses a 12-column grid system, so as long as the total is 12, it will fit perfectly on one line. E.g., 6 + 3 + 3, 4 + 4 + 4, 2 + 4 + 6 etc. for each row.
image
Benefits: responsive design – will adapt to different browser screen sizes.
TB: Time-tested principles of progressive enhancement ad graceful degradation.
Creating an About Page
make a copy of index.html and rename to about.html
Change the ‘hero-unit’ class to ‘page-header’, and remove the 2 <p> tag
image
You get the header text:
image
Now place a temp image in the first column (span8)
image
You see this:
image
After some adjustment, you get this:
image

A key part of responsive design is that it provides CSS rules to keep images from overflowing the with of their containers, such as:
img{
   max-width: 100%….

image
Thumbnail
This is a thumbnail
image
With this:
image
You get:
image
06:05pm, 01/26/2013, Page 26
Creating a Products Page
Copy about.html to products.html.
image
You get:
image
Customizing the Nav Bar
TB’s main navigation is organized in the navbar. Composed of divs, links and lists.
image
To make the nav bar stay on top, you need to pad the body in the header section:
image
image
Customizing:
This (Brand) is the site name – click and takes you to the home page.
image
You get:
image
Update these links:
image
You see:
image

Dropdown menu:
image
You get:
image
if you do a pull-right,
image
You get:
image
TABS
Page 36, 01:1am, 01/2/2013
Still trying to find out how tab link can link to static contents on the same page.

Model validation

http://www.asp.net/web-api/overview/formats-and-model-binding/model-validation-in-aspnet-web-api
In WEBAPi, you can use attributes from System.ComponentModel.DataAnnotations namespace to set validation rules for properties on your models.
image
use ModelState.IsValid to validate the model.

Under-Posting
– Client posting data that are incomplete, e.g.,
image (It’s missing Price and Weight)
But since they’re not required, so JSON formatter automatically set their default to 0.
image
If you want to distinguish 0 and NULL, do this:
(1) Make the property [Required]
(2) Make the property nullable

image

Over-Posting – Client posting more data than you expected, such as:
image
JSON simply ignores the value.
If there is a property in your model that you don’t want anyone to change/update, then create a DTO and serve it to the client. such as:
Your model:
image
Your DTO:
image
Handling Validation errors
Use action filter to catch invalidate ModelState
image
If model state invalid, it send a HTTP response (action is not invoked)
image

To apply the filter to all actions (the whole site), add this to the global.asax
image
10:13pm, 01/25/2013

Creating a Web Api that Supports CRUD

Based on :
http://www.asp.net/web-api/overview/creating-web-apis/creating-a-web-api-that-supports-crud-operations

GET – read
PUT – update (replaces the entire product) (U—>U)
POST – Add
DELETE – delete.
Create a new MVC 4 –> WEB API Project
image
Adding a Model
image
Adding A Repository (Repository Pattern)
In /Models, create a new Interface
(1) models –> Add –> New item
(2) Select [Interface] (IProductRepository)
image
In this interface, define the methods needed for Product.
image
Now, again in /Models, add a ProductRepository.cs that implements IProductRepository interface. And define the detail implementation.
A shortcut to implement all methods:
image
Detail implementation:
image
image
This complete the basic CRUD data repository – basically a data access layer. Now we’re creating a WebAPI that uses this repository to access data.
Add a ProductsController/Empty API Controller.
image
ProductsController: GET/POST/PUT/DELETE
image
image
09:13pm, 01/25/2013

WebAPI/KO App (2)

Adding an Admin View
(1) Now that set up CRUD function in WEBAPI, we will turn to client side and add pages that can consume the data.

Go to HomeController, add an [Admin] method. 
image
Create a new View for this new Controller
image
(2) Update Admin.cshtml view per the instructions.
image
Open /Views/Shared/_Layout.cshtml, update the shared “master page” to add a link to the /Home/Admin
image
Clicking on [Admin] you get this:

However, Admin page is only meant for Admin, so add authorization.
To Add the Administrator (role) and Administrator (user name), open this file:
image

And Add these lines to check/create the roles/user. (quick and dirty to add user/role; not good practice)
image
In /Home/Admin (action), allow only Administration Role
image
In the /Admin (controller), allow only Administrator
image

Difference between WebAPI and MVC’s [Authorize]
MVC: System.Web.Mvc.AuthorizeAttribute
Web API: System.Web.Http.AuthorizeAttribute

Creating a Dynamic UI with Knockout.js
KO makes it easy to bind HTML to data.
image
First we define [ViewModel]. Add this to Admin.cshtml to include the KO library.
image
Inside the empty <script> tag, we will define the ViewModel:
image
Outside of ProductViewModel(), do this:
image
So the binding can occur as soon as all HTML/script loaded.


Create a ProductDTO to hide the properties that you want to hide from the public – such as ActualPrice. 
image
Then create a ProductController,
image
ProductController:
image
The MapProducts() returns a IQuerable, so we can use it in other queries.
Create another DTO: OrderDTO. (nested classes?)
image
Add a new OrdersController
image
Creating Main Page
Open /Home/index.cshtml, replace all HTML as indicated.
A typical jquery AJAX POST POST – success and error
image
07:26pm, 01/25/2013

WebAPI/KO App (1)

This exercise is based this page:
http://www.asp.net/web-api/overview/creating-web-apis/using-web-api-with-entity-framework/using-web-api-with-entity-framework,-part-1

Overview and creating the Project
This tutorial shows how to use WEBAPI and ADO.NET Entity framework using code-first model. UI using Knockout.
Goal: simple store application. Normal user can view products and create orders; admin users can create, delete or edit products.
image
How domain objects are represented in various layers
image

(1) create a new MVC4 internet application “ProductStore”.
(2) Update the /Content/site.css per the exercise.
Creating Domain Models
(3) Define 3 models:
image image
imageimage
(4) Build the solution so EF can discover the new models.
(5) Add to WebApiConfig.cs so we can resolve circular reference issue in JSON and also remove XMLFormatter (so JSON is the default formatter).
image
Creating an Admin Controller
(6) We add an API controller that supports CRUD operations on Product
Add a new controller (AdminController) image
(7) A OrdersContext.cs is created under /Models.
image
(8) Update the web.config so the data context points to a SQL server, not SQL CE or SQL Express.
(9) On Orders.Context.cs: this name refers to the connection string name:
image
(10) In OrdersContext.cs, add these three lines after the constructor so EF can query them:
image 
AdminController defines these 5 methods:
image
(11) Add database initializer – to seed the DB.
Right click /Models, add a new class OrdersContextInitializer.cs.
image
Then in global.asax’s Application_Start, add this line to initialize the database every time the application starts.
image
(12) Now when you do Control + F5, and
http://localhost:55784/api/admin you get this JSON result:
image
because in AdminController, the default get method returns all products as an enumerable:
image
00:50am, 01/23/2013

Next:
http://www.asp.net/web-api/overview/creating-web-apis/using-web-api-with-entity-framework/using-web-api-with-entity-framework,-part-4

MVC 4 Project Using Repository Pattern (1)

(based on the CodeCamper project – available at the following address https://github.com/NicholasMurray/CodeCamper)
Create a new MVC 4 Internet application project, and add these other projects:

The first 3 are C# Class Library, and the last one is a MVC 4 web site. image
Adding IRepository.cs
This is the interface file for data repository. You can add more methods as long as they’re shared by all entities. (such as SearchByXXXX)
image

So in the Contracts project, we have IRepository.cs. Build the DST.Data.Contracts project now.
image

Now in the DSP.Data project, you need to have a class that implements the IRepository.cs interface. It’s EFRepository.cs (it’s an Entity Framework implementation, so named) Make sure in DSP.Data you include the following three references:
(1) Entity Framework 5.0
(2) System.Data.Entity
(3) The DSP.Data.Contracts project

So you have:
image

EFRepository.cs inherits IRepository.cs and therefore implements all methods defined in the contract. Any entity (T) can use this EFRepository to perform data access. Build the DSP.Data project and it should build successfully.
image

Useful Tips: Manage references in difference projects: Go to Nuget Package manager, select “Installed Packages”, locate EF 5.0, and clock [Manage] button. Check the project that you would like to have EF 5.0 installed/uninstalled.
image 00:15am, 01/19/2013

Copy the CodeCamper model files to directly under your DSP.Model project. Update the namespace from CodeCamper… to DSP…. and then make sure you can compile the project.
image
Copy the repositories from CodeCamper to DSP.Data and DSP.Data.Contracts. These three models has different method (or method signatures) than the others so need to create the to allow custom DB access for these three models. Compile and make sure all references are there.
image 
Unit of Work Pattern (UOW)
1. It’s a layer between the controller and the data repository. 
2. Series of IRepository<T>
3. Commit (call commit on the UOW to commit changes to database)

Copy the Unit of Work interface file to DSP.Data.Contracts project and update as needed.
image

Copy /SampleData folder under the CodeCamper.Data project to under DSP.Data project> These are the sample data that will be used as seed data.
image
CodeCamper uses a random text generator with “LoremIpsum” generator, so create a new folder (lib) under DSP.Data, and copy the DLL to it. Make a reference to this DLL from inside your DSP.Data project.
image
You also need to copy the /configuration folder – this is similar to the “Mapping” files generated by the EF power Tool. It defines the relationship between models if any. Compile and make sure there is no error.
image

Copy to DSP.Web/Controllers folder the ApiControllerBase.cs. ApiController all inherits from ApiController class. But we need to add UoW to all controllers, so it makes send to create a ApiControllerBase class that inherits from ApiController, and then all your application controllers can inherit from ApiControllerBase.
old:
Your controller <—ApiController
now:
Your controller <—ApiControllerBase (with Uow) <—ApiController
This new ApiControllerBase class only has one line: (UOW)
image
Copy CodeCamperUOW.cs to DSP.Data and update filename or namespace as needed. Also, copy the /Helper folder to DSP.Data project. These are classes that are needed or data repository.
image
Now let’s do Ninject.
(1) Use NuGet to install Ninject to your DSP.Web project.
(2) Copy IocConfig.cs to your DSP.Web/App_Start folder, and update namespace.
image
In global.asax, add this line. Compile and fix issues.
image
Copy these two files to DST.Web/App_Start. needed for Ninject.
image
09:41pm, 01/19/2013, Video 4-5
Move the seeding method from Context class to Global.asax of the DSP.Web project.
image
Then do these in the console to create and seed the new DB:
(1) enable-migrations
(2) add-migration (name: {random})
(3) update-database
Then you will have all tables seeded:
image
Create a new SpeakersController (API Controller)
image
When you query all speakers, you get:
image
10:09pm, 01/19/2013

Now whenever you add a new controller, just make sure you do the following:
(1) Include the DSP.Data.Contracts namespace (because you need to reference the IDSPUow interface)
(2) Inherit from ApiControllerBase
(3) Add the constructor that accepts UOW as a parameter.
image
Create a new Lookups Controller that returns Rooms/Tracks/TimeSlots, or all of them in one Lookups instance.
image
Update the WebApiConfig so it will work for all possible routes
image
Get all Rooms/TimeSlots/Tracks
image
Get Only Rooms
image
Create PersonsController
image

In your /App_Start/WebApiConfig, add three static variables that represent each of the three available API routes.
image
So if you need to dynamically use the route name, you can do this:
image

POST: Insert (returns HttpStatusCode.Created)
PUT: Update (returns HttpStatusCode.NoContent)
A typical insert/update/delete scenario. Powerful!!!!!
image
If you want WebAPI to always return JSON (default is XML), create a GlobalConfig.cs under /App_Start. In it you remove the XML formatter. image

Then you call this static method from your Application_Start method from Global.asax:
image
Now you will get JSON by default!!!
image

Global ModelState Checking (global filter). Instead of doing ModelState checking in every action code, you place it in a custom filter. Under /App_Start, create ValidationActionFilter.cs.
image
Then add this Action Filter.
image
03:07pm, 01/20/2013