SlideShare a Scribd company logo
1 of 97
Part -1
Introduction to ASP.NET MVC4
Presented By : Dilip Patel.
Table of Content
• ASP.NET MVC
• MVC Pattern (Model - View - Controller)
• Controller Action Results, Action Parameters, Action
Selectors, Action Filter, Custom Action Filters
• Razor View
• Routing
• NuGet Package
• Bundling/Minification Support
• Database Migration
• Asynchronous Support
ASP.NET MVC
ASP.NET MVC History
– ASP.NET MVC 1.0
• In February 2007, Scott Guthrie ("ScottGu") of Microsoft sketched out the core
of ASP.NET MVC
• Released on 13 March 2009
– ASP.NET MVC 2.0
• Released just one year later, on 10 March 2010
– ASP.NET MVC 3.0
• Released on 13 January 2011
– ASP.NET MVC 4.0
• Released on 15 August 2012
– ASP.NET MVC 5.0
• Released on 17 October 2014
ASP.NET Core
Presentation
Runtime
Caching .NET
HandlersRoutes
Pages Controls
Globalization
Profile
Master Pages
MembershipRoles
Etc...
ASP.NET
ASP.NET Web Forms
– Rich controls and tools
– Postbacks
– Event driven web development
– Viewstate
– Less control over the HTML
– Hard to test
– Rapid development
ASP.NET MVC
– More control over HTML
– No Codebehind
– Separation of concerns
– Easy to test
– URL routing
– No Postbacks
– No ViewState
MVC Pattern
– Model - View - Controller (MVC) is a software
architecture pattern
– Originally formulated in the late 1970s by Trygve
Reenskaug as part of the Smalltalk
– Code reusability and separation of concerns
– Originally developed for desktop, then adapted
for internet applications.
Model - View - Controller
– Model - represents the logic of the application
– View - the visual representation of the model
– Controller - responsible for handling all user input
Model
– Model is set of classes that describe the application’s
business logic, validation logic, database access logic
– MVC can compatible with any data access technology through
model.
e.g. LINQ to SQL (Language Integrated Query)
– All .edmx files, .dbml files etc. are located in the Models
folder.
– Here one application data-model-property example is given
public class AssignedCourseData
{
public int CourseID { get; set; }
public string Title { get; set; }
public bool Assigned { get; set; }
}
View
– View describe “How the application’s user interface(UI)
will be displayed”
– A view is a standard (X)HTML document that can contain
scripts.
– Most of Controller’s Action Return View
– Script delimits in the view as related to two different
view engine
1. Razor Engine – In razor view engine using “@”
2. WebForm Engine – In aspx view engine using “<% and %>”
– May support master views (layouts) and sub-views
(partial views or controls)
Controller
– The core MVC component. Basically it is a class and derived from
System.Web.Mvc.Controller base class
– Process the requests with the help of views and models
– A set of classes that handles
• Communication from the user
• Overall application flow
• Application Specific Logic
– Every controller has one or more "Actions“
– Example for Home controller.
public class Home Controller: Controller
{
public ActionResult Index()
{
return View();
}
}
Controller Actions
– Public method of the Controller class
– Cannot be overloaded
– Cannot be a static method
– Returns action result
Action Results
– Controller action response to a browser request
– Inherits from the base ActionResult class
– Different results types
Action Results Types
– ViewResult
– EmptyResult
– RedirectResult
– JsonResult
– JavaScriptResult
– ContentResult
– FileContentResult
– FileStreamResult
– FilePathResult
Controller base class methods
– View
– Redirect
– RedirectToAction
– RedirectToRoute
– Json
– JavaScriptResult
– Content
– File
Action Parameters
– ASP.NET MVC maps the data from the HTTP request
to action parameters in few ways:
a. Routing engine can pass parameters to actions
• http://localhost/Users/admin
• Routing pattern: Users/{username}
b. URL query string can contains parameters
• /Users/ByUsername?username=admin
c. HTTP post data can also contain parameters
Action Selectors
– ActionName(string name)
– AcceptVerbs
• HttpPost
• HttpGet
• HttpDelete
• HttpOptions
• …….
– NonAction
– RequireHttps
– ChildActionOnly – Only for Html.Action()
Action Filters
– Apply pre- and post-processing logic
– Can be applied to actions and to controllers
– Global filters can be registered in GlobalFilters. Filters
(or in /App_Start/FilterConfig.cs)
Name Description
OutputCache Cache the output of a controller
ValidateInput(false) Turn off request validation and allow
dangerous input (html tags)
Authorize Restrict an action to authorized users or
roles
ValidateAntiForgeryToken Helps prevent cross site request
forgeries
Custom Action Filter
– Create C# class file in /Filters/
– Inherit ActionFilterAttribute
– We can override:
• OnActionExecuting(ActionExecutingContext)
• OnActionExecuted(ActionExecutedContext)
• OnResultExecuting(ResultExecutingContext)
• OnResultExecuted(ResultExecutedContext)
– We can apply our new attribute to a controller,
method or globally in GlobalFilters.Filters
Continue...
public class LogAttribute : ActionFilterAttribute
{
public override void OnActionExecuting (ActionExecutingContext
filterContext) { /* */ }
public override void OnActionExecuted (ActionExecutedContext
filterContext) { /* */ }
public override void OnResultExecuting (ResultExecutingContext
filterContext) { /* */ }
public override void OnResultExecuted (ResultExecutedContext
filterContext) { /* */ }
}
[Log]
public class DepartmentController : Controller { // ... }
Razor View
• Template markup syntax
• Simple-syntax view engine
• Based on the C# programming language
• Enables the programmer to use an HTML
construction workflow
• Code-focused templating approach, with minimal
transition between HTML and code
– Razor syntax starts code blocks with a @ character and
does not require explicit closing of the code-block
Pass Data to a View
– With ViewBag (dynamic type):
Action: ViewBag.Message = "Hello World!";
View: @ViewBag.Message
– Strongly-typed views:
Action: return View(model);
View: @model ModelDataType;
– With ViewData (dictionary):
ViewData["message"] = "Hello World!";
View: @ViewData["message"]
How it works...
Template Data Generated Output
ByUsername.cshtml
UsersController.cs
UserModel.cs
HTML Output
Razor Syntax
– @ – For values (HTML encoded)
<p>
Current time is: @DateTime.Now!!!
Not HTML encoded value: @Html.Raw(someVar)
</p>
– @{ … } – For code blocks (keep the view simple!)
@{
var productName = "Energy drink";
if (Model != null)
{
productName = Model.ProductName;
}
else if (ViewBag.ProductName != null)
{
productName = ViewBag.ProductName;
}
}
<p>Product "@productName" has been added in your shopping cart</p>
Cont...
– If, else, for, foreach, etc. C# statements
• HTML markup lines can be included at any part
• @: – For plain text line to be rendered
<div class="products-list">
@if (Model.Products.Count() == 0)
{
<p>Sorry, no products found!</p>
}
else
{
@:List of the products found:
foreach(var product in Model.Products)
{
<b>@product.Name, </b>
}
}
</div>
Cont...
– Comments
@*
A Razor Comment
*@
@{
//A C# comment
/* A Multi
line C# comment
*/
}
– What about "@" and emails?
<p>
This is the sign that separates email names from domains: @@<br />
And this is how smart Razor is: spam_me@gmail.com
</p>
Cont...
– @(…) – Explicit code expression
<p>
Current rating(0-10): @Model.Rating / 10.0 @* 6 / 10.0 *@
Current rating(0-1): @(Model.Rating / 10.0) @* 0.6 *@
spam_me@Model.Rating @*spam_me@Model.Rating*@
spam_me@(Model.Rating) @* spam_me6 *@
</p>
– @using – for including namespace into view
– @model – for defining the model for the view
@using MyFirstMvcApplication.Models;
@model UserModel
<p>@Model.Username</p>
Layout
– Define a common site template
– Similar to ASP.NET master pages (but better!)
– Razor view engine renders content inside-out
– First view is redered, then layout
– @RenderBody() –
indicate where we want
the views based on this
layout to “fill in” their
core content at that
location in the HTML
Views and Layout
– Views don't need to specify layout since their default
layout is set in their _ViewStart file:
– ~/Views/_ViewStart.cshtml (code for all views)
– Each view can specify custom layout pages
@{
Layout = "~/Views/Shared/_UncommonLayout.cshtml";
}
– Views without layout:
@{
Layout = null;
}
Sections
– You can have one or more "sections" (optional)
– They are defined in the views:
– And may be rendered anywhere in the layout page
using the method RenderSection()
• @RenderSection(string name, bool required)
• If the section is required and not defined, an exception will
be thrown (IsSectionDefined())
View Helpers
– Each view inherits WebViewPage
• ViewPage has a property named Html
– Html property has methods that return string and
can be used to generate HTML
• Create inputs
• Create links
• Create forms
– Other helper properties are also available
• Ajax, Url, custom helpers
Html Helpers
Method Type Description
BeginForm,
BeginRouteForm
Form Returns an internal object that represents an HTML
form that the system uses to render the <form> tag
EndForm Form A void method, closes the pending </form> tag
CheckBox, CheckBoxFor Input Returns the HTML string for a check box input
element
Hidden, HiddenFor Input Returns the HTML string for a hidden input element
Password, PasswordFor Input Returns the HTML string for a password input element
RadioButton,
RadioButtonFor
Input Returns the HTML string for a radio button input
element
TextBox, TextBoxFor Input Returns the HTML string for a text input element
Label, LabelFor Label Returns the HTML string for an HTML label element
Cont...
Method Type Description
ActionLink, RouteLink Link Returns the HTML string for an HTML link
DropDownList,
DropDownListFor
List Returns the HTML string for a drop-down list
ListBox, ListBoxFor List Returns the HTML string for a list box
TextArea, TextAreaFor TextArea Returns the HTML string for a text area
Partial Partial Returns the HTML string incorporated in the specified
user control
RenderPartial Partial Writes the HTML string incorporated in the specified
user control to the output stream
ValidationMessage,
ValidationMessageFor
Validation Returns the HTML string for a validation message
ValidationSummary Validation Returns the HTML string for a validation summary
message
Custom Helpers
– Write extension methods for the HtmlHelper
• Return string or override ToString method
• TagBuilder manages closing tags and attributes
• Add namespace in web.config (if needed)
Cont...
– Another way to write helpers:
• Create folder /App_Code/
• Create a view in it (for example Helpers.cshtml)
• Write a helper in it using @helper
– You can use the helper in any view
– You have a lot of code in views? => write helpers
Partial Views
– Partial views render portions of a page
• Reuse pieces of a view
• Html helpers – Partial, RenderPartial and Action
– Razor partial views are still .cshtml files
Located in the same folder as
other views or in Shared folder
Sub-request
ASP.NET MVC Routing
– Mapping between patterns and a combination of
controller + action + parameters
– Routes are defined as a global list of routes
• System.Web.Routing.RouteTable.Routes
– Something similar to Apache mod_rewrite
– Greedy algorithm
• the first match wins
Register routes
– In Global.asax in the Application_Start() there is
RouteConfig.RegisterRoutes(RouteTable.Routes);
– RoutesConfig class is located in /App_Start/ in
internet applications template by default
Route name
Route pattern
Default parameters
Routes to ignore
The [*] means all left
Routing Example
http://localhost/Products/ById/3
–Controller: Products
–Action: ById
–Id: 3
Routing Example
– Controller: Products
– Action: ById
– Id: 0 (optional parameter)
http://localhost/Products/ById
Routing Example
– Controller: Products
– Action: Index
– Id: 0 (optional parameter)
http://localhost/Products
Routing Example
– Controller: Home
– Action: Index
– Id: 0 (optional parameter)
http://localhost/
Custom Route
– Controller: Users
– Action: ByUsername
– Username: admin
http://localhost/Users/ByUsername/ad
min
Custom Route
• Controller: Users
• Action: ByUsername
• Username: DefaultValue
http://localhost/Users
Custom Route
– Result: 404 Not Found
http://localhost/Users
?
Route Constraints
– Constraints are rules on the URL segments
– All the constraints are regular expression compatible
with class Regex
– Defined as one of the routes.MapRoute(…)
parameters
MVC Pattern for Web
MVC Steps
– Incoming request routed to Controller
– For web: HTTP request
– Controller processes request and creates
presentation Model
– Controller also selects appropriate result (view)
– Model is passed to View
– View transforms Model into appropriate output
format (HTML)
– Response is rendered (HTTP Response)
NuGet package management
– Free, open source package management
– Makes it easy to install and update open source libraries and tools
– Part of Visual Studio 2012
– Configurable package sources
– Simple as adding a reference
– GUI-based package installer
– Package manager console
– One of the advantages of using NuGet is that you don't have to ship
all the libraries in your project, reducing the project size. With
NuGet Power Tools, by specifying the package versions in the
Packages.config file, you will be able to download all the required
libraries the first time you run the project.
Bundling and Minification
– Bundling makes it easy to combine or bundle multiple files
into a single file. You can create CSS, JavaScript and other
bundles. Fewer files means fewer HTTP requests and that can
improve first page load performance.
– Minification performs a variety of different code optimizations
to scripts or CSS, such as removing unnecessary white space
and comments and shortening variable names to one
character.
– Improve loading performance of JavaScript and CSS
– Reduce # and size of HTTP requests
– Works by convention (no configuration required)
– Fully customizable and extensible
Bundling and Minification
Database Migrations
– EF is a powerful O/RM for .NET
– EF Code First provides a convention-over-
configuration based development approach
– Migrations == code-oriented approach to evolve DB
schema
• Code focused
• Developer friendly
• Can be used to generate SQL change scripts to pass off to a
DBA
Asynchronous Support
– Why use async on a server?
• Enables more efficient use of threads and server resources
– How does it work?
• Your controller class yields to ASP.NET when calling a
remote resource, allowing the server thread to be re-used
while you wait
• When remote call returns, controller is re-scheduled to
complete
• Reduces # of threads running -> increases scalability
– Use of async on server is not exposed to
browsers/clients
• http://myserver.com/products -> same URL can be
implemented in ASP.NET using either a synchronous or
async controller
Asynchronous Support
public class Products : Controller {
public async Task<ActionResult> IndexAsync() {
WebClient web = new WebClient();
string result = await web.DownloadStringAsync("www.bing.com/");
return View();
}
}
– Compared to the traditional asynchronous approaches the new
asynchronous programming model in .NET 4.5 is way cleaner and involves
just three main concepts await ,async and Task. The await and async are
the keywords introduced in C# 5.0 while Task is a type in
the System.Threading.Tasks namespace used for parallel programming.
We use task in asynchronous programming to specify the return type of a
method
Part -2
SQL Server
(Structured Query Language)
What is SQL ?
– SQL is standard language for accessing and
manipulating databases.
– SQL stands for Structured Query Language.
– In SQL you can accessing and manipulating databases
through SQL query.
– SQL is an ANSI(American National Standard Institute)
standard
What can SQL do?
– Using Sql we can do following process in database.
• Execute queries against a database
• Retrieve data from a database
• Insert records in a database
• Update records in a database
• Delete records from a database
• Create new databases
• Create new table in a database
• Create stored procedures in a database
• Create views in a databases
• Set permissions on tables, procedures, and views
Using SQL in Web Site
– To build a web site that shows data from a database, you
will need:
• An RDBMS database program (i.e. MS Access, SQL Server)
• To use a server-side scripting language, like php or ASP
• To use SQL to get the data you want
• To use HTML/CSS
– RDBMS
• RDBMS stands for Relational Database Management System.
• RDBMS is the basis for SQL, and for all modern database
systems such as MS SQL Server, IBM DB2, Oracle, MySQL, and
Microsoft Access.
• The data in RDBMS is stored in database objects called table
Some of The Most Important SQL Commands
– SELECT - extracts data from a database
– UPDATE - updates data in a database
– DELETE - deletes data from a database
– INSERT INTO - inserts new data into a database
– CREATE DATABASE - creates a new database
– ALTER DATABASE - modifies a database
– CREATE TABLE - creates a new table
– ALTER TABLE - modifies a table
– DROP TABLE - deletes a table
– CREATE INDEX - creates an index (search key)
– DROP INDEX - deletes an index
SQL Statements
– SQL SELECT Statement
• The SELECT statement is used to select data from a
database
• SELECT column_name,column_name
FROM table_name;
• SELECT * FROM table_name;
– SQL SELECT DISTINCT Statement
• The SELECT DISTINCT statement is used to return only
distinct (different) values.
• SELECT DISTINCT column_name,column_name
FROM table_name;
Cont…
– SQL SELECT INTO Statement
• The SELECT INTO statement copies data from one table
and inserts it into a new table.
• We can copy all columns into the new table:
• SELECT *
INTO newtable [IN externaldb]
FROM table1;
• We can copy selected columns into the new tabel:
• SELECT column_name(s)
INTO newtable [IN externaldb]
FROM table1;
Cont…
– SQL INSERT INTO Statement
• The INSERT INTO statement is used to insert new records in a
table.
• INSERT INTO table_name
VALUES (value1,value2,value3,...);
• INSERT INTO table_name (column1,column2,column3,...)
VALUES (value1,value2,value3,...);
– SQL UPDATE Statement
• The UPDATE statement is used to update existing records in a
table.
• UPDATE table_name
SET column1=value1,column2=value2,...
WHERE some_column=some_value;
Cont…
– SQL INSERT INTO SELECT Statement
• The INSERT INTO SELECT statement selects data from one table
and inserts it into an existing table. Any existing rows in the
target table are unaffected.
• We can copy all columns from one table to another, existing
table:
• INSERT INTO table2
SELECT * FROM table1;
• We can copy only the columns we want to into another, existing
table:
• INSERT INTO table2
(column_name(s))
SELECT column_name(s)
FROM table1;
Cont…
– SQL DELETE Statement
• The DELETE statement is used to delete rows in a table.
• DELETE FROM table_name
WHERE some_column=some_value;
• For deleting all data from data without delete table name
• DELETE FROM table_name;
Note: After Deleting records. You can’t undo this statement.
– SQL CREATE DATABASE Statement
• The CREATE DATABASE statement is used to create a
database.
• CREATE DATABASE dbname;
Cont…
– SQL CREATE TABLE Statement
• The CREATE TABLE statement is used to create a table in a database.
• CREATE TABLE table_name
(
column_name1 data_type(size),
column_name2 data_type(size),
column_name3 data_type(size),
....
);
• The column_name parameters specify the names of the
columns of the table.
• The data_type parameter specifies what type of data the
column can hold (e.g. varchar, integer, decimal, date, etc.).
• The size parameter specifies the maximum length of the
column of the table.
Cont…
– SQL CREATE INDEX Statement
• The CREATE INDEX statement is used to create indexes in tables.
• Indexes allow the database application to find data fast; without
reading the whole table.
• An index can be created in a table to find data more quickly and
efficiently.
• Users can’t see the indexes, they are just used to speed up
searches/queries.
• Updating a table with indexes takes more time than updating a
table without indexes.
• CREATE INDEX index_name
ON table_name (column_name) //Duplicate Value allow
• CREATE UNIQUE INDEX index_name
ON table_name (column_name) //Duplicate Value not allow
Cont…
– SQL DROP INDEX Statement
• The DROP INDEX statement is used to delete an index in a
table.
• DROP INDEX table_name.index_name
– SQL DROP TABLE Statement
• The DROP TABLE statement is used to delete a table.
• DROP TABLE table_name
– SQL DROP DATABASE Statement
• The DROP DATABASE statement is used to delete a
database.
• DROP DATABASE database_name
Cont…
– SQL TRUNCATE TABLE Statement
• Truncate Table statement is used to delete the data inside
the table and but it is not delete the table itself.
• TRUNCATE TABLE table_name
– SQL ALTER TABLE Statement
• The ALTER TABLE statement is used to add, delete, or
modify columns in an existing table.
• To add a column in a table
• ALTER TABLE table_name
ADD column_name datatype
• To Drop a column in a table
• ALTER TABLE table_name
DROP COLUMN column_name
Cont…
– SQL GROUP BY Statement
• The GROUP BY statement is used in conjunction with the
aggregate functions to group the result-set by one or more
columns.
• SELECT column_name, aggregate_function(column_name)
FROM table_name
WHERE column_name operator value
GROUP BY column_name;
SQL Clauses
– SQL WHERE Clause
• The WHERE clause is used to filter records.
• The WHERE clause is used to extract only those records
that fulfill a specified criterion.
• SELECT column_name,column_name
FROM table_name
WHERE column_name operator value;
– SQL SELECT TOP Clause
• The SELECT TOP clause is used to specify the number of
records to return.
• SELECT TOP number|percent column_name(s)
FROM table_name;
Cont…
– SQL HAVING Clause
• The HAVING clause was added to SQL because the WHERE
keyword could not be used with aggregate functions.
• SELECT column_name, aggregate_function(column_name)
FROM table_name
WHERE column_name operator value
GROUP BY column_name
HAVING aggregate_function(column_name) operator value;
• The following SQL statement finds if any of the employees has
registered more than 10 orders:
• SELECT Employees.LastName, COUNT(Orders.OrderID) AS
NumberOfOrders FROM (Orders
INNER JOIN Employees
ON Orders.EmployeeID=Employees.EmployeeID)
GROUP BY LastName
HAVING COUNT(Orders.OrderID) > 10;
SQL Operators
– SQL AND & OR Operators
• The AND & OR operators are used to filter records based on
more than one condition.
• The AND operator displays a record if both the first condition
AND the second condition are true.
• The OR operator displays a record if one of the first or second
condition is true.
• E.g. SELECT * FROM Customer
WHERE Country = ‘India’
AND City = ‘Surat’; // AND Operator
• E.g. SELECT * FROM Customer
WHERE City=‘Surat’ // OR Operator
OR City=‘Ahemedabad’;
Cont..
– SQL Like Operators
• The LIKE operator is used in a WHERE clause to search for a
specified pattern in a column
• SELECT column_name(s)
FROM table_name
WHERE column_name LIKE pattern;
• E.g. Select all customers with a city starting with letter “s”
SELECT * FROM Customers
WHERE City LIKE 's%';
• E.g. Select all customer with city containing the pattern
“amd”;
SELECT * FROM Customers
WHERE Country LIKE '%land%'; // NOT LIKE keyword can be use
Cont..
 SQL Wildcard Characters
• A wildcard character can be used to substitute for any
other character(s) in a string.
• In SQL, wildcard characters are used with the SQL LIKE
operator.
• SQL wildcards are used to search for data within a table.
Wildcard Description
% A substitute for zero or more characters
_ A substitute for a single character
[charlist] Sets and ranges of characters to match
[^charlist] or
[!charlist]
Matches only a character NOT specified within
the brackets
Cont..
– SQL IN Operators
• The IN operator allows you to specify multiple values in a
WHERE clause.
• Both city’s customer fetch using ‘in’ operator
• E.g. SELECT * FROM Customers
WHERE City IN (‘Vapi',‘Surat');
– SQL BETWEEN Operators
• The BETWEEN operator selects values within a range. The
values can be numbers, text, or dates.
• Fetch the product that price is in between 10 and 20
• E.g. SELECT * FROM Products
WHERE Price BETWEEN 10 AND 20;
Cont..
– SQL UNION Operators
• The SQL UNION operator combines the result of two or
more SELECT statements.
• Notice that each SELECT statement within the UNION must
have the same number of columns. The columns must also
have similar data types. Also, the columns in each SELECT
statement must be in the same order.
• SELECT column_name(s) FROM table1
UNION //Select only distinct values
SELECT column_name(s) FROM table2;
• SELECT column_name(s) FROM table1
UNION ALL //Select duplicate values also
SELECT column_name(s) FROM table2;
SQL Keywords
– SQL ORDER BY Keyword
• The ORDER BY keyword is used to sort the result-set by
one or more columns.
• The ORDER BY keyword sorts the records in ascending
order by default. To sort the records in a descending order,
you can use the DESC keyword.
• SELECT column_name,column_name
FROM table_name
ORDER BY column_name,column_name ASC|DESC;
SQL Aliases
– SQL Aliases
• SQL aliases are used to give a database table, or a column
in a table, a temporary name.
• Basically aliases are created to make column names more
readable.
• Alias Syntax for Columns
• SELECT column_name AS alias_name
FROM table_name;
• Alias Syntax for Tables
• SELECT column_name(s)
FROM table_name AS alias_name;
SQL Joins
– SQL joins are used to combine rows from two or more tables,
based on a common field between them.
– The most common type of join is: SQL INNER JOIN (simple
join). An SQL INNER JOIN return all rows from multiple tables
where the join condition is met.
– Different SQL JOINs
• INNER JOIN: Returns all rows when there is at least one match in BOTH
tables
• LEFT JOIN: Return all rows from the left table, and the matched rows
from the right table
• RIGHT JOIN: Return all rows from the right table, and the matched
rows from the left table
• FULL JOIN: Return all rows when there is a match in ONE of the tables
Cont..
– SQL INNER JOIN
• The INNER JOIN keyword selects all rows from both tables
as long as there is a match between the columns in both
tables.
• SELECT column_name(s)
FROM table1
INNER JOIN table2
ON table1.column_name=table2.column_name;
• At INNER JOIN keyword we can write only JOIN keyword
both have same meaing.
Cont..
– SQL LEFT JOIN
• The LEFT JOIN keyword returns all rows from the left table
(table1), with the matching rows in the right table (table2).
The result is NULL in the right side when there is no match.
• SELECT column_name(s)
FROM table1
LEFT JOIN table2
ON table1.column_name=table2.column_name;
• LEFT JOIN and LEFT OUTER JOIN have same meaning.
Cont..
– SQL RIGHT JOIN
• The RIGHT JOIN keyword returns all rows from the right
table (table2), with the matching rows in the left table
(table1). The result is NULL in the left side when there is no
match.
• SELECT column_name(s)
FROM table1
RIGHT JOIN table2
ON table1.column_name=table2.column_name;
• RIGHT JOIN and RIGHT OUTER JOIN have same meaning.
Cont..
– SQL FULL OUTER JOIN
• The FULL OUTER JOIN keyword returns all rows from the left
table (table1) and from the right table (table2).
• The FULL OUTER JOIN keyword combines the result of both
LEFT and RIGHT joins.
• SELECT column_name(s)
FROM table1
FULL OUTER JOIN table2
ON table1.column_name=table2.column_name;
SQL Constraints
– SQL constraints are used to specify rules for the data in a
table.
– If there is any violation between the constraint and the data
action, the action is aborted by the constraint.
– Constraints can be specified when the table is created (inside
the CREATE TABLE statement) or after the table is created
(inside the ALTER TABLE statement).
– CREATE TABLE table_name
(
column_name1 data_type(size) constraint_name,
column_name2 data_type(size) constraint_name,
column_name3 data_type(size) constraint_name,
....
);
Cont…
– In SQL, we have the following constraints:
– NOT NULL - Indicates that a column cannot store NULL value
– UNIQUE - Ensures that each row for a column must have a unique
value
– PRIMARY KEY - A combination of a NOT NULL and UNIQUE. Ensures
that a column (or combination of two or more columns) have an
unique identity which helps to find a particular record in a table more
easily and quickly
– FOREIGN KEY - Ensure the referential integrity of the data in one table
to match values in another table
– CHECK - Ensures that the value in a column meets a specific condition
– DEFAULT - Specifies a default value when specified none for this
column
Cont…
– AUTO INCREMENT Field
• Auto-increment allows a unique number to be generated
when a new record is inserted into a table.
• Syntax for SQL Server
• ID int IDENTITY(1,1) PRIMARY KEY,
• The MS SQL Server uses the IDENTITY keyword to perform
an auto-increment feature.
• In above example starting of identity is 1 and increment
with 1.
SQL Views
– A view is a virtual table based on the result-set of an
SQL statement.
– A view contains rows and columns, just like a real
table. The fields in a view are fields from one or more
real tables in the database.
– You can add SQL functions, WHERE, and JOIN
statements to a view and present the data as if the
data were coming from one single table.
– CREATE VIEW view_name AS
SELECT column_name(s)
FROM table_name
WHERE condition
SQL Functions
– SQL has many built-in functions for performing
calculations on data.
– SQL Aggregate Functions
• SQL aggregate functions return a single value, calculated
from values in a column.
a. AVG() - Returns the average value
b. COUNT() - Returns the number of rows
c. FIRST() - Returns the first value
d. LAST() - Returns the last value
e. MAX() - Returns the largest value
f. MIN() - Returns the smallest value
g. SUM() - Returns the sum
Cont…
– SQL Scalar functions
• SQL scalar functions return a single value , base on the
input value.
• Useful scalar functions:
a. UCASE() - Converts a field to upper case
b. LCASE() - Converts a field to lower case
c. MID() - Extract characters from a text field
d. LEN() - Returns the length of a text field
e. ROUND() - Rounds a numeric field to the number of decimals
specified
f. NOW() - Returns the current system date and time
g. FORMAT() - Formats how a field is to be displayed
SQL Stored Procedure
– It is the set of logically group of sql statement which are
grouped to perform a specific task.
– Main benefit of using a stored procedure is that it
increase the performance of database.
Create Procedure Procedure-name
(
Input parameters ,
Output Parameters (If required)
)
As
Begin
Sql statement used in the stored procedure
End
Cont…
– Benefits of using the stored procedure
a. It reduce the amount of information sent to the
database server. It is important when the network
bandwidth is less.
b. Compilation step is required only once when the
stored procedure is created.
c. It helps in re-usability of the sql code becase it can
be used by multiple users so just call the stored
procedure .It helps in reduces the development
time
Cont…
d. It also use for storing the business logic in the form
of stored procedure since it make it secure and if
any change is needed in the business logic then we
may only need to make changes in the stored
procedure and not in the files.
Create PROCEDURE Getstudentname(
@studentid INT --Input parameter , Studentid of the student
)
AS
BEGIN
SELECT Firstname+' '+Lastname FROM tbl_Students WHERE
studentid=@studentid
END
SQL Trigger
– A trigger is a special kind of a store procedure that
executes in response to certain action on the table
like insertion, deletion or updating of data.
– It is a database object which is bound to a table and
is executed automatically.
– Basically Triggers are classified in two types:
1. After Triggers(For Triggers)
2. Instead Of Triggers
– After Triggers are not used for View.
SQL Trigger
-- SQL Server Syntax
Trigger on an INSERT, UPDATE, or DELETE statement to a table or view (DML
Trigger)
CREATE TRIGGER [ schema_name . ]trigger_name
ON { table | view }
[ WITH <dml_trigger_option> [ ,...n ] ]
{ FOR | AFTER | INSTEAD OF }
{ [ INSERT ] [ , ] [ UPDATE ] [ , ] [ DELETE ] }
[ WITH APPEND ]
[ NOT FOR REPLICATION ]
AS { sql_statement [ ; ] [ ,...n ] | EXTERNAL NAME <method specifier [ ; ] > }
<dml_trigger_option> ::=
[ ENCRYPTION ]
[ EXECUTE AS Clause ]
<method_specifier> ::= assembly_name.class_name.method_name
SQL Injection
• SQL injection is a technique where malicious users
can inject SQL commands into an SQL statement, via
web page input.
• Injected SQL commands can alter SQL statement and
compromise the security of a web application.
• SQL Injection Based on 1=1 is Always True
UserId:
105 or 1=1
• Server Result
• SELECT * FROM Users WHERE UserId = 105 or 1=1
– The SQL above is valid. It will return all rows from the table
Users, since WHERE 1=1 is always true.
Cont..
• Second SQL injection E.g.
UserId:
105; DROP TABLE Suppliers
• Server Result
• SELECT * FROM Users WHERE UserId = 105; DROP TABLE
Suppliers
• Above server action will delete all the record of suppliers so
for stop this following method is used.
• Parameters for Protection
– To prevent this sql injection some web developers use “backlist” of
words and characters . But this is not good idea
– So use SQL parameter to stop SQL injection
Cont..
• ASP.NET Razor Example
• txtUserId = getRequestString("UserId");
txtSQL = "SELECT * FROM Users WHERE UserId = @0";
db.Execute(txtSQL,txtUserId);
• Note that parameters are represented in the SQL statement by a @
marker.
• The SQL engine checks each parameter to ensure that it is correct
for its column and are treated literally, and not as part of the SQL to
be executed.
• txtNam = getRequestString("CustomerName");
txtAdd = getRequestString("Address");
txtCit = getRequestString("City");
txtSQL = "INSERT INTO Customers (CustomerName,Address,City)
Values(@0,@1,@2)";
db.Execute(txtSQL,txtNam,txtAdd,txtCit);
Thank You
?

More Related Content

What's hot

In memory OLAP engine
In memory OLAP engineIn memory OLAP engine
In memory OLAP engine
WO Community
 
D2W Stateful Controllers
D2W Stateful ControllersD2W Stateful Controllers
D2W Stateful Controllers
WO Community
 

What's hot (20)

Modern development paradigms
Modern development paradigmsModern development paradigms
Modern development paradigms
 
Lecture 4: JavaServer Pages (JSP) & Expression Language (EL)
Lecture 4:  JavaServer Pages (JSP) & Expression Language (EL)Lecture 4:  JavaServer Pages (JSP) & Expression Language (EL)
Lecture 4: JavaServer Pages (JSP) & Expression Language (EL)
 
Backbone.js
Backbone.jsBackbone.js
Backbone.js
 
Backbone JS for mobile apps
Backbone JS for mobile appsBackbone JS for mobile apps
Backbone JS for mobile apps
 
Handlebars and Require.js
Handlebars and Require.jsHandlebars and Require.js
Handlebars and Require.js
 
In memory OLAP engine
In memory OLAP engineIn memory OLAP engine
In memory OLAP engine
 
Rest
Rest Rest
Rest
 
Backbone js
Backbone jsBackbone js
Backbone js
 
Spray - Build RESTfull services in scala
Spray - Build RESTfull services in scalaSpray - Build RESTfull services in scala
Spray - Build RESTfull services in scala
 
A Complete Tour of JSF 2
A Complete Tour of JSF 2A Complete Tour of JSF 2
A Complete Tour of JSF 2
 
Lecture 5 JSTL, custom tags, maven
Lecture 5   JSTL, custom tags, mavenLecture 5   JSTL, custom tags, maven
Lecture 5 JSTL, custom tags, maven
 
Jsf
JsfJsf
Jsf
 
Spark IT 2011 - Simplified Web Development using Java Server Faces 2.0
Spark IT 2011 - Simplified Web Development using Java Server Faces 2.0Spark IT 2011 - Simplified Web Development using Java Server Faces 2.0
Spark IT 2011 - Simplified Web Development using Java Server Faces 2.0
 
Jsf intro
Jsf introJsf intro
Jsf intro
 
Angular jS Introduction by Google
Angular jS Introduction by GoogleAngular jS Introduction by Google
Angular jS Introduction by Google
 
PHP & MVC
PHP & MVCPHP & MVC
PHP & MVC
 
D2W Stateful Controllers
D2W Stateful ControllersD2W Stateful Controllers
D2W Stateful Controllers
 
Session 36 - JSP - Part 1
Session 36 - JSP - Part 1Session 36 - JSP - Part 1
Session 36 - JSP - Part 1
 
MVC Training Part 1
MVC Training Part 1MVC Training Part 1
MVC Training Part 1
 
Struts N E W
Struts N E WStruts N E W
Struts N E W
 

Similar to MVC & SQL_In_1_Hour

django_introduction20141030
django_introduction20141030django_introduction20141030
django_introduction20141030
Kevin Wu
 

Similar to MVC & SQL_In_1_Hour (20)

ASP.NET MVC 5 - EF 6 - VS2015
ASP.NET MVC 5 - EF 6 - VS2015ASP.NET MVC 5 - EF 6 - VS2015
ASP.NET MVC 5 - EF 6 - VS2015
 
ASP.NET MVC introduction
ASP.NET MVC introductionASP.NET MVC introduction
ASP.NET MVC introduction
 
Building Modern Websites with ASP.NET by Rachel Appel
Building Modern Websites with ASP.NET by Rachel AppelBuilding Modern Websites with ASP.NET by Rachel Appel
Building Modern Websites with ASP.NET by Rachel Appel
 
C# Advanced L09-HTML5+ASP
C# Advanced L09-HTML5+ASPC# Advanced L09-HTML5+ASP
C# Advanced L09-HTML5+ASP
 
Asp.net mvc presentation by Nitin Sawant
Asp.net mvc presentation by Nitin SawantAsp.net mvc presentation by Nitin Sawant
Asp.net mvc presentation by Nitin Sawant
 
Asp.net With mvc handson
Asp.net With mvc handsonAsp.net With mvc handson
Asp.net With mvc handson
 
IGears: Template Architecture and Principles
IGears: Template Architecture and PrinciplesIGears: Template Architecture and Principles
IGears: Template Architecture and Principles
 
ASP.NET MVC 2.0
ASP.NET MVC 2.0ASP.NET MVC 2.0
ASP.NET MVC 2.0
 
Asp.Net MVC Intro
Asp.Net MVC IntroAsp.Net MVC Intro
Asp.Net MVC Intro
 
ASP.NET - Building Web Application..in the right way!
ASP.NET - Building Web Application..in the right way!ASP.NET - Building Web Application..in the right way!
ASP.NET - Building Web Application..in the right way!
 
ASP.NET - Building Web Application..in the right way!
ASP.NET - Building Web Application..in the right way!ASP.NET - Building Web Application..in the right way!
ASP.NET - Building Web Application..in the right way!
 
Practical catalyst
Practical catalystPractical catalyst
Practical catalyst
 
AngularJS training - Day 1 - Basics: Why, What and basic features of AngularJS
AngularJS training - Day 1 - Basics: Why, What and basic features of AngularJSAngularJS training - Day 1 - Basics: Why, What and basic features of AngularJS
AngularJS training - Day 1 - Basics: Why, What and basic features of AngularJS
 
Overview of MVC Framework - by software outsourcing company india
Overview of MVC Framework - by software outsourcing company indiaOverview of MVC Framework - by software outsourcing company india
Overview of MVC Framework - by software outsourcing company india
 
Asp.Net Mvc
Asp.Net MvcAsp.Net Mvc
Asp.Net Mvc
 
Web Components v1
Web Components v1Web Components v1
Web Components v1
 
AEM Sightly Deep Dive
AEM Sightly Deep DiveAEM Sightly Deep Dive
AEM Sightly Deep Dive
 
"Umbraco MVC - a journey of discovery" - Lotte Pitcher
"Umbraco MVC - a journey of discovery" - Lotte Pitcher"Umbraco MVC - a journey of discovery" - Lotte Pitcher
"Umbraco MVC - a journey of discovery" - Lotte Pitcher
 
django_introduction20141030
django_introduction20141030django_introduction20141030
django_introduction20141030
 
Introduction To Mvc
Introduction To MvcIntroduction To Mvc
Introduction To Mvc
 

MVC & SQL_In_1_Hour

  • 1. Part -1 Introduction to ASP.NET MVC4 Presented By : Dilip Patel.
  • 2. Table of Content • ASP.NET MVC • MVC Pattern (Model - View - Controller) • Controller Action Results, Action Parameters, Action Selectors, Action Filter, Custom Action Filters • Razor View • Routing • NuGet Package • Bundling/Minification Support • Database Migration • Asynchronous Support
  • 3. ASP.NET MVC ASP.NET MVC History – ASP.NET MVC 1.0 • In February 2007, Scott Guthrie ("ScottGu") of Microsoft sketched out the core of ASP.NET MVC • Released on 13 March 2009 – ASP.NET MVC 2.0 • Released just one year later, on 10 March 2010 – ASP.NET MVC 3.0 • Released on 13 January 2011 – ASP.NET MVC 4.0 • Released on 15 August 2012 – ASP.NET MVC 5.0 • Released on 17 October 2014
  • 4. ASP.NET Core Presentation Runtime Caching .NET HandlersRoutes Pages Controls Globalization Profile Master Pages MembershipRoles Etc... ASP.NET
  • 5. ASP.NET Web Forms – Rich controls and tools – Postbacks – Event driven web development – Viewstate – Less control over the HTML – Hard to test – Rapid development
  • 6. ASP.NET MVC – More control over HTML – No Codebehind – Separation of concerns – Easy to test – URL routing – No Postbacks – No ViewState
  • 7. MVC Pattern – Model - View - Controller (MVC) is a software architecture pattern – Originally formulated in the late 1970s by Trygve Reenskaug as part of the Smalltalk – Code reusability and separation of concerns – Originally developed for desktop, then adapted for internet applications.
  • 8. Model - View - Controller – Model - represents the logic of the application – View - the visual representation of the model – Controller - responsible for handling all user input
  • 9. Model – Model is set of classes that describe the application’s business logic, validation logic, database access logic – MVC can compatible with any data access technology through model. e.g. LINQ to SQL (Language Integrated Query) – All .edmx files, .dbml files etc. are located in the Models folder. – Here one application data-model-property example is given public class AssignedCourseData { public int CourseID { get; set; } public string Title { get; set; } public bool Assigned { get; set; } }
  • 10. View – View describe “How the application’s user interface(UI) will be displayed” – A view is a standard (X)HTML document that can contain scripts. – Most of Controller’s Action Return View – Script delimits in the view as related to two different view engine 1. Razor Engine – In razor view engine using “@” 2. WebForm Engine – In aspx view engine using “<% and %>” – May support master views (layouts) and sub-views (partial views or controls)
  • 11. Controller – The core MVC component. Basically it is a class and derived from System.Web.Mvc.Controller base class – Process the requests with the help of views and models – A set of classes that handles • Communication from the user • Overall application flow • Application Specific Logic – Every controller has one or more "Actions“ – Example for Home controller. public class Home Controller: Controller { public ActionResult Index() { return View(); } }
  • 12. Controller Actions – Public method of the Controller class – Cannot be overloaded – Cannot be a static method – Returns action result Action Results – Controller action response to a browser request – Inherits from the base ActionResult class – Different results types
  • 13. Action Results Types – ViewResult – EmptyResult – RedirectResult – JsonResult – JavaScriptResult – ContentResult – FileContentResult – FileStreamResult – FilePathResult
  • 14. Controller base class methods – View – Redirect – RedirectToAction – RedirectToRoute – Json – JavaScriptResult – Content – File
  • 15. Action Parameters – ASP.NET MVC maps the data from the HTTP request to action parameters in few ways: a. Routing engine can pass parameters to actions • http://localhost/Users/admin • Routing pattern: Users/{username} b. URL query string can contains parameters • /Users/ByUsername?username=admin c. HTTP post data can also contain parameters
  • 16. Action Selectors – ActionName(string name) – AcceptVerbs • HttpPost • HttpGet • HttpDelete • HttpOptions • ……. – NonAction – RequireHttps – ChildActionOnly – Only for Html.Action()
  • 17. Action Filters – Apply pre- and post-processing logic – Can be applied to actions and to controllers – Global filters can be registered in GlobalFilters. Filters (or in /App_Start/FilterConfig.cs) Name Description OutputCache Cache the output of a controller ValidateInput(false) Turn off request validation and allow dangerous input (html tags) Authorize Restrict an action to authorized users or roles ValidateAntiForgeryToken Helps prevent cross site request forgeries
  • 18. Custom Action Filter – Create C# class file in /Filters/ – Inherit ActionFilterAttribute – We can override: • OnActionExecuting(ActionExecutingContext) • OnActionExecuted(ActionExecutedContext) • OnResultExecuting(ResultExecutingContext) • OnResultExecuted(ResultExecutedContext) – We can apply our new attribute to a controller, method or globally in GlobalFilters.Filters
  • 19. Continue... public class LogAttribute : ActionFilterAttribute { public override void OnActionExecuting (ActionExecutingContext filterContext) { /* */ } public override void OnActionExecuted (ActionExecutedContext filterContext) { /* */ } public override void OnResultExecuting (ResultExecutingContext filterContext) { /* */ } public override void OnResultExecuted (ResultExecutedContext filterContext) { /* */ } } [Log] public class DepartmentController : Controller { // ... }
  • 20. Razor View • Template markup syntax • Simple-syntax view engine • Based on the C# programming language • Enables the programmer to use an HTML construction workflow • Code-focused templating approach, with minimal transition between HTML and code – Razor syntax starts code blocks with a @ character and does not require explicit closing of the code-block
  • 21. Pass Data to a View – With ViewBag (dynamic type): Action: ViewBag.Message = "Hello World!"; View: @ViewBag.Message – Strongly-typed views: Action: return View(model); View: @model ModelDataType; – With ViewData (dictionary): ViewData["message"] = "Hello World!"; View: @ViewData["message"]
  • 22. How it works... Template Data Generated Output ByUsername.cshtml UsersController.cs UserModel.cs HTML Output
  • 23. Razor Syntax – @ – For values (HTML encoded) <p> Current time is: @DateTime.Now!!! Not HTML encoded value: @Html.Raw(someVar) </p> – @{ … } – For code blocks (keep the view simple!) @{ var productName = "Energy drink"; if (Model != null) { productName = Model.ProductName; } else if (ViewBag.ProductName != null) { productName = ViewBag.ProductName; } } <p>Product "@productName" has been added in your shopping cart</p>
  • 24. Cont... – If, else, for, foreach, etc. C# statements • HTML markup lines can be included at any part • @: – For plain text line to be rendered <div class="products-list"> @if (Model.Products.Count() == 0) { <p>Sorry, no products found!</p> } else { @:List of the products found: foreach(var product in Model.Products) { <b>@product.Name, </b> } } </div>
  • 25. Cont... – Comments @* A Razor Comment *@ @{ //A C# comment /* A Multi line C# comment */ } – What about "@" and emails? <p> This is the sign that separates email names from domains: @@<br /> And this is how smart Razor is: spam_me@gmail.com </p>
  • 26. Cont... – @(…) – Explicit code expression <p> Current rating(0-10): @Model.Rating / 10.0 @* 6 / 10.0 *@ Current rating(0-1): @(Model.Rating / 10.0) @* 0.6 *@ spam_me@Model.Rating @*spam_me@Model.Rating*@ spam_me@(Model.Rating) @* spam_me6 *@ </p> – @using – for including namespace into view – @model – for defining the model for the view @using MyFirstMvcApplication.Models; @model UserModel <p>@Model.Username</p>
  • 27. Layout – Define a common site template – Similar to ASP.NET master pages (but better!) – Razor view engine renders content inside-out – First view is redered, then layout – @RenderBody() – indicate where we want the views based on this layout to “fill in” their core content at that location in the HTML
  • 28. Views and Layout – Views don't need to specify layout since their default layout is set in their _ViewStart file: – ~/Views/_ViewStart.cshtml (code for all views) – Each view can specify custom layout pages @{ Layout = "~/Views/Shared/_UncommonLayout.cshtml"; } – Views without layout: @{ Layout = null; }
  • 29. Sections – You can have one or more "sections" (optional) – They are defined in the views: – And may be rendered anywhere in the layout page using the method RenderSection() • @RenderSection(string name, bool required) • If the section is required and not defined, an exception will be thrown (IsSectionDefined())
  • 30. View Helpers – Each view inherits WebViewPage • ViewPage has a property named Html – Html property has methods that return string and can be used to generate HTML • Create inputs • Create links • Create forms – Other helper properties are also available • Ajax, Url, custom helpers
  • 31. Html Helpers Method Type Description BeginForm, BeginRouteForm Form Returns an internal object that represents an HTML form that the system uses to render the <form> tag EndForm Form A void method, closes the pending </form> tag CheckBox, CheckBoxFor Input Returns the HTML string for a check box input element Hidden, HiddenFor Input Returns the HTML string for a hidden input element Password, PasswordFor Input Returns the HTML string for a password input element RadioButton, RadioButtonFor Input Returns the HTML string for a radio button input element TextBox, TextBoxFor Input Returns the HTML string for a text input element Label, LabelFor Label Returns the HTML string for an HTML label element
  • 32. Cont... Method Type Description ActionLink, RouteLink Link Returns the HTML string for an HTML link DropDownList, DropDownListFor List Returns the HTML string for a drop-down list ListBox, ListBoxFor List Returns the HTML string for a list box TextArea, TextAreaFor TextArea Returns the HTML string for a text area Partial Partial Returns the HTML string incorporated in the specified user control RenderPartial Partial Writes the HTML string incorporated in the specified user control to the output stream ValidationMessage, ValidationMessageFor Validation Returns the HTML string for a validation message ValidationSummary Validation Returns the HTML string for a validation summary message
  • 33. Custom Helpers – Write extension methods for the HtmlHelper • Return string or override ToString method • TagBuilder manages closing tags and attributes • Add namespace in web.config (if needed)
  • 34. Cont... – Another way to write helpers: • Create folder /App_Code/ • Create a view in it (for example Helpers.cshtml) • Write a helper in it using @helper – You can use the helper in any view – You have a lot of code in views? => write helpers
  • 35. Partial Views – Partial views render portions of a page • Reuse pieces of a view • Html helpers – Partial, RenderPartial and Action – Razor partial views are still .cshtml files Located in the same folder as other views or in Shared folder Sub-request
  • 36. ASP.NET MVC Routing – Mapping between patterns and a combination of controller + action + parameters – Routes are defined as a global list of routes • System.Web.Routing.RouteTable.Routes – Something similar to Apache mod_rewrite – Greedy algorithm • the first match wins
  • 37. Register routes – In Global.asax in the Application_Start() there is RouteConfig.RegisterRoutes(RouteTable.Routes); – RoutesConfig class is located in /App_Start/ in internet applications template by default Route name Route pattern Default parameters Routes to ignore The [*] means all left
  • 39. Routing Example – Controller: Products – Action: ById – Id: 0 (optional parameter) http://localhost/Products/ById
  • 40. Routing Example – Controller: Products – Action: Index – Id: 0 (optional parameter) http://localhost/Products
  • 41. Routing Example – Controller: Home – Action: Index – Id: 0 (optional parameter) http://localhost/
  • 42. Custom Route – Controller: Users – Action: ByUsername – Username: admin http://localhost/Users/ByUsername/ad min
  • 43. Custom Route • Controller: Users • Action: ByUsername • Username: DefaultValue http://localhost/Users
  • 44. Custom Route – Result: 404 Not Found http://localhost/Users ?
  • 45. Route Constraints – Constraints are rules on the URL segments – All the constraints are regular expression compatible with class Regex – Defined as one of the routes.MapRoute(…) parameters
  • 47. MVC Steps – Incoming request routed to Controller – For web: HTTP request – Controller processes request and creates presentation Model – Controller also selects appropriate result (view) – Model is passed to View – View transforms Model into appropriate output format (HTML) – Response is rendered (HTTP Response)
  • 48. NuGet package management – Free, open source package management – Makes it easy to install and update open source libraries and tools – Part of Visual Studio 2012 – Configurable package sources – Simple as adding a reference – GUI-based package installer – Package manager console – One of the advantages of using NuGet is that you don't have to ship all the libraries in your project, reducing the project size. With NuGet Power Tools, by specifying the package versions in the Packages.config file, you will be able to download all the required libraries the first time you run the project.
  • 49. Bundling and Minification – Bundling makes it easy to combine or bundle multiple files into a single file. You can create CSS, JavaScript and other bundles. Fewer files means fewer HTTP requests and that can improve first page load performance. – Minification performs a variety of different code optimizations to scripts or CSS, such as removing unnecessary white space and comments and shortening variable names to one character. – Improve loading performance of JavaScript and CSS – Reduce # and size of HTTP requests – Works by convention (no configuration required) – Fully customizable and extensible
  • 51. Database Migrations – EF is a powerful O/RM for .NET – EF Code First provides a convention-over- configuration based development approach – Migrations == code-oriented approach to evolve DB schema • Code focused • Developer friendly • Can be used to generate SQL change scripts to pass off to a DBA
  • 52. Asynchronous Support – Why use async on a server? • Enables more efficient use of threads and server resources – How does it work? • Your controller class yields to ASP.NET when calling a remote resource, allowing the server thread to be re-used while you wait • When remote call returns, controller is re-scheduled to complete • Reduces # of threads running -> increases scalability – Use of async on server is not exposed to browsers/clients • http://myserver.com/products -> same URL can be implemented in ASP.NET using either a synchronous or async controller
  • 53. Asynchronous Support public class Products : Controller { public async Task<ActionResult> IndexAsync() { WebClient web = new WebClient(); string result = await web.DownloadStringAsync("www.bing.com/"); return View(); } } – Compared to the traditional asynchronous approaches the new asynchronous programming model in .NET 4.5 is way cleaner and involves just three main concepts await ,async and Task. The await and async are the keywords introduced in C# 5.0 while Task is a type in the System.Threading.Tasks namespace used for parallel programming. We use task in asynchronous programming to specify the return type of a method
  • 55. What is SQL ? – SQL is standard language for accessing and manipulating databases. – SQL stands for Structured Query Language. – In SQL you can accessing and manipulating databases through SQL query. – SQL is an ANSI(American National Standard Institute) standard
  • 56. What can SQL do? – Using Sql we can do following process in database. • Execute queries against a database • Retrieve data from a database • Insert records in a database • Update records in a database • Delete records from a database • Create new databases • Create new table in a database • Create stored procedures in a database • Create views in a databases • Set permissions on tables, procedures, and views
  • 57. Using SQL in Web Site – To build a web site that shows data from a database, you will need: • An RDBMS database program (i.e. MS Access, SQL Server) • To use a server-side scripting language, like php or ASP • To use SQL to get the data you want • To use HTML/CSS – RDBMS • RDBMS stands for Relational Database Management System. • RDBMS is the basis for SQL, and for all modern database systems such as MS SQL Server, IBM DB2, Oracle, MySQL, and Microsoft Access. • The data in RDBMS is stored in database objects called table
  • 58. Some of The Most Important SQL Commands – SELECT - extracts data from a database – UPDATE - updates data in a database – DELETE - deletes data from a database – INSERT INTO - inserts new data into a database – CREATE DATABASE - creates a new database – ALTER DATABASE - modifies a database – CREATE TABLE - creates a new table – ALTER TABLE - modifies a table – DROP TABLE - deletes a table – CREATE INDEX - creates an index (search key) – DROP INDEX - deletes an index
  • 59. SQL Statements – SQL SELECT Statement • The SELECT statement is used to select data from a database • SELECT column_name,column_name FROM table_name; • SELECT * FROM table_name; – SQL SELECT DISTINCT Statement • The SELECT DISTINCT statement is used to return only distinct (different) values. • SELECT DISTINCT column_name,column_name FROM table_name;
  • 60. Cont… – SQL SELECT INTO Statement • The SELECT INTO statement copies data from one table and inserts it into a new table. • We can copy all columns into the new table: • SELECT * INTO newtable [IN externaldb] FROM table1; • We can copy selected columns into the new tabel: • SELECT column_name(s) INTO newtable [IN externaldb] FROM table1;
  • 61. Cont… – SQL INSERT INTO Statement • The INSERT INTO statement is used to insert new records in a table. • INSERT INTO table_name VALUES (value1,value2,value3,...); • INSERT INTO table_name (column1,column2,column3,...) VALUES (value1,value2,value3,...); – SQL UPDATE Statement • The UPDATE statement is used to update existing records in a table. • UPDATE table_name SET column1=value1,column2=value2,... WHERE some_column=some_value;
  • 62. Cont… – SQL INSERT INTO SELECT Statement • The INSERT INTO SELECT statement selects data from one table and inserts it into an existing table. Any existing rows in the target table are unaffected. • We can copy all columns from one table to another, existing table: • INSERT INTO table2 SELECT * FROM table1; • We can copy only the columns we want to into another, existing table: • INSERT INTO table2 (column_name(s)) SELECT column_name(s) FROM table1;
  • 63. Cont… – SQL DELETE Statement • The DELETE statement is used to delete rows in a table. • DELETE FROM table_name WHERE some_column=some_value; • For deleting all data from data without delete table name • DELETE FROM table_name; Note: After Deleting records. You can’t undo this statement. – SQL CREATE DATABASE Statement • The CREATE DATABASE statement is used to create a database. • CREATE DATABASE dbname;
  • 64. Cont… – SQL CREATE TABLE Statement • The CREATE TABLE statement is used to create a table in a database. • CREATE TABLE table_name ( column_name1 data_type(size), column_name2 data_type(size), column_name3 data_type(size), .... ); • The column_name parameters specify the names of the columns of the table. • The data_type parameter specifies what type of data the column can hold (e.g. varchar, integer, decimal, date, etc.). • The size parameter specifies the maximum length of the column of the table.
  • 65. Cont… – SQL CREATE INDEX Statement • The CREATE INDEX statement is used to create indexes in tables. • Indexes allow the database application to find data fast; without reading the whole table. • An index can be created in a table to find data more quickly and efficiently. • Users can’t see the indexes, they are just used to speed up searches/queries. • Updating a table with indexes takes more time than updating a table without indexes. • CREATE INDEX index_name ON table_name (column_name) //Duplicate Value allow • CREATE UNIQUE INDEX index_name ON table_name (column_name) //Duplicate Value not allow
  • 66. Cont… – SQL DROP INDEX Statement • The DROP INDEX statement is used to delete an index in a table. • DROP INDEX table_name.index_name – SQL DROP TABLE Statement • The DROP TABLE statement is used to delete a table. • DROP TABLE table_name – SQL DROP DATABASE Statement • The DROP DATABASE statement is used to delete a database. • DROP DATABASE database_name
  • 67. Cont… – SQL TRUNCATE TABLE Statement • Truncate Table statement is used to delete the data inside the table and but it is not delete the table itself. • TRUNCATE TABLE table_name – SQL ALTER TABLE Statement • The ALTER TABLE statement is used to add, delete, or modify columns in an existing table. • To add a column in a table • ALTER TABLE table_name ADD column_name datatype • To Drop a column in a table • ALTER TABLE table_name DROP COLUMN column_name
  • 68. Cont… – SQL GROUP BY Statement • The GROUP BY statement is used in conjunction with the aggregate functions to group the result-set by one or more columns. • SELECT column_name, aggregate_function(column_name) FROM table_name WHERE column_name operator value GROUP BY column_name;
  • 69. SQL Clauses – SQL WHERE Clause • The WHERE clause is used to filter records. • The WHERE clause is used to extract only those records that fulfill a specified criterion. • SELECT column_name,column_name FROM table_name WHERE column_name operator value; – SQL SELECT TOP Clause • The SELECT TOP clause is used to specify the number of records to return. • SELECT TOP number|percent column_name(s) FROM table_name;
  • 70. Cont… – SQL HAVING Clause • The HAVING clause was added to SQL because the WHERE keyword could not be used with aggregate functions. • SELECT column_name, aggregate_function(column_name) FROM table_name WHERE column_name operator value GROUP BY column_name HAVING aggregate_function(column_name) operator value; • The following SQL statement finds if any of the employees has registered more than 10 orders: • SELECT Employees.LastName, COUNT(Orders.OrderID) AS NumberOfOrders FROM (Orders INNER JOIN Employees ON Orders.EmployeeID=Employees.EmployeeID) GROUP BY LastName HAVING COUNT(Orders.OrderID) > 10;
  • 71. SQL Operators – SQL AND & OR Operators • The AND & OR operators are used to filter records based on more than one condition. • The AND operator displays a record if both the first condition AND the second condition are true. • The OR operator displays a record if one of the first or second condition is true. • E.g. SELECT * FROM Customer WHERE Country = ‘India’ AND City = ‘Surat’; // AND Operator • E.g. SELECT * FROM Customer WHERE City=‘Surat’ // OR Operator OR City=‘Ahemedabad’;
  • 72. Cont.. – SQL Like Operators • The LIKE operator is used in a WHERE clause to search for a specified pattern in a column • SELECT column_name(s) FROM table_name WHERE column_name LIKE pattern; • E.g. Select all customers with a city starting with letter “s” SELECT * FROM Customers WHERE City LIKE 's%'; • E.g. Select all customer with city containing the pattern “amd”; SELECT * FROM Customers WHERE Country LIKE '%land%'; // NOT LIKE keyword can be use
  • 73. Cont..  SQL Wildcard Characters • A wildcard character can be used to substitute for any other character(s) in a string. • In SQL, wildcard characters are used with the SQL LIKE operator. • SQL wildcards are used to search for data within a table. Wildcard Description % A substitute for zero or more characters _ A substitute for a single character [charlist] Sets and ranges of characters to match [^charlist] or [!charlist] Matches only a character NOT specified within the brackets
  • 74. Cont.. – SQL IN Operators • The IN operator allows you to specify multiple values in a WHERE clause. • Both city’s customer fetch using ‘in’ operator • E.g. SELECT * FROM Customers WHERE City IN (‘Vapi',‘Surat'); – SQL BETWEEN Operators • The BETWEEN operator selects values within a range. The values can be numbers, text, or dates. • Fetch the product that price is in between 10 and 20 • E.g. SELECT * FROM Products WHERE Price BETWEEN 10 AND 20;
  • 75. Cont.. – SQL UNION Operators • The SQL UNION operator combines the result of two or more SELECT statements. • Notice that each SELECT statement within the UNION must have the same number of columns. The columns must also have similar data types. Also, the columns in each SELECT statement must be in the same order. • SELECT column_name(s) FROM table1 UNION //Select only distinct values SELECT column_name(s) FROM table2; • SELECT column_name(s) FROM table1 UNION ALL //Select duplicate values also SELECT column_name(s) FROM table2;
  • 76. SQL Keywords – SQL ORDER BY Keyword • The ORDER BY keyword is used to sort the result-set by one or more columns. • The ORDER BY keyword sorts the records in ascending order by default. To sort the records in a descending order, you can use the DESC keyword. • SELECT column_name,column_name FROM table_name ORDER BY column_name,column_name ASC|DESC;
  • 77. SQL Aliases – SQL Aliases • SQL aliases are used to give a database table, or a column in a table, a temporary name. • Basically aliases are created to make column names more readable. • Alias Syntax for Columns • SELECT column_name AS alias_name FROM table_name; • Alias Syntax for Tables • SELECT column_name(s) FROM table_name AS alias_name;
  • 78. SQL Joins – SQL joins are used to combine rows from two or more tables, based on a common field between them. – The most common type of join is: SQL INNER JOIN (simple join). An SQL INNER JOIN return all rows from multiple tables where the join condition is met. – Different SQL JOINs • INNER JOIN: Returns all rows when there is at least one match in BOTH tables • LEFT JOIN: Return all rows from the left table, and the matched rows from the right table • RIGHT JOIN: Return all rows from the right table, and the matched rows from the left table • FULL JOIN: Return all rows when there is a match in ONE of the tables
  • 79. Cont.. – SQL INNER JOIN • The INNER JOIN keyword selects all rows from both tables as long as there is a match between the columns in both tables. • SELECT column_name(s) FROM table1 INNER JOIN table2 ON table1.column_name=table2.column_name; • At INNER JOIN keyword we can write only JOIN keyword both have same meaing.
  • 80. Cont.. – SQL LEFT JOIN • The LEFT JOIN keyword returns all rows from the left table (table1), with the matching rows in the right table (table2). The result is NULL in the right side when there is no match. • SELECT column_name(s) FROM table1 LEFT JOIN table2 ON table1.column_name=table2.column_name; • LEFT JOIN and LEFT OUTER JOIN have same meaning.
  • 81. Cont.. – SQL RIGHT JOIN • The RIGHT JOIN keyword returns all rows from the right table (table2), with the matching rows in the left table (table1). The result is NULL in the left side when there is no match. • SELECT column_name(s) FROM table1 RIGHT JOIN table2 ON table1.column_name=table2.column_name; • RIGHT JOIN and RIGHT OUTER JOIN have same meaning.
  • 82. Cont.. – SQL FULL OUTER JOIN • The FULL OUTER JOIN keyword returns all rows from the left table (table1) and from the right table (table2). • The FULL OUTER JOIN keyword combines the result of both LEFT and RIGHT joins. • SELECT column_name(s) FROM table1 FULL OUTER JOIN table2 ON table1.column_name=table2.column_name;
  • 83. SQL Constraints – SQL constraints are used to specify rules for the data in a table. – If there is any violation between the constraint and the data action, the action is aborted by the constraint. – Constraints can be specified when the table is created (inside the CREATE TABLE statement) or after the table is created (inside the ALTER TABLE statement). – CREATE TABLE table_name ( column_name1 data_type(size) constraint_name, column_name2 data_type(size) constraint_name, column_name3 data_type(size) constraint_name, .... );
  • 84. Cont… – In SQL, we have the following constraints: – NOT NULL - Indicates that a column cannot store NULL value – UNIQUE - Ensures that each row for a column must have a unique value – PRIMARY KEY - A combination of a NOT NULL and UNIQUE. Ensures that a column (or combination of two or more columns) have an unique identity which helps to find a particular record in a table more easily and quickly – FOREIGN KEY - Ensure the referential integrity of the data in one table to match values in another table – CHECK - Ensures that the value in a column meets a specific condition – DEFAULT - Specifies a default value when specified none for this column
  • 85. Cont… – AUTO INCREMENT Field • Auto-increment allows a unique number to be generated when a new record is inserted into a table. • Syntax for SQL Server • ID int IDENTITY(1,1) PRIMARY KEY, • The MS SQL Server uses the IDENTITY keyword to perform an auto-increment feature. • In above example starting of identity is 1 and increment with 1.
  • 86. SQL Views – A view is a virtual table based on the result-set of an SQL statement. – A view contains rows and columns, just like a real table. The fields in a view are fields from one or more real tables in the database. – You can add SQL functions, WHERE, and JOIN statements to a view and present the data as if the data were coming from one single table. – CREATE VIEW view_name AS SELECT column_name(s) FROM table_name WHERE condition
  • 87. SQL Functions – SQL has many built-in functions for performing calculations on data. – SQL Aggregate Functions • SQL aggregate functions return a single value, calculated from values in a column. a. AVG() - Returns the average value b. COUNT() - Returns the number of rows c. FIRST() - Returns the first value d. LAST() - Returns the last value e. MAX() - Returns the largest value f. MIN() - Returns the smallest value g. SUM() - Returns the sum
  • 88. Cont… – SQL Scalar functions • SQL scalar functions return a single value , base on the input value. • Useful scalar functions: a. UCASE() - Converts a field to upper case b. LCASE() - Converts a field to lower case c. MID() - Extract characters from a text field d. LEN() - Returns the length of a text field e. ROUND() - Rounds a numeric field to the number of decimals specified f. NOW() - Returns the current system date and time g. FORMAT() - Formats how a field is to be displayed
  • 89. SQL Stored Procedure – It is the set of logically group of sql statement which are grouped to perform a specific task. – Main benefit of using a stored procedure is that it increase the performance of database. Create Procedure Procedure-name ( Input parameters , Output Parameters (If required) ) As Begin Sql statement used in the stored procedure End
  • 90. Cont… – Benefits of using the stored procedure a. It reduce the amount of information sent to the database server. It is important when the network bandwidth is less. b. Compilation step is required only once when the stored procedure is created. c. It helps in re-usability of the sql code becase it can be used by multiple users so just call the stored procedure .It helps in reduces the development time
  • 91. Cont… d. It also use for storing the business logic in the form of stored procedure since it make it secure and if any change is needed in the business logic then we may only need to make changes in the stored procedure and not in the files. Create PROCEDURE Getstudentname( @studentid INT --Input parameter , Studentid of the student ) AS BEGIN SELECT Firstname+' '+Lastname FROM tbl_Students WHERE studentid=@studentid END
  • 92. SQL Trigger – A trigger is a special kind of a store procedure that executes in response to certain action on the table like insertion, deletion or updating of data. – It is a database object which is bound to a table and is executed automatically. – Basically Triggers are classified in two types: 1. After Triggers(For Triggers) 2. Instead Of Triggers – After Triggers are not used for View.
  • 93. SQL Trigger -- SQL Server Syntax Trigger on an INSERT, UPDATE, or DELETE statement to a table or view (DML Trigger) CREATE TRIGGER [ schema_name . ]trigger_name ON { table | view } [ WITH <dml_trigger_option> [ ,...n ] ] { FOR | AFTER | INSTEAD OF } { [ INSERT ] [ , ] [ UPDATE ] [ , ] [ DELETE ] } [ WITH APPEND ] [ NOT FOR REPLICATION ] AS { sql_statement [ ; ] [ ,...n ] | EXTERNAL NAME <method specifier [ ; ] > } <dml_trigger_option> ::= [ ENCRYPTION ] [ EXECUTE AS Clause ] <method_specifier> ::= assembly_name.class_name.method_name
  • 94. SQL Injection • SQL injection is a technique where malicious users can inject SQL commands into an SQL statement, via web page input. • Injected SQL commands can alter SQL statement and compromise the security of a web application. • SQL Injection Based on 1=1 is Always True UserId: 105 or 1=1 • Server Result • SELECT * FROM Users WHERE UserId = 105 or 1=1 – The SQL above is valid. It will return all rows from the table Users, since WHERE 1=1 is always true.
  • 95. Cont.. • Second SQL injection E.g. UserId: 105; DROP TABLE Suppliers • Server Result • SELECT * FROM Users WHERE UserId = 105; DROP TABLE Suppliers • Above server action will delete all the record of suppliers so for stop this following method is used. • Parameters for Protection – To prevent this sql injection some web developers use “backlist” of words and characters . But this is not good idea – So use SQL parameter to stop SQL injection
  • 96. Cont.. • ASP.NET Razor Example • txtUserId = getRequestString("UserId"); txtSQL = "SELECT * FROM Users WHERE UserId = @0"; db.Execute(txtSQL,txtUserId); • Note that parameters are represented in the SQL statement by a @ marker. • The SQL engine checks each parameter to ensure that it is correct for its column and are treated literally, and not as part of the SQL to be executed. • txtNam = getRequestString("CustomerName"); txtAdd = getRequestString("Address"); txtCit = getRequestString("City"); txtSQL = "INSERT INTO Customers (CustomerName,Address,City) Values(@0,@1,@2)"; db.Execute(txtSQL,txtNam,txtAdd,txtCit);

Editor's Notes

  1. Viewresult - If you want an action method to result in a rendered view, the action method should return a call to the controller's View helper method. The View helper method passes a ViewResult object to the ASP.NET MVC framework, which calls the object's ExecuteResult method. JsonResult - Represents a class that is used to send JSON-formatted content to the response. JavaScriptResult - Sends JavaScript content to the response. ContentResult - Represents a user-defined content type that is the result of an action method. FileContntResult - Represents a class that is used to send binary file content to the response FileStreamResult - Sends binary content to the response by using a Stream instance. FilePathResult - Sends the contents of a file to the response
  2. View - Creates a ViewResult object that renders a view to the response. Redirect - Creates a RedirectResult object that redirects to the specified URL. RedirectToAction - Redirects to the specified action using the action name Json - Creates a JsonResult object that serializes the specified object to JavaScript Object Notation (JSON) format. JavaScript - Creates a JavaScriptResult object Content - Creates a content result object by using a string. File - Creates a FileContentResult object by using the file contents and file type.