Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
NET MVC
Radu Florescu
ii
Cuprins
Introduction
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
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
Ce este un ORM? . . . . .
Despre Entity Framework
Congurari . . . . . . . .
Modelul edmx . . . . . . .
T4 . . . . . . . . . . . . .
Generare de clase . . . . .
Comenzi . . . . . . . . . .
Modele . . . . . . . . . . .
Atribute . . . . . . . . . .
Referinte . . . . . . . . . .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
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.
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.
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.
ix
INTRODUCTION
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 } ]
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>
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>
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 ] [ ; ]
INTRODUCTION
xiv
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.
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. 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
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.
INTRODUCTION
xviii
Escape Sequence
\0
\a
\b
\f
\n
\r
\h
\v
\'
\"
\\
\?
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;
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
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. 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
{
}
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] =
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;
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();
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:
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:
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:
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.
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.
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.
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.
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
Fiecare pagina are propriul ei controller, numit Page Controller sau page behind. Acesta contine codul
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
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
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
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
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.
Fav.icon Este un sier care va folosit de browser pentru a-l asa in tab langa numele aplicatiei.
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.
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
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.
Exemple de astfel de librarii in C# si .net: NHibernate, Entity Framework, DataMapper, Linq To SQL,
etc.
10
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 >]
update-database va aplica toate schimbarile care sunt in asteptare si au fost generate printr-o comanda
anterioara 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 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
Din urmatoarea fereastra selecta Internet Application, care va genera structura de proiect dorita si o
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
14
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.
15
< 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 " / >
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;"
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.
Comanda enable-migration va folosita pentru a genera directorul Migrations si un sier nou numit
conguration.
18
}
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.
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".
20
21
22