Sei sulla pagina 1di 48

Cum sa construiesti o aplicatie ASP.

NET MVC

Radu Florescu

15 martie 2014 Radu Florescu


All Rights Reserved

ii

Cuprins

Introduction

0.1 Introduction to OOP . . . . . . . . . . . . . . .


0.1.1 What is Object Oriented Programming?
0.1.2 OOP Keywords . . . . . . . . . . . . . .
0.2 Introduction to SQL . . . . . . . . . . . . . . .
0.2.1 What is SQL? . . . . . . . . . . . . . .
0.2.2 SQL dictionary . . . . . . . . . . . . . .
0.2.3 DML vs DDL . . . . . . . . . . . . . . .
0.2.4 DDL statements . . . . . . . . . . . . .
0.2.5 DML statements . . . . . . . . . . . . .
0.3 Introduction to C# . . . . . . . . . . . . . . . .
0.3.1 C# history . . . . . . . . . . . . . . . .
0.3.2 Similarities to C++ and Java . . . . . .
0.3.3 Data types . . . . . . . . . . . . . . . .
0.3.4 Variables . . . . . . . . . . . . . . . . .
0.3.5 Variable declaration . . . . . . . . . . .
0.3.6 C# statements . . . . . . . . . . . . . .
0.3.7 C# Namespaces . . . . . . . . . . . . .
0.3.8 C# Classes . . . . . . . . . . . . . . . .
0.3.9 C# Interfaces . . . . . . . . . . . . . . .
0.3.10 C# Access Modiers . . . . . . . . . . .
0.3.11 C# Other Modiers . . . . . . . . . . .
0.3.12 C# Properties . . . . . . . . . . . . . .
0.3.13 C# Attributes . . . . . . . . . . . . . .
0.3.14 C# Arrays and Collections . . . . . . .
0.3.15 C# Generics . . . . . . . . . . . . . . .
0.4 Reference materials . . . . . . . . . . . . . . . .

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

I Introducere In ASP.NET MVC

vii

vii
vii
vii
viii
viii
viii
ix
ix
xiv
xvi
xvi
xvi
xvii
xvii
xvii
xix
xxi
xxi
xxi
xxii
xxii
xxiii
xxiv
xxiv
xxv
xxv

1 ASP.NET

1.1 Istorie . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
1.2 What is MVC? . . . . . . . . . . . . . . . . . . . . . . . . . .
1.2.1 Separarea responsabilitatilor (Separations of concerns)
1.2.2 Diferentele dintre ASP.Net si ASP.NET MVC . . . . .
1.3 Bazele ASP.NET . . . . . . . . . . . . . . . . . . . . . . . . .
1.3.1 Structura proiectului . . . . . . . . . . . . . . . . . . .
1.4 References . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
iii

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

3
4
5
5
6
6
8

CUPRINS

iv

2 Entity Framework Code First


2.1
2.2
2.3
2.4
2.5
2.6
2.7
2.8
2.9
2.10

Ce este un ORM? . . . . .
Despre Entity Framework
Congurari . . . . . . . .
Modelul edmx . . . . . . .
T4 . . . . . . . . . . . . .
Generare de clase . . . . .
Comenzi . . . . . . . . . .
Modele . . . . . . . . . . .
Atribute . . . . . . . . . .
Referinte . . . . . . . . . .

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

Inregistrarea unui utilizator nou . . . . . . . . . .


Baza de date locala vs Baza de date SQL Server
Descrierea modelului de date curent . . . . . . .
Generarea primei migrari . . . . . . . . . . . . .
Adaugarea functionalitatii MVC . . . . . . . . .
Primul produs adaugat . . . . . . . . . . . . . . .

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

3 Code First Tutorial curs 1


3.1
3.2
3.3
3.4
3.5
3.6

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

9
10
10
10
10
10
10
11
11
11

13

14
15
16
16
19
19

Prefata
This course is base on existing tutorials available on the internet, most of them from PluralSight and Exam
Ref 70-486 book. It was designed as a full course to learn how to create a functional website, with basic
functionality.
Technologies used in this course will be ASP.Net MVC4, C# SQL, Entity Framework 5 Code First Approach,
HTML5, CSS3 and javascript/JQuery.

vi

CUPRINS

Introduction
In order to understand this course, you will be able to know basic of OOP, SQL, HTML and javascript.

0.1 Introduction to OOP


0.1.1 What is Object Oriented Programming?
OOP is the short form or abbreviation of Object Oriented Programming. In theory, we get an input and
then we process that data into an output data that will be sent out. This information from the output will
be processed in a linear fashion in order to produce a return value.
Initially, before OOP was rst introduced, the programs with similar functionality had large portions of
duplicate code, which was both hard to maintain and harder to know and modify accordingly. First time
there were functions and procedures, which extracted some of the existing code in separate portion of space
which was available to the whole program. The expected outcome was a code which was lighter, easier to
understand and to maintain, but still this wasn't enough. There had to be a procedure, that given a required
amount of input data, will produce an expected result for each of the times it was used, and so OOP was born.
OOP meant that all the data (both input, output and internal) were held in the same place as the functions which manipulated it and it's name is "CLASS". And our code contained one or more classes which
processed data in a certain way in order to produce the desired outcome.

0.1.2 OOP Keywords


Object. An object is everything that can be represented through data and operation that can be applied
to the data. An object can be a representation of a real life entity, like a car.

Class. A denition/specication of an object, an it is used to dene a set of properties and methods for

all the object that are from a class. The short form for this would be that: An Object is an instance of a
class.

Encapsulation. The process of gather a set of properties and methods in one class which will provide a
desired output. This hides certain part of our code from the outside world. This is also part of the black
box concept, together with Interface.
Interface. A set of methods and properties which are exposed to the outside of the class. All methods
dened in an interface "must" be implemented by the class which implements that interface.

A good example of encapsulation and interface. A useful example would be an elevator. From the
outside world we are only seeing the commands which allow us to call the elevator and to command it to go
to a certain oor (which is the interface and allows us to access certain methods of the elevator). Also, we
have certain parts hidden like the mechanisms to lift or to lower the elevator or the electronic components
for buttons which we don't know how they are implemented.
vii

viii

INTRODUCTION

Abstraction. Refers to data, that we only want to represent as pattern of a class. For example an abstract

class can be a class which represents an animal and all animals eat. This means that an abstract class can
idealize this concept into a method "EatFood()".

Inheritance. Refers to the fact that a class can inherit certain features of an another class. For example,

we have a fruit class which can be inherited by an Apple and an Orange class. Both of which are instance of
a Fruit, but in particular an Apple has a dierent taste, color and aspect which are dierent from an Orange.

Polymorphism. Refers to the fact that in a hierarchy of classes, those classes are derived from a base

class. For example, Animal class has a Girae class and an Elephant class. Those child classes will both
have an implementation of "EatFood()". When we will use an instance of one of them, we will only know
the existence of EatFood Method and we will execute it either from the Elephant class or the Girae class.
Also, any method which inherits some methods from the parent may choose to use that functionality, extend
or create a new one.

0.2 Introduction to SQL


0.2.1 What is SQL?
SQL stands for Structured Query Language.
SQL lets you access and manipulate databases.
SQL is an ANSI (American National Standards Institute) standard.

0.2.2 SQL dictionary


Entry. A row containing data of dierent types.
Table. A collection of entries of same type. A table consists of many columns, which may or not be of the
same type.

Index. A collection of dierent columns that will be used to search data easily.
Primary Key. A collection of columns which are used to identify in a unique manner a table row.
Foreign Key. A collection of columns which are used to make relations between a table and another one.
Multiplicity. In RDBMS there are many type of relations between tables: one to one, one to many, many

to one and many to many. The last one uses one extra table which will have a many to one relation with
the other 2 tables.

Constraint. Is related to data and it is used to specify some rules regarding entries in a row or table.
Unique Constraint. requires us to introduce unique data in a specied table.
Foreign Key Constraint. requires that when you enter data in a table that is in relation to another one,
to enter only entries related to existing data. Or even more simple: A FOREIGN KEY from one table points
to a PRIMARY KEY from another table.

Trigger. An event that happens when a certain condition occurs.

0.2. INTRODUCTION TO SQL

ix

0.2.3 DML vs DDL


DDL stands for Data Denition Language, meaning a series of commands and instructions that will help us
dene data structure, create, modify and delete tables, indexes, constraints etc.
DML means Data Modeling Language, which is a series of instructions that will help us to do a series
of operations known as CRUD (Create, Retrieve, Update, Delete). It can have more other instructions, but
we will learn more later.

0.2.4 DDL statements


ALTER Statements (Transact-SQL) This statement can be used to alter some settings like: Database,
tables, indexes.

ALTER DATABASE database_name


{
| MODIFY NAME = new_database_name
| COLLATE collation_name
| <file_and_filegroup_options>
| <set_database_options>
}
[;]
<file_and_filegroup_options >::=
<add_or_modify_files>::=
<filespec>::=
<add_or_modify_filegroups>::=
<filegroup_updatability_option>::=
<set_database_options>::=
<optionspec>::=
<auto_option> ::=
<change_tracking_option> ::=
<cursor_option> ::=
<database_mirroring_option> ::=
<date_correlation_optimization_option> ::=
<db_encryption_option> ::=
<db_state_option> ::=
<db_update_option> ::=
<db_user_access_option> ::=
<external_access_option> ::=
<parameterization_option> ::=
<recovery_option> ::=
<service_broker_option> ::=
<snapshot_option> ::=
<sql_option> ::=
<termination> ::=
Arguments
database_name: Is the name of the database to be modified.
MODIFY NAME: new_database_name
Renames the database with the name specified as new_database_name.
COLLATE collation_name
Specifies the collation for the database.
collation_name can be either a Windows collation name or a SQL collation name.

INTRODUCTION

If not specified, the database is assigned the collation of the instance of


SQL Server.
For more information about the Windows and SQL collation names,
see COLLATE (Transact-SQL).
<file_and_filegroup_options >::=
For more information, see ALTER DATABASE File and Filegroup Options (Transact-SQL).
<set_database_options >::=
For more information, see ALTER DATABASE SET Options (Transact-SQL).

CREATE Statements (Transact-SQL) used to create dierent database objects like table, keys, inde-

xes, constraints.

CREATE TABLE
[ database_name . [ schema_name ] . | schema_name . ] table_name
( { <column_definition> | <computed_column_definition>
| <column_set_definition> | [ <table_constraint> ] [ ,...n ] } )
[ ON { partition_scheme_name ( partition_column_name ) | filegroup
| "default" } ]
[ { TEXTIMAGE_ON { filegroup | "default" } ]
[ FILESTREAM_ON { partition_scheme_name | filegroup
| "default" } ]
[ WITH ( <table_option> [ ,...n ] ) ]
[ ; ]
<column_definition> ::=
column_name <data_type>
[ FILESTREAM ]
[ COLLATE collation_name ]
[ NULL | NOT NULL ]
[
[ CONSTRAINT constraint_name ] DEFAULT constant_expression ]
| [ IDENTITY [ ( seed ,increment ) ] [ NOT FOR REPLICATION ]
]
[ ROWGUIDCOL ] [ <column_constraint> [ ...n ] ]
[ SPARSE ]
<data type> ::=
[ type_schema_name . ] type_name
[ ( precision [ , scale ] | max |
[ { CONTENT | DOCUMENT } ] xml_schema_collection ) ]
<column_constraint> ::=
[ CONSTRAINT constraint_name ]
{
{ PRIMARY KEY | UNIQUE }
[ CLUSTERED | NONCLUSTERED ]
[
WITH FILLFACTOR = fillfactor
| WITH ( < index_option > [ , ...n ] )
]
[ ON { partition_scheme_name ( partition_column_name )
| filegroup | "default" } ]
| [ FOREIGN KEY ]
REFERENCES [ schema_name . ] referenced_table_name [ ( ref_column ) ]
[ ON DELETE { NO ACTION | CASCADE | SET NULL | SET DEFAULT } ]

0.2. INTRODUCTION TO SQL


[ ON UPDATE { NO ACTION | CASCADE | SET NULL | SET DEFAULT } ]
[ NOT FOR REPLICATION ]
| CHECK [ NOT FOR REPLICATION ] ( logical_expression )
}
<computed_column_definition> ::=
column_name AS computed_column_expression
[ PERSISTED [ NOT NULL ] ]
[
[ CONSTRAINT constraint_name ]
{ PRIMARY KEY | UNIQUE }
[ CLUSTERED | NONCLUSTERED ]
[
WITH FILLFACTOR = fillfactor
| WITH ( <index_option> [ , ...n ] )
]
| [ FOREIGN KEY ]
REFERENCES referenced_table_name [ ( ref_column ) ]
[ ON DELETE { NO ACTION | CASCADE } ]
[ ON UPDATE { NO ACTION } ]
[ NOT FOR REPLICATION ]
| CHECK [ NOT FOR REPLICATION ] ( logical_expression )
[ ON { partition_scheme_name ( partition_column_name )
| filegroup | "default" } ]
]
<column_set_definition> ::=
column_set_name XML COLUMN_SET FOR ALL_SPARSE_COLUMNS
< table_constraint > ::=
[ CONSTRAINT constraint_name ]
{
{ PRIMARY KEY | UNIQUE }
[ CLUSTERED | NONCLUSTERED ]
(column [ ASC | DESC ] [ ,...n ] )
[
WITH FILLFACTOR = fillfactor
|WITH ( <index_option> [ , ...n ] )
]
[ ON { partition_scheme_name (partition_column_name)
| filegroup | "default" } ]
| FOREIGN KEY
( column [ ,...n ] )
REFERENCES referenced_table_name [ ( ref_column [ ,...n ] ) ]
[ ON DELETE { NO ACTION | CASCADE | SET NULL | SET DEFAULT } ]
[ ON UPDATE { NO ACTION | CASCADE | SET NULL | SET DEFAULT } ]
[ NOT FOR REPLICATION ]
| CHECK [ NOT FOR REPLICATION ] ( logical_expression )
}
<table_option> ::=
{
DATA_COMPRESSION = { NONE | ROW | PAGE }
[ ON PARTITIONS ( { <partition_number_expression> | <range> }
[ , ...n ] ) ]

xi

xii

INTRODUCTION

}
<index_option> ::=
{
PAD_INDEX = { ON | OFF }
| FILLFACTOR = fillfactor
| IGNORE_DUP_KEY = { ON | OFF }
| STATISTICS_NORECOMPUTE = { ON | OFF }
| ALLOW_ROW_LOCKS = { ON | OFF}
| ALLOW_PAGE_LOCKS ={ ON | OFF}
| DATA_COMPRESSION = { NONE | ROW | PAGE }
[ ON PARTITIONS ( { <partition_number_expression> | <range> }
[ , ...n ] ) ]
}
<range> ::=
<partition_number_expression> TO <partition_number_expression>

CREATE INDEX (Transact-SQL) is used to create a new index on a table.


Create Relational Index
CREATE [ UNIQUE ] [ CLUSTERED | NONCLUSTERED ] INDEX index_name
ON <object> ( column [ ASC | DESC ] [ ,...n ] )
[ INCLUDE ( column_name [ ,...n ] ) ]
[ WHERE <filter_predicate> ]
[ WITH ( <relational_index_option> [ ,...n ] ) ]
[ ON { partition_scheme_name ( column_name )
| filegroup_name
| default
}
]
[ FILESTREAM_ON { filestream_filegroup_name | partition_scheme_name | "NULL" } ]
[ ; ]
<object> ::=
{
[ database_name. [ schema_name ] . | schema_name. ]
table_or_view_name
}
<relational_index_option> ::=
{
PAD_INDEX = { ON | OFF }
| FILLFACTOR = fillfactor
| SORT_IN_TEMPDB = { ON | OFF }
| IGNORE_DUP_KEY = { ON | OFF }
| STATISTICS_NORECOMPUTE = { ON | OFF }
| DROP_EXISTING = { ON | OFF }
| ONLINE = { ON | OFF }
| ALLOW_ROW_LOCKS = { ON | OFF }
| ALLOW_PAGE_LOCKS = { ON | OFF }
| MAXDOP = max_degree_of_parallelism
| DATA_COMPRESSION = { NONE | ROW | PAGE}
[ ON PARTITIONS ( { <partition_number_expression> | <range> }

0.2. INTRODUCTION TO SQL

xiii

[ , ...n ] ) ]
}
<filter_predicate> ::=
<conjunct> [ AND <conjunct> ]
<conjunct> ::=
<disjunct> | <comparison>
<disjunct> ::=
column_name IN (constant ,...n)
<comparison> ::=
column_name <comparison_op> constant
<comparison_op> ::=
{ IS | IS NOT | = | <> | != | > | >= | !> | < | <= | !< }
<range> ::=
<partition_number_expression> TO <partition_number_expression>

Backward Compatible Relational Index


Important The backward compatible relational index syntax structure will be removed in a future version of SQL
CREATE [ UNIQUE ] [ CLUSTERED | NONCLUSTERED ] INDEX index_name
ON <object> ( column_name [ ASC | DESC ] [ ,...n ] )
[ WITH <backward_compatible_index_option> [ ,...n ] ]
[ ON { filegroup_name | "default" } ]
<object> ::=
{
[ database_name. [ owner_name ] . | owner_name. ]
table_or_view_name
}
<backward_compatible_index_option> ::=
{
PAD_INDEX
| FILLFACTOR = fillfactor
| SORT_IN_TEMPDB
| IGNORE_DUP_KEY
| STATISTICS_NORECOMPUTE
| DROP_EXISTING
}

DROP TABLE (Transact-SQL) is used to delete a table from a database, given that the table exists.
Otherwise it will throw an error. You can also drop an index or other objects
DROP TABLE [ database_name . [ schema_name ] . | schema_name . ]
table_name [ ,...n ] [ ; ]

For more information check: MSDN DDL

INTRODUCTION

xiv

0.2.5 DML statements


The most important statements are CRUD: Create Retrieve Update Delete (Insert, Select, Update, Delete).
With only this 4 instructions we can achieve a lot of things in a database.

Insert is used to insert new entries in a table. The Insert statements can have many forms and variations.
[ WITH <common_table_expression> [ ,...n ] ]
INSERT
{
[ TOP ( expression ) [ PERCENT ] ]
[ INTO ]
{ <object> | rowset_function_limited
[ WITH ( <Table_Hint_Limited> [ ...n ] ) ]
}
{
[ ( column_list ) ]
[ <OUTPUT Clause> ]
{ VALUES ( { DEFAULT | NULL | expression } [ ,...n ] ) [ ,...n
| derived_table
| execute_statement
| <dml_table_source>
| DEFAULT VALUES
}
}
}
[;]

Examples:
INSERT INTO Table1(Column1,Column2, ..., ColumnN) VALUES(Value1,Value2, ..., ValueN)
OR
INSERT INTO Table1 VALUES(Value1,Value2, ..., ValueN)

Select is used to iterate throughout a bunch of data and selects data if a certain condition is met. We
can then specify a source using FROM and a condition using WHERE. We can also group data and apply
certain operations of aggregation. We'll discover more on this matter in the technical presentation.
[ WITH <common_table_expression>]
SELECT select_list [ INTO new_table ]
[ FROM table_source ] [ WHERE search_condition ]
[ GROUP BY group_by_expression ]
[ HAVING search_condition ]
[ ORDER BY order_expression [ ASC | DESC ] ]

Examples:
SELECT * FROM Table1;
OR
SELECT * FROM Table1 where CONDITION;

UPDATE (Transact-SQL) is used to update existing data from a table with other valid data, if data
constraints are met on that table.

0.2. INTRODUCTION TO SQL


[ WITH <common_table_expression> [...n] ]
UPDATE
[ TOP ( expression ) [ PERCENT ] ]
{ { table_alias | <object> | rowset_function_limited
[ WITH ( <Table_Hint_Limited> [ ...n ] ) ]
}
| @table_variable
}
SET
{ column_name = { expression | DEFAULT | NULL }
| { udt_column_name.{ { property_name = expression
| field_name = expression }
| method_name ( argument [ ,...n ] )
}
}
| column_name { .WRITE ( expression , @Offset , @Length ) }
| @variable = expression
| @variable = column = expression
| column_name { += | -= | *= | /= | %= | &= | ^= | |= } expression
| @variable { += | -= | *= | /= | %= | &= | ^= | |= } expression
| @variable = column { += | -= | *= | /= | %= | &= | ^= | |= } expression
} [ ,...n ]
[ <OUTPUT Clause> ]
[ FROM { <table_source> } [ ,...n ] ]
[ WHERE { <search_condition>
| { [ CURRENT OF
{ { [ GLOBAL ] cursor_name }
| cursor_variable_name
}
]
}
}
]
[ OPTION ( <query_hint> [ ,...n ] ) ]
[ ; ]
<object> ::=
{
[ server_name . database_name . schema_name .
| database_name .[ schema_name ] .
| schema_name .
]
table_or_view_name}

DELETE (Transact-SQL) will delete data from a table if a condition is met.


[ WITH <common_table_expression> [ ,...n ] ]
DELETE
[ TOP ( expression ) [ PERCENT ] ]
[ FROM ]
{ { table_alias
| <object>
| rowset_function_limited

xv

INTRODUCTION

xvi
[ WITH ( table_hint_limited [ ...n ] ) ] }
| @table_variable
}
[ <OUTPUT Clause> ]
[ FROM table_source [ ,...n ] ]
[ WHERE { <search_condition>
| { [ CURRENT OF
{ { [ GLOBAL ] cursor_name }
| cursor_variable_name
}
]
}
}
]
[ OPTION ( <Query Hint> [ ,...n ] ) ]
[; ]
<object> ::=
{
[ server_name.database_name.schema_name.
| database_name. [ schema_name ] .
| schema_name.
]
table_or_view_name
}

0.3 Introduction to C#
0.3.1 C# history
"C# is an elegant and type-safe object-oriented language that enables developers to build a variety of secure
and robust applications that run on the .NET Framework. You can use C# to create traditional Windows
client applications, XML Web services, distributed components, client-server applications, database applications, and much, much more. Visual C# provides an advanced code editor, convenient for the user interface
designers, an integrated debugger and many other tools to make it easier to develop applications based on
version 4.0 of the C# language and version 4.0 of the .NET Framework."
C# appeared in 1999, as a managed code compiler, which was rst known as Simple Managed Compiler,
then it was renamed Cool and in 2000 was announced that C# was born.
Since there were a lot of similarities between C/C++ and Java, some of the features evolved and separated,
but some of them remained similar and many of the features were borrowed along time.

0.3.2 Similarities to C++ and Java


Like C++ and Java, C# is a strongly typed language, which means that each object has to have a type and
this base type is the object class. Every class we dene in C# is derived from object which in terms of OOP
is a base class for all classes.
C# has 13 basic data types that are used throughout a program. Each of those 13 basic data types are
described in the below table 1.

0.3. INTRODUCTION TO C#
Data
byte
char
bool
sbyte
short
ushort
int
uint
oat
double
decimal
long
ulong

Type
1
2
1
1
2
2
4
4
4
8
12
8
8

Storage
Byte
Char
Boolean
SByte
Int16
UInt16
Int32
UInt32
Single
Double
Decimal
Int64
UInt64

xvii

.NET Type Range of Values


0 to 255
unicode character codes (0 to 65,535)
True or false
-128 to 127
-32,768 to 32767
0 to 65,535
2,147,483,648 to 1,147,483,647
0 to 4,294,967,295
1:51045 to 3:41038, 7 signicant gures
5:010324 to 1:810308, 15 signicant gures
for nancial applications
-91018 to 91018
0 to 1.81019
Tabela 1: Basic data types C# vs C++

0.3.3 Data types


Char data type is used to store integers from 0 to 65535, but it is commonly used to store characters

like 'a'...'z', 'A'...'Z', each char has a code(integer). E.g. 'A' has 65, just use alt key pressed and 065 from
numpad.

Integer data types all data type can hold the values from last column of table 1, but if you want to store
more than allowed values, you will receive an error.
Real data types are used to represent data with decimal point in several ways, some of them with greater

precision and some with smaller precision. Usually you need to use integer, when no decimal point is needed,
because it is faster, memory storage is bigger and you escape the problems of rounding and error with
precision.

0.3.4 Variables
The variables in C# are of 2 types: value types and the reference types. Between the 2 types there are major
dierences which will detail further.
Procedural programming languages that let you to create variables dynamically at run-time use two
dierent areas of Ram for holding variables;. the `stack` and the `heap`. The heap is basically all unallocated
memory.
The stack holds value type variables plus return addresses for functions. All numeric types, ints, oats
and doubles along with enums, chars, bools and structs are value types.
The heap hold variables created dynamically - known as reference variables and mainly instances of
classes or strings. These variables are stored in two places; there's a hidden pointer to the place in the heap
where the data is stored.
Another distinction between value and reference type is that a value type is derived from `System.ValueType`
while a reference type is derived from `System.Object`.
If you assign a value type variable to another then a direct copy of the value is made. But copying a
reference type variable just makes a copy of the reference to the variable and does not aect the variable
itself. This is like pointers in C and C++. You aren't copying what the pointer points to but making a copy
of the pointer itself.

0.3.5 Variable declaration


Before you can use a variable you have to declare it rst, there are many types of declarations:

INTRODUCTION

xviii
Escape Sequence
\0
\a
\b
\f
\n
\r
\h
\v
\'
\"
\\
\?

What does it mean?


null character
audible alert
backspace
form feed
new line
carriage return
horizontal tab
vertical tab
single quote
double quote
back slash
question mark

Tabela 2: Escape sequences


int x = 5;
or
var x = 5;
From compiler and CLR this is the same at run-time and IL code is the same.

Each variable declaration has to have a name or identier. The identier has a set of rules:
the rst character has to be a letter or underscore _;
it has to contain only letters, numbers and underscores;
you cannot use reserved words as variable names like in var or int.;

Caution note: C# is case sensitive. For example myVar and MyVar are totally dierent variables from
CLR perspective, to dierent memory location, values and maybe duration of existence.
If a variable is declared in a begin end block then the whole variable life will be between those brackets
and then the variable will be lost.
Also a variable can have dierent initialization and declaration moments:
int x; \\declaration
x = 5; \\ initialization
string s;
s = "Hello";
or
int x = 5; \\declaration and initialization
string s = "Hello";
which will both result in the same value stored in variable x

Constant are values which are declared once and used multiple types and will retain the value from their
creation and cannot be modied.
const int MY_CONSTANT_VAR= 5;
or
const string MY_HELLO_WORLD_STRING = "Hello World!!!";

Literal Constants are a series of special characters which are recognized as special chars and will need
to be escaped. This series of chars are part of string variables. A table with this gures is found in 2.

0.3. INTRODUCTION TO C#

xix

Enumerations are a way that we can use dierent static values through our application like a constant
value. For example, we can use the following enum.
enum Animal{
Cat = 0,
Dog = 1,
Horse = 2,
}

Enum type can be converted to int or long easily. As you can see it has integer values assigned. For more
related information please read chapter 3 from: Introduction to OOP C# and TAP course by Lucian Sasu.

0.3.6 C# statements
Many of the C# statements are similar to C++ or Java.

Expression statement is the simplest one; you write an expression followed by the semicolon.
x = 5;
i++;
x = 1;
i++;
s = s + "A";
x = 12 - (3 / 5) + 23;

Compound/block statements are a group of statements which is executed sequentially.


syntax: {
statement
statement
statement
}

Decision Statements like if and switch (or "case" in some languages like Pascal or Delphi) are very
common and widely.

if statement it is used for deciding if a condition is true. If the condition is true then we will execute a
code block for that, or if not, the else block will be executed.
syntax 1:
if ( condition ) true statement block;
else false statement block;
syntax 2:
if ( condition ) true statement block;
syntax 3:
if ( condition ) true statement block;
else if ( condition ) true statement block;
else false statement block;

xx

INTRODUCTION

ternary operator condition This operator does what the "if statement" does on the shorthand and it

is very used by programmers. Be aware that this makes the life very hard when you try to read the code
again.
int x = 5;
int y = 6;
int z = 7;
bool isGreater = x > y ? true : false; // false
isGreater = z > y ? true : false; // true

switch statement is like cascading "if statement" from the syntax 3 above. The code is more elegant and
easier to read.

switch( expression )
{
case constant1: statement1; break;
case constant2: statement2; break;
default: default_statement;
}

"For" repetitive statement is a code block used to iterate through a collection, array or a "IEnumerable"

collection. You will always know how many times the "for statement" will execute. Unless you use a continue
and break, the steps might not all execute.
for([initialisation];[condition];[action])
[statement_block]

"Foreach" repetitive statement is a code block used to iterate through an "IEnumerable" collection.

This will enumerate all the elements from your collection. This is the most used repetitive statement, I
think.
foreach(Type value in Collection)
[statement_block_to_execute]

"Do while" repetitive statement is a code block which will execute a set of statements and it will
continue only if a condition is met. Otherwise it will exit the code block.
do {
[statement_block_to_execute]
}
while(condition);

"While do" repetitive statement is a code block which will check a condition and will continue only
when the condition is true. Otherwise it will exit without executing the code block even once.
do {
[statement_block_to_execute]
}
while(condition);

0.3. INTRODUCTION TO C#

xxi

0.3.7 C# Namespaces
Namespaces are the same as "include" in C++ or "import" in Java. Usually, they are used to impor-

t/include another library from which we may want to use some functionality. Namespaces are a collection of
classes, interfaces and abstract classes which may be included in many projects. For example, we may want
to write a library in order to draw geometrical gures and we may use this library in a project like paint or
others.
We will take a look at all this in some future examples.
using System; \\ this is the same as import System.*;
\\Unlike in java we can include a library in full, not only parts of
\\it like in Java.
using System.Linq; \\ this is used for different lambda expressions,
\\but we will learn more in the future.

0.3.8 C# Classes
Class is the concept that we will use in course to construct all the features. A C# class is almost the same
as the classes in Java and/or C++. A class is a collection of properties, elds, methods, events and delegates.
using System;
namespace MyNamespace{
class MyClass {
private int myIntegerValue;
public int MyProperty{ get; set;}
public int CalculateSquare(){
return MyProperty * MyProperty;
}
}
}
\\ now we can use the class like this
MyClass obj = new MyClass();
obj.MyProperty = 5;
obj.CalculateSquare(); \\ this will be 25

0.3.9 C# Interfaces
Interface is another concept that we will use. The interface will be used to specify some behavior that

we will expose to the outside world. We can specify the series of methods, properties which we will have to
implement in the classes that we use that interface.
using System;
namespace MyNamespace{
interface MyInterface {

INTRODUCTION

xxii
int MyProperty{ get; set;}
int CalculateSquare();
}
class MyClass : MyInterface {
private int myIntegerValue;
public int MyProperty{ get; set;}
public int CalculateSquare(){
return MyProperty * MyProperty;
}
}
}
\\ now we can use the class like this
MyInterface obj = new MyClass();
obj.MyProperty = 5;
obj.CalculateSquare(); \\ this will be 25

0.3.10 C# Access Modiers


Access Modiers are a set of keywords which are used to describe how much an element is accessible
from the outside world. This set of elements can be used on classes, properties, elds, methods, events and
delegates.

public is the least restrictive. This means that the element is accessible from an outside package/namespace
and there are no restrictions.

internal means that the value is restricted to the classes from the current package that it's a part of.
protected internal means that the value is accessible from the descending classes in the same assembly.
protected means that this element will be accessed from the current class and any descending classes
which inherits this class.

private is the most restrictive. This means that nothing from outside the class can access it; not even
from a class that implements this class.

0.3.11 C# Other Modiers


abstract will be used to specify that a class is a base class for a hierarchy of classes. If this modier is
applied to a class, it will allow us to dene a series of methods, which may or may not have an implementation
that may be overridden in the inheriting classes.

async will specify that the element on which it is applied is asynchronous.


const is used to specify a constant value which will retain its value for the whole application lifetime and
it cannot be modied.

0.3. INTRODUCTION TO C#

xxiii

override will be used on a class which inherits an abstract class. This will be used on an existing method
which is marked as "abstract" or has the existing implementation in the base class.

partial is a new feature which is dierent from Java or C/C++. We can dene a class in multiple places.

At run-time the class will have all the functionality from all the places and it will be the same as the same
class in one le. This will allow us to extend a series of functionality from the existing libraries.

event can be used to declare an event which can be subscribed or unsubscribed to execute a function at a
specied time.

readonly is more or less like a constant, but it's value can be modied where it is declared or we can
modify it in the constructor.

sealed is the same as "nal" in Java. We will prevent from inheriting this class.
static means that this value will be available for all the classes of the same type. This can be sometimes
a bottleneck. Use it with care.

virtual is used to declare a method which can be overridden in the inheriting classes.

0.3.12 C# Properties
Properties are a shorthand form of "getter" and "setter" from Java. This is a very nice and elegant way
to access data in C#. The rst C# class may be used with validation on setter or on getter.
public class MyClassJavaStyle {
private string myName;
public string getMyName()
{
return myName;
}
public string setMyName(string myName)
{
return myName;
}
}
// C\# style
public class MyClassCSharpStyle {
private string myName;
public string MyName
{
get {
return myName;
}
set {
myName = value;
}
}

INTRODUCTION

xxiv
}
public class MyClassCSharpStyle2 {
public string MyName { get;set; }
}

0.3.13 C# Attributes
All attributes are derived from System.Attribute Class or it's descendants. We will use more of them together
with Entity Framework later. For more information read about: Attributes tutorial
// this atrribute can be applied on any kind of element:
//class, property, struct, etc
[AttributeUsage(AttributeTargets.All)]
public class MyAttribute : Attribute
{
}

0.3.14 C# Arrays and Collections


Arrays are a way to store more than one object of the same type. "Array" can contain items of multiple
types. Array can be represented as a single dimensional array, n-dimensional array or as a jagged array.

Simple Arrays can store multiple objects. This will have a known number of elements and will be
initialized to the required length before usage. Any kind of removal or addition of a new element it will have
to be recreated to the reect changes.
int[] lotoNumbers =
\\ this will create
\\length 6 with the
\\ lotoNumbers[0] =
\\ lotoNumbers[1] =
\\ lotoNumbers[2] =
\\ lotoNumbers[3] =
\\ lotoNumbers[4] =
\\ lotoNumbers[5] =

new int[] {1, 4, 5, 14, 32, 16};


an array of
following values
1;
4;
5;
14;
32;
16;

N-Dimensional Arrays can store elements on n levels that can be specied. For example, if N equals 2
then we will have a matrix. This has the same restriction as Single Dimensional Arrays or Simple Arrays.
You will have to know the length of the rows or columns.
int[,] matrix
matrix[0,0] =
matrix[0,1] =
matrix[0,2] =
matrix[1,0] =
matrix[1,1] =
matrix[1,2] =
matrix[2,0] =
matrix[2,1] =
matrix[2,2] =
\\ 1 2 3
\\ 4 5 6
\\ 7 8 9

= new int[3,3];
1;
2;
3;
4;
5;
6;
7;
8;
9;

0.4. REFERENCE MATERIALS

xxv

Jagged Arrays are a special kind of arrays that can be very dierent from each other. Each row can have
a dierent length. See the below example:
int[][] matrix = new int[3][];
matrix[0] = new int[3];
matrix[1] = new int[2];
matrix[2] = new int[1];
matrix[0,0] = 1;
matrix[0,1] = 2;
matrix[0,2] = 3;
matrix[1,0] = 4;
matrix[1,1] = 5;
matrix[2,0] = 7;
\\ 1 2 3
\\ 4 5
\\ 7

Collections are as an upgrade to Arrays. For example, an upgrade to an array was done by using List<>.

This will help us a lot in this course. All the functionalty of Entity Framework is based on this. A list can
be initialized and then lled up with data. We don't need to know it's length when we initialize it. Also,
when we will modify it, we will not be forced to create new instance.
using System;
using System.Collections.Generic;
using System.Linq;
...
List<int> list = new List<int>(); \\ new List<int>(){1,2,3};
list.Add(1); \\ 1, 2, 3, 1
list.RemoveAt(0); \\ 2, 3, 1
Console.WriteLine(list[2]); \\ 1
list[2] = 3; \\ 2, 3, 3

0.3.15 C# Generics
This is another improvement which came together with C# 3.0 and .net Framework 3.0. This helped us to
create classes which can duplicate the same functionality for multiple classes.
For example, we have 2 arrays: one with integers and one with decimals which do the same arithmetic
operations with the numbers.
List<int> ints = new List<int>{ 1, 2, 3};
int result = ints.Sum();
List<decimal> decimals = new List<decimal>{ 1.2M, 2.5M, 3.7M};
decimal result2 = decimals.Sum();

0.4 Reference materials


Introduction to OOP C#
Introduction to SQL
Sql 10h Course
DDL resources
DML resources
SQL online tool

xxvi
C# MSDN
History of C#
Value type vs reference type
Attributes C#
Attributes tutorial Arrays and Collections MSDN

INTRODUCTION

Partea I
Introducere In ASP.NET MVC

Capitolul 1
ASP.NET

1.1 Istorie
La inceput, a fost doar ASP clasic, care era un fel de limbaj de scriptare, foarte asemanator cu PHP. Acesta
era compus din VBScript si JScript. ASP folosea componente COM pentru a imbunatati functionalitatea
existenta. Doar ca functionalitatile oferite de COM aveau performante scazute si nu se scalau bine.
Asp.net a aparut odata cu prima versiune de Visual Studio in 16 Ianuarie 2002. Aceasta versiune avea suport
POO, care suporta mostenirea, polimorsmul si alte trasaturi ale POO. Aplicatia rezultata era formata dintrun set de DLL(librarii), care ne ajuta sa dezvoltam aplicatii robuste, care fac mult mai mult decat o simpla
randare a unui continut HTML.
ASP.NET a fost dezvoltatat mai departe, s-au adaugat o serie de trasaturi complexe. Printre aceste trasaturi
a aparut si ASP.Net MVC 1.0 in anul 2009. Printre trasaturi se puteau remarca:

Conceptul de MVC
separarea responsabilitatilor
rutare(routing)
unelte de randare a tagurilor html
unelte pentru facilitarea lucrului asincron(AJAX)
model binding

Aceste trasaturi au insemnat un pas urias pentru noul Web, de asemenea un mare pas pentru Microsoft.
Platforma construita este extensibila si poate dezvolta aplicatii de talie mare de tip enterprise. Majoritatea
componentelor aparute cu aceasta prima versiune, au fost extensibile. Printre trasaturile care nu au putut
 suportate din prima versiune, s-a numarat si Dependency Injection. Insa, dezvoltatorii au lasat o portita
pentru integrarea unor componente externe de IOC(Inversion of Control).
In urmatorul an a aparut ASP.NET MVC2. Aceasta versiune a venit cu mari imbunatatiri pentru o productivitate sporita si suportul mentenantei pentru proiecte de mari dimenisiuni. Printre trasaturi se numara:

Validarea atat pe client, cat si pe server bazat pe atribute


Suportul la partitionarea aplicatiilor mari prin introducerea zonelor(Areas)
generarea unor formulare bazat pe descrierea modelului
introducerea lambda expression pentru a specica campurile unui view

De asemenea au fost introduse alte trasaturi ale mediului de lucru pentru a imbunatati extensibilitatea:
Model Metadata Provider si ModelValidationProvider
Atribute si logica de validare
Sabloane de asare care suporta personalizare(Custom templates)

In anul 2013, a aparut MVC 3 cu o multime de update-uri pentru mediul de lucru, dar si pentru framework.
Printre imbunatatiri se numara: NuGet, IIS Express. De asemenea, aceste trasaturi au putut  folosite
3

CAPITOLUL 1. ASP.NET

impreuna cu platforma .net 4.0. Printre trasaturile care au fost incluse in aceasta versiune:

validarea pe model, fara a impacta codul html, simplu si elegant


validare pe server a modelului de pe client
managementul dependintelor la runtime

motorul Razor view

Filtre globale
noi tipuri de proiecte personalizate si pregatite pentru a suporta mai multe tipuri de aplicatii: cu
autenticare online cu formulare, aplicatii enterprise, servicii web.

MVC 4 a aparut la sfarsitul lui 2011. Aparitia sa a fost insotita de o serie de unelte care puteau  incluse
peste mediul de lucru VS. Trasaturile noi aparute sunt urmatoarele:

integrarea cu Entity Framework


generarea unor functionalitati CRUD, din modelul de date
proiecte si librarii NuGet jQuery, jQuery UI, modernizer imbunatatite
Entity Framework Code First este inclus pentru proiecte implicit
Suportul pentru HTML5 si CSS3 in mediul de lucru cat si o serie de unelte

1.2 What is MVC?


Modelul arhitectural Model-View-Controller face separarea aplicatiei in trei mari componente: model, view,
and controller. Prin acest model arhitectural, se ofera o alternativa a modelului de lucru ASP.net Web
Pages. Acest model este unul foarte simplu de inteles, testabil, integrat cu toate trasaturile de server deja
prezente in ASP.net, cum ar : paginile master, securitate. Librariile care contin acest framework sunt
prexate cu System.Web.MVC.

Sablonul MVC include urmatoarele componente:

Model-ul este alcatuit dintr-o serie de obiecte care implementeaza logica domeniului, cum se stocheaza
si cum se manipuleaza setul de date. De cele mai multe ori, cu ajutorul modelului se salveaza si se incarca
cu ajutorul modelului de date. De exemplu, un produs poate  incarcat din baza de date, se pot opera
schimbari asupra sa si apoi se pot salva modicarile facute in baza de date.
In aplicatiile mai mici, de obicei separarea nu se face foarte pronuntat in aceasta zona, dar e posibil sa mai
existe cateva nivele sub model care se ocupa de validare si logica aplicatiei. In acest caz aplicatia incarca
niste obiecte si le trimite direct la view, asa cum au fost ele incarcate si fara alte procesari suplimentare. In
aceasta situatie, dataset-ul devine modelul de date folosit.
Views sunt componentele care sunt asate catre utilizatorul aplicatiei(User Interface). De regula, asarea
acestuia este conditionat de modelul de date. Un exemplu ar  un view de modicare al unui produs, care
are o serie de elemente de html care sunt bazate pe starea actuala a obiectului.

1.2. WHAT IS MVC?

Controller-ul este componenta intermediaza si proceseaza interactiunea utilizatorului, face trac de informatii cu modelul, identica si selecteaza un view care sa il arate utilizatorului bazat pe o anumita logica.
In aplicatiile de tip MVC, componenta View doar aseaza informatii; componenta Controller se ocupa doar
cu manipularea si procesarea actiunilor utilizatorulu, iar modelul se ocupa cu stocarea si procesarea datelor.
De exemplu, controllerul primeste o cerere HTTP cu o serie de informatii in query string, acesta proceseaza
datele si face o cerere catre model, iar dupa ce primeste rezultatul intoarce un View cu rezultatul actiunii.

1.2.1 Separarea responsabilitatilor (Separations of concerns)


Sablonul arhitectural ne ajuta sa realizam aplicatii in care se separa diferitele aspect ala aplicatiei (logica
de introducere a datelor, reguli de validare, logica interna aplicatiei si modul cum se aseaza). In acelasi
timp, se realizeaza si cuplarea slaba(loose coupling) intre elementele mentionate. Dupa numele componentei
si destinatie se pot plasa elementele:
1. Logica de asare se plaseaza in view
2. Logica datelor de introdus se plaseaza in controller
3. Logica si regulile de business se vor plasa in model, care va pastra si garanta integritatea datelor
De asemenea, folosind acest pattern, se va putea concentra doar pe un aspect, de prezentare fara a face
functionalitatea din spate. Sau de asemenea se va putea face modelul si functionalitatea aferenta fara a 
nevoie de UI. Pentru cea de a doua abordare, vom putea suplini interfata cu teste unitare sau de integrare.
Cele doua abordari favorizeaza paralelizarea si impartinirea responsabilitatilor in echipa de dezvoltare intre
dezvoltatori si designeri. Iar la randul sau partea de model si logica poate  impartita intre mai multi
dezvoltatori, pe functionalitati, zone sau chiar testare.

Suportul pentru TDD(Test Driven Development) este asigurat de faptul ca o componenta poate 
total separate de celelalte. Putem testa separat modelul si interactiunea cu baza de date sau doar controllerele
cu procesarile de date.

1.2.2 Diferentele dintre ASP.Net si ASP.NET MVC


Avantajele aplicatiei de tip MVC Proiectul de tip ASP.NET MVC ofera urmatoarele avantaje:
Reduce complexitatea prin divizarea unitatii de lucru pe responsabilitati: model, controller si view.
Nu foloseste mecanismul de view state si stocarea acestuia in view. Favorizeaza controlul total asupra

aplicatiei si a comportamentului acesteia.

Are un singur controller, dispecerul care primeste toate cererile si in functie de parametrii ii redirecteaza

catre cel specilizat pentru tratare. Faciliteaza aplicatiile care au nevoie de o infrastructura de rutare.

Favorizeaza testarea si modul de lucru bazat pe testare(TDD).


Ajuta echipele mari sa lucreze in paralel si permite un control mai mare asupra comportamentului.

Avantajele aplicatiei de tip Web Forms Aplicatia de tip Web Forms ofera urmatoarele avantaje:
Suporta mentinerea starii peste HTTP. Acest mecanism de mentinere a starii este suportat de o multime

de evenimente pentru componentele de server oferite de framework.

Fiecare pagina are propriul ei controller, numit Page Controller sau page behind. Acesta contine codul

pentru evenimentele denite din acea pagina.

Pastreaza starea asata pe formularele de pe pagina, fapt care favorizeaza lucrul cu informatiile pre-

zentate.

Functioneaza foarte bine pentru echipe mici, compuse din dezvoltatori si designeri, care doresc sa

dezvolte rapid aplicatii(RAD)

In general, e mult mai usor din punct de vedere al complexitatii, datorita componentelor (Page, User

Control, Custom Control) care sunt integrate intre ele si necesita mult mai putin cod decat unele de
tip MVC.

CAPITOLUL 1. ASP.NET

1.3 Bazele ASP.NET


1.3.1 Structura proiectului

Figura 1.1: Structura proiectului


Pentru a incepe un nou proiect, vom folosi File -> New Project -> Visual C# -> Web Application MVC
4 va genera o structura de foldere si siere ca in gura 1.1.

Properties Acest director contine o serie de setari referitor la namespace, drepturi de auto, versiunea
aplicatiei si autorul acesteia care se for imbrica in libraria rezultata. Putem observa un exemplu mai jos.
using System . Reflection ; \\ librariile folosite in acest fisier
using System . Runtime . CompilerServices ;
using System . Runtime . InteropServices ;
[ assembly : AssemblyTitle ( " MvcApplication1 " ) ] \\ numele aplicatiei
[ assembly : AssemblyDescription ( " " ) ]
[ assembly : AssemblyConfiguration ( " " ) ]
[ assembly : AssemblyCompany ( " " ) ]
[ assembly : AssemblyProduct ( " MvcApplication1 " ) ] \\ numele fisierului dll
rezultat in urma procesului de compilare
[ assembly : AssemblyCopyright ( " Copyright 2014 " ) ]
[ assembly : AssemblyTrademark ( " " ) ]
[ assembly : AssemblyCulture ( " " ) ]
// Setting ComVisible to false makes the types in this assembly not visible

1.3. BAZELE ASP.NET

// to COM components . If you need to access a type in this assembly from


// COM , set the ComVisible attribute to true on that type .
[ assembly : ComVisible ( false ) ]
// The following GUID is for the ID of the typelib if this project is exposed
to COM
[ assembly : Guid ( " eac3abfb -9 dd4 -410 b -9 f68 -82 f528c94634 " ) ] \\ versiunea unica a
acestui proiect
// Version information for an assembly consists of the following four values :
//
//
Major Version
//
Minor Version
//
Build Number
//
Revision
//
// You can specify all the values or you can default the Revision and Build
Numbers
// by using the * as shown below :
[ assembly : AssemblyVersion ( " 1.0.0.0 " ) ] // informatii de versionare
[ assembly : AssemblyFileVersion ( " 1.0.0.0 " ) ]

App_Data contine o serie de siere, care vor  folosite in aplicatie, cum ar  acorduri de tip EULA,
imagini, etc. Toate aceste siere vor  accesibile pentru toata aplicatia.
App_Code poate contine o serie de siere cum ar  visual helpers sau Razor view helpers. Codul va 
compilat impreuna cu aplicatia si vor rezulta o serie de siere. Aceste siere vor ramane in zona de siere
temporare ale serverului de IIS. Acestea se vor putea folosi in aplicatie in views.
App_Start contine o serie de clase care separa responsabilitatile prezente in versiunile anterioare in

Global.asax. Dintre responsabilitatile care sunt mutate aici putem enumera:


Autorizarea si furnizorii de securitate(AuthCong) ne va ajuta in congurarea partii de securitate, e
ca este implicita sau explicita, interna sau externa.
Impachetare si prezentare(BundleCong) sierelor care se vor incarca in pagina cum ar  sierele de
tip javascript si CSS3. Mecanismul descris aici va  referit doar ca impachetare (bundle), dar are mult
mai multe functii decat cea declarata.
Filtrare(FilterCong) impacheteaza o serie de functionalitati care se refera la auditarea aplicatiei,
securitate si altele create de noi cu alte scopuri
RutareRouteCong se refera la mecanismele congurate predenite care vor  tratate de catre Front
Controller si vor  redirectate catre Controllerele specice.
WebApiWebApiCong se refera la mecanismele specice serviciilor de frontend care le-am putea folosi
in aplicatie.

Areas
Content , acest director contine resursele de tip imagine, css sau font care sunt folosite in aplicatia noastra.
Controllers contine o serie de controllere care sunt folosite in aplicatie. Toate Controllerele din aplicatie

sunt de forma *Controller, aceasta este o conventie de nume la nivelul frameworkului si sunt derivate din
Controller.
public class HomeController : System . Web . MVC . Controller
{

CAPITOLUL 1. ASP.NET

8
}

Filters contine o serie de clase cu functionalitati multiple de securitate, auditare sau alte functionalitati.
Dupa cum se poate observa, e derivat din System.Web.MVC.ActionFilterAttribute.
[ AttributeUsage ( AttributeTargets . Class | AttributeTargets . Method ,
AllowMultiple = false , Inherited = true ) ]
public sealed class InitializeSimpleMembershipAttribute :
ActionFilterAttribute
{
}

Images contine imaginile care vor  folosite ca logo sau imagini predenite pentru anumite parti ale
aplicatiei.

Models va contine o serie de model pentru aplicatia noastra.


Scripts contine o serie de siere javascript, coee script, jquery, etc.
Views Contine o serie de foldere printre care unul pentru ecare controller nou creat si un folder de Shared
cu o specicatie un pic mai speciala.

Fav.icon Este un sier care va  folosit de browser pentru a-l asa in tab langa numele aplicatiei.

Figura 1.2: fav.icon

Global.asax este sierul central al aplicatiilor web, e ca sunt aplicatii de tip web pages sau web forms
sau MVC. El contine o serie de evenimente cum ar :

Application_Start
Application_End
Application_Error
Session_Start
Session_End

Vom detalia mai mult aspectele legate de acest sier si functionalitatile aferente la partea practica.

Packages.cong este un sier specic pentru NuGet si contine informatii legate de pachetele instalate in

aplicatia noastra.

Web.cong o serie de congurari, conexiuni la baza de date.

1.4 References
History of MVC so far
History of ASP.Net
asp.net/mvc
ASP.NET MVC Overview

Capitolul 2
Entity Framework Code First

2.1 Ce este un ORM?


ORM sau Object-Relational Mapping este un tool care permite manipularea datelor prezente in baza

de date utilizand o serie de obiecte. Este o librarie sau un o colectie de librarii care este scrisa in limbajul
nativ, cel in care noi scriem codul. Libraria incapsuleaza codul necesar pentru a manipula datele, astfel incat
sa nu mai e nevoie sa folosim SQL, ci doar prin limbajul care il folosim.

Avantajele unui astfel de sistem:


DRY(Don't Repeat Yourself) scrii tot codul intr-un singur loc, il refolosesti, il rescrii si il mentii si

toate acestea se intampla intr-un singur loc.


O mare parte din functionalitate este oferita automat
de cele mai multe ori, te forteaza sa folosesti o arhitectura MVC
nu trebuie sa stii bine SQL
are in spate un set de proceduri si metode prin care face interogarea bazei de date
are o exibilitate mai mare
permite modicari mult mai mari asupra bazei de date
cuplare slaba intre module, mai ales intre baze de date si aplicatie
permite folosirea conceptelor de OOP

Dezavantajele unui astfel de sistem:

se poate invata nu foarte usor


este mai complex
trebuie integrat in solutia pe care lucrezi si trebuie congurat
este posibil ca performanta sa nu e aceeasi ca in cazul folosirii doar a SQL
abstractizeaza baza de date si nu prea ai idee de multe ori ce se intampla in spatele scenei

Exemple de astfel de librarii in C# si .net: NHibernate, Entity Framework, DataMapper, Linq To SQL,

etc.

CAPITOLUL 2. ENTITY FRAMEWORK CODE FIRST

10

2.2 Despre Entity Framework


2.3 Congurari
2.4 Modelul edmx
2.5 T4
2.6 Generare de clase
2.7 Comenzi
enable-migrations este folosita o singura data pentru a putea sa generam structura de code-rst. Aceasta
comanda va genera o serie de siere, care vor aparea in proiect in directorul Migrations.

Enable - Migrations [ - EnableAutomaticMigrations ] [[ - ProjectName ] < String >]


[ - Force ] [ < CommonParameters >]
-EnableAutomaticMigrations este folosit pentru a migra automat baza de date, la momentul la care

facem proiectul
-ProjectName <String> este folosit pentru a face modicare unui singur context dupa nume
-Force de cele mai multe ori suntem nevoiti sa fortam executia codului pe masina, chiar daca provoaca
pierderi de date.

add-migration va genera o serie de schimbari pe baza diferentelor dintre baza de date si clasele generate.
De asemenea va genera atat scripturi C#, cat si SQL care pot  interschimbate. Fisierele rezultate vor  de
asemenea puse in directorul Migrations.
Add - Migration [ - Name ] < String > [ - Force ]
[ - ProjectName < String >] [ - StartUpProjectName < String >]
[ - ConfigurationTypeName < String >] [ - ConnectionStringName < String >]
[ - IgnoreChanges ] [ < CommonParameters >]

-Name <String>: reprezinta numele care va  stocat pentru aceasta schimbare


-Force: va forta o regenerare a ultimei migrari
-ProjectName <String>: proiectul pentru care se face modicarea
-ConnectionStringName <String>: numele conexiunii la baza de date care va  folosit
mai sunt si alti parametrii, dar nu sunt asa importanti.

update-database va aplica toate schimbarile care sunt in asteptare si au fost generate printr-o comanda
anterioara add-migration.

Update - Database [ - SourceMigration < String >]


[ - TargetMigration < String >] [ - Script ] [ - Force ] [ - ProjectName < String >]
[ - StartUpProjectName < String >] [ - ConfigurationTypeName < String >]
[ - ConnectionStringName < String >] [ < CommonParameters >]
-SourceMigration <String>: vom putea specica aplicarea unui singur add-migration care sa e rulat
parametrii sunt similari comenzii add-migration

get-migrations ne ajuta sa obtinem toate migrarile care au fost deja aplicate la baza de date curenta.
Parametrii acestei comenzi sunt similari cu comenzile anterioare.

2.8. MODELE

2.8 Modele
2.9 Atribute
2.10 Referinte
EF Code First command

11

12

CAPITOLUL 2. ENTITY FRAMEWORK CODE FIRST

Capitolul 3
Code First Tutorial curs 1

Prima data, vom crea un nou proiect folosind Visual Studio 2012 sau 2013 prin urmatorii pasi:
File -> New Project ...
din nodul de Installed -> Templates -> Web -> Selectam ASP.NET MVC 4 Web Application si ii dam

un nume sugestiv Shop si apoi dam OK

Din urmatoarea fereastra selecta Internet Application, care va genera structura de proiect dorita si o

serie de siere care le vom folosi in continuare.

Urmatorul pas ar  sa rulam proiectul, iar rezultatul va  asat in navigatorul presetat pe calculator

(Chrome/Firefox/IE/Safari/etc).

adresa din browser va  una de genul http://localhost:XXXXX/ unde XXXXX poate  un port aleator

pe masina pe care rulam proiectul. 3.1

Figura 3.1: Prima asare a proiectului


Printre altele in proiectul de mai sus observam urmatoarele elemente specice unei aplicatii web:

titlu: "Shop Tutorial"


un meniu cu mai multe elemente Home, About, Contact
sectiune de prol care in functie de starea utilizatorului: autenticat sau nu va arata diferit.
o sectiune de titlu in cadru paginii: Home Page. Hello World!
o portiune de continut, deocamdata acesta va  de tip text.
13

14

CAPITOLUL 3. CODE FIRST TUTORIAL CURS 1

Dupa aceasta vom incepe sa adaugam functionalitate la acest proiect. Datorita faptului ca dorim sa
facem o aplicatie care este un magazin de produse, vom adauga functionalitate pentru a adauga si edita
produse. Acest procedeu va  facut prin Code First. Practic vom genera baza de date din cod C#, apoi
vom updata baza de date si apoi vom construi o serie de functionalitati de mvc pornind de la portiuni de
cod generate de tooluri Visual Studio.

3.1 Inregistrarea unui utilizator nou


Se poate face acest lucru din sectiunea de prol din dreapta sus prin intermediul legaturii "Register" 3.2.

Figura 3.2: Sectiunea de prol


Din pagina care se deschide, vom putea sa inregistram un nou utilizator in baza de date 3.3.

Figura 3.3: Inregistrarea unui utilizator


De indata ce vom apasa "Register" se vor petrece doua lucruri, o sa m redirectionati catre prima pagina
si aceasta o sa reprezinte o portiune de pagina in care vom avea numele utilizatorului si un buton de log o
pentru a parasi modul autenticat 3.4.
In spatele acestui tip de modicari avem o serie de tabele in baza de date, care au inregistrat aceste
aspecte 3.5 si 3.6.
Tabela UserProle 3.5 contine doar doua coloare: UserId si UserName.

3.2. BAZA DE DATE LOCALA VS BAZA DE DATE SQL SERVER

15

Figura 3.4: Prolul unui utilizator

Figura 3.5: Tabela UserProle

Figura 3.6: Tabela webpages_Membership


Iar tabele webpages_Membership 3.6 contine o serie de informatii cum ar  parola criptata, o cheie straina
pentru user, data la care s-a gresit ultima data parola, daca e contul blocat, detalii legate de conrmarea
contului si multe altele.

3.2 Baza de date locala vs Baza de date SQL Server


Pentru a putea dezvolta acest proiect avem la dispozitie, mai multe optiuni, printre care:
baza de date inclusa in proiect - respectiv un sier MDF, care este si optiunea implicita
baza de date externa - in cazul nostru SQL SERVER

< add name = " DefaultConnection " connectionString = " Data Source =( LocalDb ) \ v11 .0;
Initial Catalog = aspnet - Shop_20140313 -20140313180846;
Integrated Security = SSPI ;
AttachDBFilename =| DataDirectory |\ aspnet - Shop_20140313 -20140313180846. mdf "
providerName = " System . Data . SqlClient " / >

Conexiunea la baza de date inclusa in proiect, dupa cum putem observa, contine un nume de sier stocat
pe disc, cu extensia MDF. De asemenea are instructiuni ca sa e creata, doar dupa prima utilizare.
< add name = " DefaultConnection "
connectionString = " Server =.\ sqlserver ;
Database = Shop_20140313 ;
Trusted_Connection = True ; "
providerName = " System . Data . SqlClient " / >

CAPITOLUL 3. CODE FIRST TUTORIAL CURS 1

16

Conexiunea la SQL server contine printre altele, numele serverului: "Server=...", numele bazei de date
"Shop_20140313", faptul ca e o conexiune sigura catre baza de date si nu necesita user sau parola: "Trusted_Connection=True;"

3.3 Descrierea modelului de date curent


Modelul de date curent il gasim in directorul Models in clasa AccountModels. Aceasta clasa contine o serie
de modele, care sunt folosite in aplicatie, pentru inregistrarea unui utilizator, autenticare si autorizare.
public class UsersContext : DbContext \\ contextul de lucru al lui
Entity Framework
{
public UsersContext ()
: base ( " DefaultConnection " ) \\ conexiunea default la baza de
date , e exact numele conexiunii de mai sus
{
}
public DbSet < UserProfile > UserProfiles { get ; set ; } \\ un set de
utilizatori din baza de date , practic tabela de UserProfile
}
[ Table ( " UserProfile " ) ] \\ numele tabelei din baza de date
public class UserProfile \\ numele modelului din aplicatia web
{
\\ specificam faptul ca e cheie primara
[ Key ]
\\ specificam faptul ca aceasta cheie este
autoincrementata
\\ si baza de date va avea grija de generarea
acesteia
[ DatabaseGeneratedAttribute ( DatabaseGeneratedOption . Identity ) ]
public int UserId { get ; set ; }
public string UserName { get ; set ; }
}

3.4 Generarea primei migrari


Prima data pentru a putea salva un obiect de tip produs in baza de date, va trebui sa creem o tabela in baza
de date, in care sa stocam informatiile legate de produs.
O sa adaugam in directorul models o noua clasa numita Product.
[ Table ( " Product " ) ] \\ numele tabelei
public class Product
{
[ Key ] \\ cheie primara
[ DatabaseGeneratedAttribute ( DatabaseGeneratedOption . Identity ) ]
\\ autogenerata
public int ProductId { get ; set ; }
public string ProductName { get ; set ; } \\ numele produsului
public decimal Price { get ; set ; } \\ pret
}

3.4. GENERAREA PRIMEI MIGRARI

17

Al doilea lucru pe care trebuie sa il facem ar  sa facem contextul sa recunoasca aceasta noua tabela.
public class UsersContext : DbContext
{
public UsersContext ()
: base ( " DefaultConnection " )
{
}
public DbSet < UserProfile > UserProfiles { get ; set ; }
public DbSet < Product > Products { get ; set ; } \\ am adaugat un set de
produse
}

Al treilea lucru pe care trebuie sa il facem este sa activam migrarea Entity Framework pe proiect. Vom
folosi Nuget Package Manager Console 3.7, iar in partea de jos va aparea o fereastra, care va  folosita pentru
a rula o serie de comenzi.

Figura 3.7: Nuget Package Manager Console

Comanda enable-migration va  folosita pentru a genera directorul Migrations si un sier nou numit
conguration.

PM > enable - migrations


Checking if the context targets an existing database ...
Code First Migrations enabled for project ....
internal sealed class Configuration :
DbMigrationsConfiguration < MvcApplication4 . Models . UsersContext >
{
public Configuration ()
{
\\ faptul ca modificarile asupra bazei de
date nu se vor aplica automat ,
\\ ci se va astepta o comanda de tip
update - database
AutomaticMigrationsEnabled = false ;

CAPITOLUL 3. CODE FIRST TUTORIAL CURS 1

18
}

protected override void Seed ( Models . UsersContext context )


{
// This method will be called after migrating to the latest
version .
//
//
//
//
//
//
//
//
//
//

You can use the DbSet <T >. AddOrUpdate () helper extension method
to avoid creating duplicate seed data . E . g .
context . People . AddOrUpdate (
p = > p . FullName ,
new Person { FullName = " Andrew Peters " } ,
new Person { FullName = " Brice Lambson " } ,
new Person { FullName = " Rowan Miller " }
);

}
}

Comanda add-migration va  folosita pentru generarea primelor modicari asupra bazei de date. Vom
folosi Package Manager console ca si mai devreme si vom rula urmatoarea comanda.

PM > add - migration firstMigration


Scaffolding migration firstMigration .
The Designer Code for this migration file includes a snapshot of your current
Code First model . This snapshot is used to calculate the changes to your
model when you scaffold the next migration . If you make additional
changes to your model that you want to include in this migration , then
you can re - scaffold it by running Add - Migration
201403152013151 _firstMigration again .
public partial class firstMigration : DbMigration
{
// script de upgrade
public override void Up ()
{
CreateTable (
" dbo . UserProfile " ,
c = > new
{
UserId = c . Int ( nullable : false , identity : true ) ,
UserName = c . String () ,
})
. PrimaryKey ( t = > t . UserId ) ;
CreateTable (
" dbo . Product " ,
c = > new
{
ProductId = c . Int ( nullable : false , identity : true ) ,
ProductName = c . String () ,
Price = c . Decimal ( nullable : false , precision : 18 ,
scale : 2) ,

3.5. ADAUGAREA FUNCTIONALITATII MVC

19

})
. PrimaryKey ( t = > t . ProductId ) ;
}
// script de downgrade
public override void Down ()
{
DropTable ( " dbo . Product " ) ;
DropTable ( " dbo . UserProfile " ) ;
}
}

Acum suntem in postura de a putea aplica toate schimbarile noastre pe baza de date prin rularea din
Package Manager console a comenzii: Update-database.
PM > Update - database
Specify the - Verbose flag to view the SQL statements being applied to the
target database .
No pending code - based migrations .
Running Seed method .

Daca ne vom uita in baze de date, vom putea observa aparitia unei noi tabele numita "Product".

3.5 Adaugarea functionalitatii MVC


Visual Studio are un mecanism numit scaolding care ne va genera pentru un controller si un model o serie
de functionalitati predenite, pe care noi le vom extinde in proiectul nostru.
Pentru a efectua aceste schimbari vom da click dreapta pe Controllers -> Add Controller
Dupa apasarea butonului OK, vom putea observa ca a aparut un nou controller numit Product Controller,
un folder numit Product in Views, care contine 4 siere de View, pe care le vom detalia ulterior.

3.6 Primul produs adaugat


Pentru a verica functionalitatea tocmai adaugata, va trebui sa rulam proiectul din nou. Apoi sa modicam
url-ul din http://localhost:XXXXX/ in http://localhost:XXXXX/Product/Index

20

CAPITOLUL 3. CODE FIRST TUTORIAL CURS 1

Figura 3.8: Adaugarea unui controller

Figura 3.9: Adaugarea unui controller bazat pe un context EF si model

3.6. PRIMUL PRODUS ADAUGAT

Figura 3.10: Asarea listei de produse

Figura 3.11: Adaugarea unui nou produs

21

22

CAPITOLUL 3. CODE FIRST TUTORIAL CURS 1

Figura 3.12: Adaugarea unui nou produs

Figura 3.13: Lista cu produsul nou adaugat

Potrebbero piacerti anche