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 TrygveReenskaug as part of the Smalltalk
– Code reusability and separation of concerns
– Originally developed for desktop, then adaptedfor 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 engine1. 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 (ActionExecutingContextfilterContext) { /* */ }
public override void OnActionExecuted (ActionExecutedContextfilterContext) { /* */ }
public override void OnResultExecuting (ResultExecutingContextfilterContext) { /* */ }
public override void OnResultExecuted (ResultExecutedContextfilterContext) { /* */ }}
[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: [email protected]
</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 *@
[email protected] @*[email protected]*@
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 wantthe views based on thislayout to “fill in” theircore content at thatlocation 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 HelpersMethod 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 ignoreThe [*] means all left
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
Custom Route
– Controller: Users– Action: ByUsername– Username: admin
http://localhost/Users/ByUsername/admin
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 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 shipall the libraries in your project, reducing the project size. WithNuGet Power Tools, by specifying the package versions in thePackages.config file, you will be able to download all the requiredlibraries 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
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
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_nameFROM 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_nameFROM 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_nameSET 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 table2SELECT * 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_nameWHERE 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_nameON table_name (column_name) //Duplicate Value allow
• CREATE UNIQUE INDEX index_nameON 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_nameWHERE column_name operator valueGROUP 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_nameFROM table_nameWHERE 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_nameWHERE column_name operator valueGROUP BY column_nameHAVING 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 (OrdersINNER JOIN EmployeesON Orders.EmployeeID=Employees.EmployeeID)GROUP BY LastNameHAVING 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_nameWHERE 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 CustomersWHERE 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 ProductsWHERE 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 table1UNION //Select only distinct valuesSELECT column_name(s) FROM table2;
• SELECT column_name(s) FROM table1UNION ALL //Select duplicate values alsoSELECT 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_nameFROM table_nameORDER 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 table1INNER JOIN table2ON 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 table1LEFT JOIN table2ON 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 table1RIGHT JOIN table2ON 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 table1FULL OUTER JOIN table2ON table1.column_name=table2.column_name;
SQL Constraints
– SQL constraints are used to specify rules for the data in atable.
– If there is any violation between the constraint and the dataaction, the action is aborted by the constraint.
– Constraints can be specified when the table is created (insidethe 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 uniquevalue
– PRIMARY KEY - A combination of a NOT NULL and UNIQUE. Ensuresthat a column (or combination of two or more columns) have anunique identity which helps to find a particular record in a table moreeasily and quickly
– FOREIGN KEY - Ensure the referential integrity of the data in one tableto 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 thiscolumn
Cont…
– AUTO INCREMENT Field
• Auto-increment allows a unique number to be generatedwhen 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 performan auto-increment feature.
• In above example starting of identity is 1 and incrementwith 1.
SQL Views
– A view is a virtual table based on the result-set of anSQL statement.
– A view contains rows and columns, just like a realtable. The fields in a view are fields from one or morereal tables in the database.
– You can add SQL functions, WHERE, and JOINstatements to a view and present the data as if thedata were coming from one single table.
– CREATE VIEW view_name ASSELECT column_name(s)FROM table_nameWHERE condition
SQL Functions
– SQL has many built-in functions for performingcalculations 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 theinput 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 decimalsspecified
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 aregrouped to perform a specific task.
– Main benefit of using a stored procedure is that itincrease the performance of database.Create Procedure Procedure-name
(Input parameters ,Output Parameters (If required))
AsBegin
Sql statement used in the stored procedureEnd
Cont…
– Benefits of using the stored procedure
a. It reduce the amount of information sent to thedatabase server. It is important when the networkbandwidth is less.
b. Compilation step is required only once when thestored procedure is created.
c. It helps in re-usability of the sql code becase it canbe used by multiple users so just call the storedprocedure .It helps in reduces the developmenttime
Cont…
d. It also use for storing the business logic in the formof stored procedure since it make it secure and ifany change is needed in the business logic then wemay only need to make changes in the storedprocedure 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 thatexecutes in response to certain action on the tablelike insertion, deletion or updating of data.
– It is a database object which is bound to a table andis 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 SyntaxTrigger on an INSERT, UPDATE, or DELETE statement to a table or view (DML
Trigger)
CREATE TRIGGER [ schema_name . ]trigger_nameON { 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);