Definition: In
Factory pattern, we create object without exposing the creation logic. In this
pattern, an interface is used for creating an object, but let subclass decide
which class to instantiate. The creation of object is done when it is required.
The Factory method allows a class later instantiation to subclasses.
Uses of Factory Method
Patterns
1.creation of object is done when it is required.
2.The process of objects creation is required to
centralize within the application.
3.A class (creator) will not know what classes it will be
required to create.
interface Product
{
}
class ConcreteProductA : Product
{
}
class ConcreteProductB : Product
{
}
abstract class Creator
{
public abstract Product
FactoryMethod(string type);
}
class ConcreteCreator : Creator
{
public override Product
FactoryMethod(string type)
{
switch (type)
{
case "A":
return new ConcreteProductA();
case "B":
return new ConcreteProductB();
default: throw new
ArgumentException("Invalid type", "type");
$("p").click(function(){ // When a click event fires on a
element
$(this).hide();
//
hide the current element
});
dblclick()
$("p").dblclick(function(){
$(this).hide();
});
mouseenter()
$("#p1").mouseenter(function(){
alert("You
entered p1!");
});
hover()
$("#p1").hover(function(){
alert("You
entered p1!");
},
focus()
$("input").focus(function(){
$(this).css("background-color",
"#cccccc");
});
blur()
$("input").blur(function(){
$(this).css("background-color",
"#ffffff");
});
jQuery toggle()
Shown elements are hidden and hidden elements are shown:
$("button").click(function(){
$("p").toggle();
});
5. jQuery Callback
Functions
JavaScript statements are executed line by line. However, with
effects, the next line of code can be run even though the effect is not
finished. This can create errors.
A callback function is executed after the current effect is
finished.
jQuery has several
important methods for working with dimensions:
width()
height()
innerWidth()
innerHeight()
outerWidth()
outerHeight()
jQuery Traversing -
Ancestors
An ancestor is a parent, grandparent, great-grandparent, and so
on.
With jQuery you can traverse up the DOM tree to find ancestors
of an element.
jQuery parent() Method
The parent() method returns the direct parent element of the
selected element.
This method only traverse a single level up the DOM tree.
jQuery parents() Method
The parents() method returns all ancestor elements of the
selected element, all the way up to the document's root element ().
$(document).ready(function(){
$("span").parents();
});
The following example returns all ancestors of all
elements that are
elements:
$(document).ready(function(){
$("span").parents("ul");
});
jQuery parentsUntil()
Method
The parentsUntil() method returns all ancestor elements between
two given arguments.
$(document).ready(function(){
$("span").parentsUntil("div");
});
jQuery Traversing -
Descendants
A descendant is a child, grandchild, great-grandchild, and so
on.
With jQuery you can traverse down the DOM tree to find
descendants of an element.
jQuery children() Method
The children() method returns all direct children of the
selected element.
$(document).ready(function(){
$("div").children();
});
jQuery find() Method
The find() method returns descendant elements of the selected
element, all the way down to the last descendant.
$(document).ready(function(){
$("div").find("span");
});
The following example
returns all descendants of
:
$(document).ready(function(){
$("div").find("*");
});
jQuery siblings() Method
The following example returns all sibling elements of
:
$(document).ready(function(){
$("h2").siblings();
});
jQuery next() Method
The next() method returns the next sibling element of the
selected element
$(document).ready(function(){
$("h2").next();
});
jQuery nextAll() Method
The nextAll() method returns all next sibling elements of the
selected element.
$(document).ready(function(){
$("h2").nextAll();
});
jQuery nextUntil()
Method
The nextUntil() method returns all next sibling elements
between two given arguments.
$(document).ready(function(){
$("h2").nextUntil("h6");
});
jQuery first() Method
The first() method returns the first element of the selected
elements.
$(document).ready(function(){
$("div
p").first();
});
jQuery last() Method
The last() method returns the last element of the selected
elements.
$(document).ready(function(){
$("div
p").last();
});
jQuery eq() method
The eq() method returns an element with a specific index number
of the selected elements.
$(document).ready(function(){
$("p").eq(1);
});
jQuery filter() Method
The following example returns all elements with class
name "intro":
$(document).ready(function(){
$("p").filter(".intro");
});
jQuery not() Method
The following example returns all elements that do
not have class name "intro":
$(document).ready(function(){
$("p").not(".intro");
});
jQuery - The
noConflict() Method
If two different frameworks are using the same shortcut, one of
them might stop working.
The jQuery team have already thought about this, and
implemented the noConflict() method.
The noConflict() method releases the hold on the $ shortcut
identifier, so that other scripts can use it.
$.noConflict();
jQuery(document).ready(function(){
jQuery("button").click(function(){
jQuery("p").text("jQuery
is still working!");
});
});
JQuery
//MVC JQuery Ajax
$('#learnitem-form').ajaxSubmit({
data : {
data1: data1,
data2: data2,
},
success :
function(result){
//success
},
error : function(){
//error
}
});
Posting Javascript
Object
type This
is type of HTTP Request and accepts a valid HTTP verb. POST is the option
illustrated in this article.
url This is the location of the resource that
the request will be made to.
data This is the actual data to be sent as part
of the request.
contentType This is the content type of the request
you are making. The default is 'application/x-www-form-urlencoded'.
dataType This is the type of data you expect to
receive back. Accepted values are text, xml, json, script, html jsonp. If you do
not provide a value, jQuery will examine the MIME type of the response and base
its decision on that.
MVC is an architectural pattern
which separates the representation and user interaction.
M - Model - Application business logic is in the Model
V - View - Views represent the user
interface, with which the end users interact.
C - Controller - Controller is the
component that responds to user actions. Based on the user actions, the
respective controller, work with the model, and selects a view to render that
displays the user interface.
2.
Advantages of MVC
1.ASP.NET MVC views are light weight, as they do not use
viewstate.
2.Extensive support for TDD. With asp.net MVC, views can
also be very easily unit tested.
3.Complex application can be easily managed by the
developer.
4.In Razor view engine using a @ block is automatically
HTML encoded to protect from cross site scripting (XSS) attacks.
5.Bundling and minification improves load time by
reducing the number of requests to the server and reducing the size of
requested assets (such as CSS and JavaScript.). Bundling that makes it easy to
combine or bundle multiple files into a single file.
6.Minification performs a variety of different code
optimizations to scripts or css, such as removing unnecessary whitespace and
comments and shortening variable names to one character.
3. MVC
Application Life cycle
MVC application life cycle has two
main phases
Creating the request object and
sending our response to the browser.
Creating the
request Object
Step 1: Fill
route : - MVC requests are mapped to route tables which in turn specify
which controller and action to be invoked. So if the request is the first
request the first thing is to fill the route table with routes collection. This
filling of route table happens in the global.asax file.
Step 2: Depending on
the URL sent “UrlRoutingModule” searches the route table to create “RouteData” object which has the
details of which controller and action to invoke.
Step 3 Request
context created: - The “RouteData” object is used to create the
“RequestContext” object.
Step 4 Controller
instance created: - This request object is sent to “MvcHandler” instance to
create the controller class instance. Once the controller class object is
created it calls the “Execute” method of the controller class.
Creating
Response object: - This phase has two steps executing the action and finally
sending the response as a result to the view.
4.Routing in
MVC
Routing is a pattern matching system that monitor the
incoming request and figure out what to do with that request. At runtime,
Routing engine use the Route table for matching the incoming request's URL
pattern against the URL patterns defined in the Route table. You can register
one or more URL patterns to the Route table at Application_Start event.
routes.MapRoute(
"View", // Route
name
"View/ViewCustomer/{id}",
// URL with parameters
new { controller =
"Customer", action = "DisplayCustomer",
id = UrlParameter.Optional }); // Parameter defaults
The route mapping code is written in
"RouteConfig.cs" file and registered using "global.asax" application
start event.
5.HTML helpers in MVC
HTML helpers help you to render HTML controls in the view.
For instance if you want to display a HTML textbox on the view , below is the
HTML helper code.
Copy Code
<%= Html.TextBox("LastName") %>
6. Difference between
HTML.TextBoxFor and HTML.TextBox
Both of them provide the same HTML output, “HTML.TextBoxFor”
is strongly typed while “HTML.TextBox” isn’t
Html.TextBox("CustomerCode")
Html.TextBoxFor(m => m.CustomerCode)
7.Attribute based routing in
MVC
This is a feature introduced in MVC 5. By using the
"Route" attribute we can define the URL structure.
public class HomeController : Controller
{
[Route("Users/about")]
public ActionResult GotoAbout()
{
return View();
}
}
Most of the time developers code in the action methods.
Developers can see the URL structure right upfront rather than going to the
“routeconfig.cs” and see the lengthy codes.
8. Navigate from one view to
another using a hyperlink?
<%= Html.ActionLink("Home","Gotohome")
%>
Home - Controller
Gotohome - Action
9. Restrict MVC actions to be
invoked only by GET or POST
We can decorate the MVC action with the HttpGet or HttpPost
attribute to restrict the type of HTTP calls. For instance you can see in the
below code snippet the DisplayCustomer action can only be invoked by HttpGet.
If we try to make HTTP POST on DisplayCustomer, it will throw an error.
ASP.NET MVC offers us three options ViewData, ViewBag and
TempData for passing data from controller to view and in next request. ViewData
and ViewBag are almost similar and TempData performs additional responsibility.
Helps to maintain data when you move from controller to view.
ViewData requires typecasting for complex data type and check
for null values to avoid error and ViewBag doesn’t require typecasting for
complex data type.
ViewBag & ViewData
Example:
public ActionResult Index()
{
ViewBag.Name
= "Arun Prakash";
return
View();
}
public ActionResult Index()
{
ViewData["Name"]
= "Arun Prakash";
return
View();
}
In View, we call like below:
@ViewBag.Name
@ViewData["Name"]
TempData:
Helps to maintain data when you move from one controller to
another controller or from one action to other action. In other words when you
redirect, “Tempdata” helps to maintain data between those redirects. It
internally uses session variables. TempData is meant to be a very short-lived
instance, and you should only use it during the current and the subsequent
requests only.
It requires typecasting for complex data type and check for
null values to avoid error.
So if “TempData” is once read it will not be available in the
subsequent request.
11.Partial views in MVC?
Partial view is a reusable view (like a user control) which
can be embedded inside other view.
12.Validations in MVC?
Data annotations are nothing but attributes which can be
applied on model properties.
Types
[Required]
[StringLength(50, MinimumLength = 2)]
[Range(15, 100)]
Data type
The data type annotation can be used to specify the data type
for validation. The information may also be used as UI hint later in rendering
process.
Copy Code
[Url]
public string url { get; set; }
[Phone]
public string phone { get; set; }
[DataType(DataType.Date)]
public DateTime updatedate { get; set; }
[DataType(DataType.PhoneNumber)]
public string phone { get; set; }
public class Customer
{
[Required(ErrorMessage="Customer
code is required")]
public string CustomerCode
{
set;
get;
}
}
Later in the controller we can check if the model is proper
or not by using the ModelState.IsValid property and accordingly we can take
actions.
public ActionResult PostCustomer(Customer obj)
{
if (ModelState.IsValid)
{
obj.Save();
return View("Thanks");
}
else
{
return
View("Customer");
}
}
13.Can we display all errors
in one go?
Yes, we can; use the ValidationSummary method from the Html
helper class.
<%= Html.ValidationSummary() %>
14. Ajax in MVC
Implement Ajax using Ajax
libraries
function GetData()
{
var url
= "/MyAjax/getCustomer";
$.post(url,
function (data)
{
$("#txtCustomerCode").val(data.CustomerCode);
$("#txtCustomerName").val(data.CustomerName);
}
)
}
implement AJAX by using the
“AJAX” helper library
function OnSuccess(data1)
{
// Do something here
}
<%
var AjaxOpt = new
AjaxOptions{OnSuccess="OnSuccess"};
%>
<% using
(Ajax.BeginForm("getCustomer","MyAjax",AjaxOpt)) { %>
<%} %>
15.Difference between
ActionResult and ViewResult?
ActionResult is an abstract class while ViewResult derives
from the ActionResult class.
ActionResult has several derived classes like ViewResult,
JsonResult, FileStreamResult, and so on.
Depending on the flag (IsHtmlView) it will either return a
ViewResult or JsonResult.
public ActionResult DynamicView()
{
if (IsHtmlView)
return View(); // returns simple
ViewResult
else
return Json(); // returns
JsonResult view
}
16.Different types of results
in MVC?
There 12 kinds of results in MVC, at the top is the
ActionResult class which is a base class that can have 11 subtypes as listed
below:
1.ViewResult
- Renders a specified view to the response stream
2.PartialViewResult
- Renders a specified partial view to the response stream
3.EmptyResult
- An empty response is returned
4.RedirectResult
- Performs an HTTP redirection to a specified URL
5.RedirectToRouteResult
- Performs an HTTP redirection to a URL that is determined by the routing
engine, based on given route data
6.JsonResult
- Serializes a given ViewData object to JSON format
7.JavaScriptResult
- Returns a piece of JavaScript code that can be executed on the client
8.ContentResult
- Writes content to the response stream without requiring a view
9.FileContentResult
- Returns a file to the client
10.FileStreamResult
- Returns a file to the client, which is provided by a Stream
11.FilePathResult
- Returns a file to the client
17. Areas in MVC?
Group the controller
classes into logical section
18. MVC Scaffolding
Scaffolding is a technique in which the MVC template helps to
auto-generate CRUD code. CRUD stands for create, read, update and delete.
19.Multiple Submit buttons
pointing to multiple actions in a single MVC view
HTML Way
Ajax Way
20. MVC Ajax Example
//MVC JQuery Ajax
$('#learnitem-form').ajaxSubmit({
data : {
data1: data1,
data2: data2,
},
success :
function(result){
//success
},
error : function(){
//error
}
});
20. MVC Action Filters
ASP.NET MVC provides Action Filters for executing filtering
logic either before or after an action method is called. Action Filters are
custom attributes that provide declarative means to add pre-action and
post-action behavior to the controller's action methods.
Authorization filter, which
makes security decisions about whether to execute an action method, such as
performing authentication or validating properties of the request.
Action filter, which
wraps the action method execution. This filter can perform additional
processing, such as providing extra data to the action method, inspecting the
return value, or canceling execution of the action method
OnActionExecuting - Runs before
execution of Action method.
OnActionExecuted - Runs after
execution of Action method.
OnResultExecuting - Runs before
content is rendered to View.
OnResultExecuted - Runs after
content is rendered to view.
Result filter, which
wraps execution of the ActionResult object. This filter can perform additional
processing of the result, such as modifying the HTTP response.
Exception filter, which
executes if there is an unhandled exception thrown somewhere in action method,
starting with the authorization filters and ending with the execution of the
result. Exception filters can be used for tasks such as logging or displaying
an error page.
21. MVC Custom Filters
When you request any page into MVC Application, it will go
through the Routing Architecture. Your Routing system will decide your URL
pattern. The default routing algorithm is like {controller}/ {action}/ {id}
patterns. But it can be possible to change that pattern using Custom Routes.
When you create a Custom Route, you can also include route
constraints. These constraints are used to restrict the requests to match
routes. There are three basic types of constraints:
1.Regular Expression Constraints - check the
pattern of the Route and prevent invalid requests
2.HttpMethod Constraints - You can
match route with any type of the HTTP operation like POST, GET, etc. you want
to prevent user to access particular URL when GET operation occurs but not POST
operation occurs.
//Custom Route With HttpMethod
Constraint
routes.MapRoute(
"HttpMethodConstraintRoute",
"Blog/Insert",
new { Controller =
"Blog", action = "Insert" },
new { method = new
HttpMethodConstraint("GET") });
3. CatchAllRoutes- Suitable for
the dynamic URL, But if you want to match your URL, regardless of the
number of the segments for that, we
have to create Catch-All Parameter.
22.Action Results - ActionResult
method works as a return type of any controller method in the MVC. It acts like
the base class of Result classes. It is used to return the models to the Views,
file streams and also redirect to the controllers.
23.Razor View Engine VS Web
Form(ASPX) View Engine
1.Razor Engine is an advanced view engine that was
introduced with MVC3.
Web Form Engine is the default view
engine for the Asp.net MVC that is included with Asp.net MVC from the
beginning.
2. The
file extensions used with Razor Engine are different from Web Form Engine. It
has .cshtml (Razor
with
C#) or .vbhtml (Razor with VB) extension for views, partial views,
editor templates and for layout pages.
3. The file extensions used with
Web Form Engine are also like Asp.net Web Forms. It has .aspx extension for
views, .ascx extension for partial views & editor templates and
.master extension for layout/master pages.
4. Razor
has new and advance syntax that are compact, expressive and reduces typing.
Web Form
Engine has the same syntax like Asp.net Web Forms uses for .aspx pages.
5. Razor syntax are easy to learn
and much clean than Web Form syntax. Razor uses @ symbol to make the code like
as:
@Html.ActionLink("SignUp",
"SignUp")
Web Form syntax are borrowed from
Asp.net Web Forms syntax that are mixed with html and sometimes make a view
messy. Webform uses <% and %> delimiters to make the code like as:
<%:
Html.ActionLink("SignUp", "SignUp") %>
6.By default, Razor Engine prevents
XSS attacks(Cross-Site Scripting Attacks) means it encodes the script or html
tags like <,> before rendering to view.
Web Form Engine does not prevent
XSS attacks means any script saved in the database will be fired while
rendering the page
7. Razor Engine is little bit slow
as compared to Webform Engine.
Web Form Engine is faster than
Razor Engine.
8. Razor Engine, doesn't support
design mode in visual studio means you cannot see your page look and feel.
Web Form engine support design mode
in visual studio means you can see your page look and feel without running the
application.
9. Razor Engine support TDD (Test
Driven Development) since it is not depend on System.Web.UI.Page class.
Web Form Engine doesn't support TDD
(Test Driven Development) since it depend on System.Web.UI.Page class which
makes the testing complex.
There is no input in the form to let a user set the IsAdmin flag, but this won't stop someone from crafting an HTTP request with IsAdmin in the query string or request body. Maybe they saw the "IsAdmin" name somewhere in a request displaying account details, or maybe they just got lucky and guessed the name.
If you use the MVC model binder with the above request and the previous model, then the model binder will happily move the IsAdmin value into the IsAdmin property of the model. Assuming you save the model values into a database, then any user can become an administrator by sending the right request. It's not enough to leave an IsAdmin input out of the edit form.
Fortunately, there are at least 6 different approaches you can use to remove the vulnerability. Some approaches are architectural, others just involve adding some metadata or using the right API.
Weakly Typed Approaches
The [Bind] attribute will let you specify the exact properties a model binder should include in binding (a whitelist).
Alternatively, you could use a blacklist approach by setting the Exclude parameter on the attribute.
[HttpPost]
public ViewResult Edit([Bind(Exclude = "IsAdmin")] User user)
{
// ...
}
If you prefer explicit binding with the UpdateModel and TryUpdateModel API, then these methods also support whitelist and blacklist parameters.
[HttpPost]
public ViewResult Edit()
{
var user = new User();
TryUpdateModel(user, includeProperties: new[] { "FirstName" });
// ...
}
Strongly Typed Approaches
TryUpdateModel will take a generic type parameter. You can use the generic type parameter and an interface definition to restrict the model binder to a subset of properties.
[HttpPost]
public ViewResult Edit()
{
var user = new User();
TryUpdateModel<IUserInputModel>(user);
return View("detail", user);
}
This assumes your interface definition looks like the following.
Of course, the model will also have to implement the interface.
public class User : IUserInputModel
{
public string FirstName { get; set; }
public bool IsAdmin { get; set; }
}
There is also a [ReadOnly] attribute the model binder will respect. ReadOnly metadata might be want you want to use if you never want to bind the IsAdmin property. (Note: I remember ReadOnly not working in MVC 2 or MVC 1, but it is working in 3 & 4 (beta)).
public class User
{
public string FirstName { get; set; }
[ReadOnly(true)]
public bool IsAdmin { get; set; }
}
An Architectural Approach
Put user input into a model designed for user input only.
public class UserInputViewModel
{
public string FirstName { get; set; }
}
In this approach you'll never bind against business objects or entities, and you'll only have properties available for the input you expect. Once the model is validated you can move values from the input model to the object you use in the next layer of software.
Based upon our convenience we can choose the approach.
JavaScript Module pattern provides a way to wrap public, private methods (and variable) into a single entity and exposing only the public members to the world outside of module. This allows faster namespace resolution, avoid collision of the methods/variables with other global APIs since the namespace isn't populated with all many functions, and obviously provides cleaner code.
CalcModule = (function(){
var mem = new Array(); //private variable
var storeInMemory = function(val) { //private function
mem.push(val);
};
var add = function(a, b) {
var result = a + b;
storeInMemory(result); //call to private function
return result;
};
var sub = function(a, b) {
var result = a - b;
storeInMemory(result); //call to private function
return result;
};
var retrieveFromMemory = function() {
return mem.pop();
};
Instead we define all the functions public or not in the same way, and then in the return statement create a new object and add properties to it.
Advantages of Revealing Module pattern in Javascript
1. Consistent coding style inside the module for both private and public members.
2. Better control on the name of the public API, i.e., if it is required to change the name of add() method to addition(), all we need to do is change the name in the return statement without effecting the function name inside the module.
3.Control on what to make public, just adding/removing the properties in return statement is sufficient.
4.As always, cleaner code.
Restrict MVC actions to be invoked only by GET or POST
We can decorate the MVC action with the HttpGet or HttpPost attribute to restrict the type of HTTP calls. For instance you can see in the below code snippet the DisplayCustomer action can only be invoked by HttpGet. If we try to make HTTP POST on DisplayCustomer, it will throw an error.
Routing in MVC
Routing helps you to define a URL structure and map the URL with the controller.
The route mapping code is written in the “global.asax” file.
For Example
routes.MapRoute(
"View", // Route name
"View/ViewCustomer/{id}", // URL with parameters
new { controller = "Customer", action = "DisplayCustomer",
id = UrlParameter.Optional }); // Parameter defaults
When a user types “http://localhost/View/ViewCustomer/”, it goes to the “Customer” Controller and invokes the DisplayCustomer action. This is defined by adding an entry in to the routes collection using the maproute function. Below is the underlined code which shows how the URL structure and mapping with controller and action is defined.
Note:
We can map multiple URL'S to the same action.
Add two entries with different key names and specify the same controller and action.