Académique Documents
Professionnel Documents
Culture Documents
When to Use: A high level of control over the generated HTML, Easier unit
testing, Separation of concerns
Benefits: High degree of control over the HTML, Test-driven development (TDD),
Full control over the behavior of an application, do not use view state or serverbased forms, easier to manage complexity by clearly separating the functionality
Features:
Web API - building HTTP and Restful services, JQuery Mobile and
mobile features
Task support for asynchronous controllers, Microsoft Windows Azure SDK support,
Bundling and minification for CSS and JavaScript files to help reduce the amount of
HTTP requests
Automatic selection of rendered views with Display Modes
MVC Projects:
Empty: Only the directory structure is added, does not create any controllers,
views, or functionality
Basic: adds some shared views
Internet Application:
CSS files, jQuery
User Profile
webpages_OAuthMembership
webpages Membership
Webpages Roles
webpages_UsersInRoles
The Details action method in the Pet Controller class passes the value 1 as the Id
parameter of the action method.
Custom route can be created like below:
controller = "Showmen" action = "Fido" id = ""
Adding Constraints to Routes -The segments in a URL pattern can be further
restricted by defining constraints. Constraints are defined by using regular
expressions or by using objects that implement the IRouteConstraint interface.
routes.MapRoute( name: "", url: "ShowMe/{id}", defaults: new { controller = "Pet",
action = "GetPhoto", id = "Fido" }, constraints: new { id = ".{4}" });
constraint in which the length of the {id} segment in the custom route added.
ASP.NET Routing vs. URL Rewriting
URL rewriting is used to manipulate URLs before the request is handled by the web
server.
ASP.NET routing is used to map a request to a handler based on the URL.
To read the values in the {id} segment of the default route in an action method, we
would need to do
the following: object id = RouteData.Values["id"];
Controller base :
View Engines
Aspx Engine :
<%--ASPX--%> Ex: <%=DateTime.Now %> Razor Engine:
@*Razor*@
Ex: @DateTime.Now
One of the easiest ways to create a view for an action method is to right-click
anywhere inside the action method and select the option Add View,.
_ViewStart.cshtml view is default shared view.
Referring a layout example: @{
}
Layout = "~/Views/Shared/_Layout.cshtml";
ViewData["ErrorCode"] = 12345;
ViewBag is different from ViewData in the sense that properties can be added to
ViewBag dynamically.
The object is TempData, which, as opposed to ViewData, is stored in the current
session instead of a dictionary Is between controller to controller.
@Html.AntiForgeryToken(),
@Html.ValidationSummary(true)
@Html.TextBoxFor(m =>
@Html.PasswordFor(m =>
Model
refers to a set of objects that implements a piece of functionality
3 types of models Data model - interact with a database. EX: Entity
Framework
Business model - implement functionality that business rules or
processing, dont
Directly respond to user requests. work per requests from action
methods.
Ex: adding a class under the model folder
Model Binding
Process of mapping the information in the HttpRequest object to the model object
is called
Benefits :
No manual code is needed to extract the data from the
HttpRequest object, which avoids coding errors.
Data type conversions happen automatically
Data can be easily validated
Model binding is possible thanks to the built-in binder class DefaultModelBinder
Data Validation
Should not only be on client but also server because of unsure
incoming data while processing complex business logic.
Validation logic will be kept in action method If you are validating manually.
jQuery
jquery-[version].js file , jquery-[version].intellisense.js, jquery-[version].min.js, jquery[version].min.map
Adding a reference :
<script src="~/Scripts/jquery-1.9.1.min.js"></script>
Bundle : collection of Jquery files and Bundling is a feature in ASP.NET that allows
developers to combine multiple files into a single file. Another benefit is automatic
minification. To create a bundle, you use the ScriptBundle and StyleBundle classes.
public class BundleConfig
{ public static void RegisterBundles(BundleCollection bundles) {
bundles.Add(new ScriptBundle("~/bundles/jquery")
.Include("~/Scripts/jquery-{version}.js") ); ); } }
Using Jquery : $(document).ready(handler) Or $().ready(handler) Or $(handler)
jQuery Selectors
To search for the target elements you use what is called a selector
$("#menu") Finds the element with an id of menu
$(".selected") Finds the elements with the class name of selected
$("h1") Finds all the <h1> elements
$("#menu ul") Finds all the <ul> elements that are descendants of the element
with id menu
ASP.NET MVC 4 includes features that facilitate the usage of Ajax through the @Ajax
property in the Razor view
object. The @Ajax property is of type System.Web.Mvc.AjaxHelper. This property
provides the implementation of
HTML helper methods for forms and hyperlinks. The HTML helper methos in the
@Ajax property are similar to those
in the @Html property, the difference is that the ones in the @Ajax property work
asynchronously using Ajax. For example,
a traditional hyperlink would be created using
@Html.ActionLink("This is a regular link","actionName","controllerName")
With the @Ajax property, this hyperlink would be created like this:
@Ajax.ActionLink("This is an Ajax link", "actionName", "controllerName",
ajaxOptions)
AjaxOptions:
Confirm = "Are you sure?", HttpMethod = "Post", UpdateTargetId = "resultDiv",
InsertionMode = InsertionMode.Replace
A simplified $.ajax() definition is as follows:
$.ajax ({ url : "", type: "" data: "", dataType: "", beforeSend: handler, complete:
handler, success: andler,
error: handler});
Web API
Web API is a technology that allows you to easily create services that provide an API
for clients using the HTTP protocol. Implementation is at the framework level
The Web API classes are located inside the System.Web.Http namespace
It can be used to create RESTful APIs. A RESTful API is a web API that is built using
HTTP but also follows the principles of Representational State Transfer (REST).
Methods: GET, POST, PUT, DELETE
The Controllers/ValuesController.cs will include the above methods.
Uses System.Web.Http.ApiController class, we can create API controller from the
add controller API controller
Authentication
includes Forms Authentication as the default mechanism to authenticate users
<authentication mode="Forms">
<forms loginUrl="/Account/Login" protection="All" timeout="2880"
name="AppNameCookie"
path="/FormsAuth" requireSSL="false" slidingExpiration="true" defaultUrl="/"
cookieless="UseCookies" enableCrossAppRedirects="false" /> </authentication>
To allow only authenticated users to access certain sections in the application,
you need to specify those sections with the [Authorize] attribute
do not require authentication by decorating them with the [AllowAnonymous]
attribute
The ASP.NET MVC 4 Internet Application project template also includes support for
authentication using the Open Authentication protocol (OAuth). This functionality is
based on the DotNetOpenAuth open source library.
Membership providers abstract the underlying store used to maintain user
credentials. ASP.NET includes two membership providers,
ActiveDirectoryMembershipProvider and SqlMembershipProvider
we are using SimpleMembership, users are stored in the UserProfile and
webpages_Membership tables, or the webpages_OAuthMembership table for
externally authenticated users. Roles are stored in the webpages_Roles table.
If the users will be stored in Active Directory, then you need
ActiveDirectoryMembershipProvider. If users will be stored in a SQL Server
database, then you need SqlMembershipProvider or SimpleMembership. If users will
be stored in a different system (e.g., a NoSQL database such as MongoDB), you will
need to create a custom membership provider implementing the
MembershipProvider class.
ActiveDirectoryMembershipProvider
<membership defaultProvider="MembershipADProvider">
<providers>
<add name="MembershipADProvider"
type="System.Web.Security.ActiveDirectoryMembershipProvider, System.Web,
Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
connectionStringName="ADConnectionString"
connectionUsername="<domainName>\administrator"
connectionPassword="password"/>
</providers> </membership>
The LDAP connection string to the Active Directory user store is in the following
format:
LDAP://server/userdn
SqlMembershipProvider
aspnet_regsql.exe -E -S localhost -A m
<membership defaultProvider="SqlProvider"
userIsOnlineTimeWindow="15">
<providers> <clear />
<add name="SqlProvider" type="System.Web.Security.SqlMembershipProvider"
connectionStringName="MySqlConnection" www.it-ebooks.infoChapter 9 Security
160 applicationName="MyApplication" enablePasswordRetrieval="false"
enablePasswordReset="true" requiresQuestionAndAnswer="true"
requiresUniqueEmail="true" passwordFormat="Hashed" />
</providers> </membership>
SimpleMembership
To use SimpleMembership, all you need is a connection string pointing to the
database that will store the user accounts
CreateUser(),DeleteUser(),FindUsersByName(),FindUsersByEmail(),GenerateP
assword(),
GetAllUsers(),GetNumberOfUsersOnline(),GetUserNameByEmail(),UpdateUse
r(),ValidateUser()
For example:
MembershipUser u = Membership.CreateUser(model.UserName,
model.Password, model.Email);
Using Roles
Roles define groups of users. the configuration of Role Manager is specified in
the Web.config file. three different role providers:
SqlRoleProvider, WindowsTokenRoleProvider, AuthorizationRoleStoreProvider
A single SQL Server database can be used to store membership and role
information for multiple applications. The connectionStringName and
applicationName parameters define the database where users and roles will
be stored for an application.
MembershipUser u = Membership.GetUser(model.UserName);
if (u.IsInRole("Administrators"))
{ ...}
[Authorize(Roles="Administrators,Managers")]
Action Filters: Filters are custom classes that provide both a declarative and
programmatic means to add pre-action and post-action behavior to controller
action methods.
Types of Action Filters
1. Authorization filters Implements the IAuthorizationFilter attribute. This
filter is always executed first.
2. Action filters Implements the IActionFilter attribute.You can use this filter
to modify the viewdata that an action returns.
3. Result filters Implements the IResultFilter attribute. Eg You might want to
modify the view result before view is redered to the browser.
4. Exception filters Implements the IExceptionFilter attribute. Can be used to
log errors, raised by your controller action or controller action results
2. ActionNameAttribute
Using a proxy mechanism to mock objects is simple and fast, but it has a
serious limitation: while both interfaces and classes can be proxied, only
virtual members can be intercepted and thus mocked. for example, static
classes or members, they cannot be mocked with Moq.
Setting Up Moq: The easiest way to set up Moq in your application is to install
it via NuGet. To open NuGet, choose Tools Library Package Manager
Manage NuGet Packages for Solution
Benefits of Unit Testing
Finds problems early, Facilitates change, Simplifies integration, Provides
documentation
Commonly Used Methods in the Assert Class
AreEqual(),AreEqual<T>(), AreNotEqual(),AreNotEqual<T>(),
AreNotSame(),AreSame(),Equals(),IsFalse(),IsTrue(),IsNull(),IsNotNull(),IsInsta
nceOfType()
Create unit test project and run all the tests.
public void GetByName_ExistingPet_ReturnsPet()
{ // Arrange
string petName = "Fido";
// Act
HaveYouSeenMe.Models.Pet result =
PetManagement.GetByName(petName);
// Assert
Assert.IsNotNull(result); // The pet exists} Which ever you want to test
right click and add unit test. [TestMethod], [TestClass] attributes are added
respectively to the test methods and classes
Preparing the Application for Deployment
Enable compile-time error checking for views - The element
<MvcBuildViews> is a Boolean. The value by default is set to false. To enable
compile-time error checking, change the value to true