HowToAspNetMVC

48

description

HowToAspNetMVC

Transcript of HowToAspNetMVC

Page 1: HowToAspNetMVC

Cum sa construiesti o aplicatie ASP.NET MVC

Radu Florescu

15 martie 2014© Radu Florescu

All Rights Reserved

Page 2: HowToAspNetMVC

ii

Page 3: HowToAspNetMVC

Cuprins

Introduction vii0.1 Introduction to OOP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . vii

0.1.1 What is Object Oriented Programming? . . . . . . . . . . . . . . . . . . . . . . . . . . vii

0.1.2 OOP Keywords . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . vii

0.2 Introduction to SQL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . viii

0.2.1 What is SQL? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . viii

0.2.2 SQL dictionary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . viii

0.2.3 DML vs DDL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ix

0.2.4 DDL statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ix

0.2.5 DML statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xiv

0.3 Introduction to C# . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xvi

0.3.1 C# history . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xvi

0.3.2 Similarities to C++ and Java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xvi

0.3.3 Data types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xvii

0.3.4 Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xvii

0.3.5 Variable declaration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xvii

0.3.6 C# statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xix

0.3.7 C# Namespaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxi

0.3.8 C# Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxi

0.3.9 C# Interfaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxi

0.3.10 C# Access Modi�ers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxii

0.3.11 C# Other Modi�ers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxii

0.3.12 C# Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxiii

0.3.13 C# Attributes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxiv

0.3.14 C# Arrays and Collections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxiv

0.3.15 C# Generics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxv

0.4 Reference materials . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxv

I Introducere In ASP.NET MVC 1

1 ASP.NET 31.1 Istorie . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3

1.2 What is MVC? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4

1.2.1 Separarea responsabilitatilor (Separations of concerns) . . . . . . . . . . . . . . . . . . 5

1.2.2 Diferentele dintre ASP.Net si ASP.NET MVC . . . . . . . . . . . . . . . . . . . . . . . 5

1.3 Bazele ASP.NET . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6

1.3.1 Structura proiectului . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6

1.4 References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8

iii

Page 4: HowToAspNetMVC

iv CUPRINS

2 Entity Framework Code First 92.1 Ce este un ORM? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92.2 Despre Entity Framework . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102.3 Con�gurari . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102.4 Modelul edmx . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102.5 T4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102.6 Generare de clase . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102.7 Comenzi . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102.8 Modele . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112.9 Atribute . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112.10 Referinte . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11

3 Code First Tutorial curs 1 133.1 Inregistrarea unui utilizator nou . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143.2 Baza de date locala vs Baza de date SQL Server . . . . . . . . . . . . . . . . . . . . . . . . . 153.3 Descrierea modelului de date curent . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163.4 Generarea primei migrari . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163.5 Adaugarea functionalitatii MVC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 193.6 Primul produs adaugat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19

Page 5: HowToAspNetMVC

Prefata

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

v

Page 6: HowToAspNetMVC

vi CUPRINS

Page 7: HowToAspNetMVC

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 andthen we process that data into an output data that will be sent out. This information from the output willbe 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 ofduplicate code, which was both hard to maintain and harder to know and modify accordingly. First timethere were functions and procedures, which extracted some of the existing code in separate portion of spacewhich was available to the whole program. The expected outcome was a code which was lighter, easier tounderstand and to maintain, but still this wasn't enough. There had to be a procedure, that given a requiredamount 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 func-tions which manipulated it and it's name is "CLASS". And our code contained one or more classes whichprocessed 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 appliedto the data. An object can be a representation of a real life entity, like a car.

Class. A de�nition/speci�cation of an object, an it is used to de�ne a set of properties and methods forall the object that are from a class. The short form for this would be that: An Object is an instance of aclass.

Encapsulation. The process of gather a set of properties and methods in one class which will provide adesired output. This hides certain part of our code from the outside world. This is also part of the blackbox concept, together with Interface.

Interface. A set of methods and properties which are exposed to the outside of the class. All methodsde�ned 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 theoutside world we are only seeing the commands which allow us to call the elevator and to command it to goto a certain �oor (which is the interface and allows us to access certain methods of the elevator). Also, wehave certain parts hidden like the mechanisms to lift or to lower the elevator or the electronic componentsfor buttons which we don't know how they are implemented.

vii

Page 8: HowToAspNetMVC

viii INTRODUCTION

Abstraction. Refers to data, that we only want to represent as pattern of a class. For example an abstractclass can be a class which represents an animal and all animals eat. This means that an abstract class canidealize 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 ofa Fruit, but in particular an Apple has a di�erent taste, color and aspect which are di�erent from an Orange.

Polymorphism. Refers to the fact that in a hierarchy of classes, those classes are derived from a baseclass. For example, Animal class has a Gira�e class and an Elephant class. Those child classes will bothhave an implementation of "EatFood()". When we will use an instance of one of them, we will only knowthe existence of EatFood Method and we will execute it either from the Elephant class or the Gira�e class.Also, any method which inherits some methods from the parent may choose to use that functionality, extendor 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 di�erent types.

Table. A collection of entries of same type. A table consists of many columns, which may or not be of thesame type.

Index. A collection of di�erent 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, manyto one and many to many. The last one uses one extra table which will have a many to one relation withthe 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 speci�ed 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 pointsto a PRIMARY KEY from another table.

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

Page 9: HowToAspNetMVC

0.2. INTRODUCTION TO SQL ix

0.2.3 DML vs DDL

DDL stands for Data De�nition Language, meaning a series of commands and instructions that will help usde�ne 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 seriesof operations known as CRUD (Create, Retrieve, Update, Delete). It can have more other instructions, butwe 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> ::=

Argumentsdatabase_name: Is the name of the database to be modified.MODIFY NAME: new_database_nameRenames the database with the name specified as new_database_name.COLLATE collation_nameSpecifies the collation for the database.collation_name can be either a Windows collation name or a SQL collation name.

Page 10: HowToAspNetMVC

x INTRODUCTION

If not specified, the database is assigned the collation of the instance ofSQL 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 di�erent 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 } ]

Page 11: HowToAspNetMVC

0.2. INTRODUCTION TO SQL xi

[ 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 ] ) ]

Page 12: HowToAspNetMVC

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 IndexCREATE [ 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> }

Page 13: HowToAspNetMVC

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 IndexImportant The backward compatible relational index syntax structure will be removed in a future version of SQL Server. Avoid using this syntax structure in new development work, and plan to modify applications that currently use the feature. Use the syntax structure specified in <relational_index_option> instead.

CREATE [ UNIQUE ] [ CLUSTERED | NONCLUSTERED ] INDEX index_nameON <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

Page 14: HowToAspNetMVC

xiv INTRODUCTION

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)ORINSERT 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. Wecan then specify a source using FROM and a condition using WHERE. We can also group data and applycertain 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;ORSELECT * FROM Table1 where CONDITION;

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

Page 15: HowToAspNetMVC

0.2. INTRODUCTION TO SQL xv

[ 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

Page 16: HowToAspNetMVC

xvi INTRODUCTION

[ 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 secureand robust applications that run on the .NET Framework. You can use C# to create traditional Windowsclient applications, XML Web services, distributed components, client-server applications, database applica-tions, and much, much more. Visual C# provides an advanced code editor, convenient for the user interfacedesigners, an integrated debugger and many other tools to make it easier to develop applications based onversion 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 andthis base type is the object class. Every class we de�ne in C# is derived from object which in terms of OOPis 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 aredescribed in the below table 1.

Page 17: HowToAspNetMVC

0.3. INTRODUCTION TO C# xvii

Data Type Storage .NET Type Range of Valuesbyte 1 Byte 0 to 255char 2 Char unicode character codes (0 to 65,535)bool 1 Boolean True or falsesbyte 1 SByte -128 to 127short 2 Int16 -32,768 to 32767ushort 2 UInt16 0 to 65,535int 4 Int32 2,147,483,648 to 1,147,483,647uint 4 UInt32 0 to 4,294,967,295�oat 4 Single 1:51045 to 3:41038, 7 signi�cant �guresdouble 8 Double 5:010324 to 1:810308, 15 signi�cant �guresdecimal 12 Decimal for �nancial applicationslong 8 Int64 -91018 to 91018ulong 8 UInt64 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 characterslike 'a'...'z', 'A'...'Z', each char has a code(integer). E.g. 'A' has 65, just use alt key pressed and 065 fromnumpad.

Integer data types all data type can hold the values from last column of table 1, but if you want to storemore 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 greaterprecision 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 withprecision.

0.3.4 Variables

The variables in C# are of 2 types: value types and the reference types. Between the 2 types there are majordi�erences which will detail further.

Procedural programming languages that let you to create variables dynamically at run-time use twodi�erent areas of Ram for holding variables;. the `stack` and the `heap`. The heap is basically all unallocatedmemory.

The stack holds value type variables plus return addresses for functions. All numeric types, ints, �oatsand doubles along with enums, chars, bools and structs are value types.

The heap hold variables created dynamically - known as reference variables and mainly instances ofclasses or strings. These variables are stored in two places; there's a hidden pointer to the place in the heapwhere 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 areference type variable just makes a copy of the reference to the variable and does not a�ect the variableitself. This is like pointers in C and C++. You aren't copying what the pointer points to but making a copyof 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:

Page 18: HowToAspNetMVC

xviii INTRODUCTION

Escape Sequence What does it mean?\0 null character\a audible alert\b backspace\f form feed\n new line\r carriage return\h horizontal tab\v vertical tab\' single quote\" double quote\\ back slash\? question mark

Tabela 2: Escape sequences

int x = 5;orvar 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 identi�er. The identi�er 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 di�erent variables fromCLR perspective, to di�erent 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 bracketsand then the variable will be lost.

Also a variable can have di�erent initialization and declaration moments:

int x; \\declarationx = 5; \\ initializationstring s;s = "Hello";or

int x = 5; \\declaration and initializationstring 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 theircreation and cannot be modi�ed.

const int MY_CONSTANT_VAR= 5;orconst string MY_HELLO_WORLD_STRING = "Hello World!!!";

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

Page 19: HowToAspNetMVC

0.3. INTRODUCTION TO C# xix

Enumerations are a way that we can use di�erent static values through our application like a constantvalue. 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 morerelated 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: {statementstatementstatement}

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

if statement it is used for deciding if a condition is true. If the condition is true then we will execute acode 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;

Page 20: HowToAspNetMVC

xx INTRODUCTION

ternary operator condition This operator does what the "if statement" does on the shorthand and itis very used by programmers. Be aware that this makes the life very hard when you try to read the codeagain.

int x = 5;int y = 6;int z = 7;bool isGreater = x > y ? true : false; // falseisGreater = z > y ? true : false; // true

switch statement is like cascading "if statement" from the syntax 3 above. The code is more elegant andeasier 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 continueand 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, Ithink.

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 willcontinue 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 onlywhen the condition is true. Otherwise it will exit without executing the code block even once.

do {[statement_block_to_execute]}while(condition);

Page 21: HowToAspNetMVC

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 ofclasses, interfaces and abstract classes which may be included in many projects. For example, we may wantto write a library in order to draw geometrical �gures and we may use this library in a project like paint orothers.

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 sameas 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 thatwe will expose to the outside world. We can specify the series of methods, properties which we will have toimplement in the classes that we use that interface.

using System;

namespace MyNamespace{

interface MyInterface {

Page 22: HowToAspNetMVC

xxii INTRODUCTION

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 Modi�ers

Access Modi�ers are a set of keywords which are used to describe how much an element is accessiblefrom the outside world. This set of elements can be used on classes, properties, �elds, methods, events anddelegates.

public is the least restrictive. This means that the element is accessible from an outside package/namespaceand 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 classeswhich inherits this class.

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

0.3.11 C# Other Modi�ers

abstract will be used to specify that a class is a base class for a hierarchy of classes. If this modi�er isapplied to a class, it will allow us to de�ne a series of methods, which may or may not have an implementationthat 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 andit cannot be modi�ed.

Page 23: HowToAspNetMVC

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 methodwhich is marked as "abstract" or has the existing implementation in the base class.

partial is a new feature which is di�erent from Java or C/C++. We can de�ne 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 sameclass 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 aspeci�ed time.

readonly is more or less like a constant, but it's value can be modi�ed where it is declared or we canmodify 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 sometimesa 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 wayto 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;

}}

Page 24: HowToAspNetMVC

xxiv INTRODUCTION

}

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 togetherwith 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 multipletypes. 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 beinitialized to the required length before usage. Any kind of removal or addition of a new element it will haveto be recreated to the re�ect changes.

int[] lotoNumbers = new int[] {1, 4, 5, 14, 32, 16};\\ this will create an array of\\length 6 with the following values\\ lotoNumbers[0] = 1;\\ lotoNumbers[1] = 4;\\ lotoNumbers[2] = 5;\\ lotoNumbers[3] = 14;\\ lotoNumbers[4] = 32;\\ lotoNumbers[5] = 16;

N-Dimensional Arrays can store elements on n levels that can be speci�ed. For example, if N equals 2then 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 = new int[3,3];matrix[0,0] = 1;matrix[0,1] = 2;matrix[0,2] = 3;matrix[1,0] = 4;matrix[1,1] = 5;matrix[1,2] = 6;matrix[2,0] = 7;matrix[2,1] = 8;matrix[2,2] = 9;\\ 1 2 3\\ 4 5 6\\ 7 8 9

Page 25: HowToAspNetMVC

0.4. REFERENCE MATERIALS xxv

Jagged Arrays are a special kind of arrays that can be very di�erent from each other. Each row can havea di�erent 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 canbe 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, 1list.RemoveAt(0); \\ 2, 3, 1Console.WriteLine(list[2]); \\ 1list[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 tocreate 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 arithmeticoperations 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 SQLSql 10h CourseDDL resourcesDML resourcesSQL online tool

Page 27: HowToAspNetMVC

Partea I

Introducere In ASP.NET MVC

1

Page 28: HowToAspNetMVC
Page 29: HowToAspNetMVC

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. Acestaera compus din VBScript si JScript. ASP folosea componente COM pentru a imbunatati functionalitateaexistenta. 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 suportPOO, care suporta mostenirea, polimor�smul si alte trasaturi ale POO. Aplicatia rezultata era formata dintr-un set de DLL(librarii), care ne ajuta sa dezvoltam aplicatii robuste, care fac mult mai mult decat o simplarandare a unui continut HTML.ASP.NET a fost dezvoltatat mai departe, s-au adaugat o serie de trasaturi complexe. Printre aceste trasaturia 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. Majoritateacomponentelor 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 portitapentru 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 produc-tivitate 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 speci�ca 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 a�sare 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

Page 30: HowToAspNetMVC

4 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: cuautenti�care 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 � inclusepeste 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 WebPages. Acest model este unul foarte simplu de inteles, testabil, integrat cu toate trasaturile de server dejaprezente in ASP.net, cum ar �: paginile master, securitate. Librariile care contin acest framework suntpre�xate cu System.Web.MVC.

Sablonul MVC include urmatoarele componente:

Model-ul este alcatuit dintr-o serie de obiecte care implementeaza logica domeniului, cum se stocheazasi cum se manipuleaza setul de date. De cele mai multe ori, cu ajutorul modelului se salveaza si se incarcacu ajutorul modelului de date. De exemplu, un produs poate � incarcat din baza de date, se pot operaschimbari asupra sa si apoi se pot salva modi�carile facute in baza de date.In aplicatiile mai mici, de obicei separarea nu se face foarte pronuntat in aceasta zona, dar e posibil sa maiexiste cateva nivele sub model care se ocupa de validare si logica aplicatiei. In acest caz aplicatia incarcaniste obiecte si le trimite direct la view, asa cum au fost ele incarcate si fara alte procesari suplimentare. Inaceasta situatie, dataset-ul devine modelul de date folosit.

Views sunt componentele care sunt a�sate catre utilizatorul aplicatiei(User Interface). De regula, a�sareaacestuia este conditionat de modelul de date. Un exemplu ar � un view de modi�care al unui produs, careare o serie de elemente de html care sunt bazate pe starea actuala a obiectului.

Page 31: HowToAspNetMVC

1.2. WHAT IS MVC? 5

Controller-ul este componenta intermediaza si proceseaza interactiunea utilizatorului, face tra�c de in-formatii cu modelul, identi�ca si selecteaza un view care sa il arate utilizatorului bazat pe o anumita logica.In aplicatiile de tip MVC, componenta View doar a�seaza informatii; componenta Controller se ocupa doarcu 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 proceseazadatele 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 (logicade introducere a datelor, reguli de validare, logica interna aplicatiei si modul cum se a�seaza). In acelasitimp, se realizeaza si cuplarea slaba(loose coupling) intre elementele mentionate. Dupa numele componenteisi destinatie se pot plasa elementele:

1. Logica de a�sare 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 facefunctionalitatea 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 intredezvoltatori si designeri. Iar la randul sau partea de model si logica poate � impartita intre mai multidezvoltatori, 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 controllerelecu 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 asupraaplicatiei si a comportamentului acesteia.

� Are un singur controller, dispecerul care primeste toate cererile si in functie de parametrii ii redirecteazacatre 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 multimede evenimente pentru componentele de server oferite de framework.

� Fiecare pagina are propriul ei controller, numit Page Controller sau page behind. Acesta contine codulpentru evenimentele de�nite din acea pagina.

� Pastreaza starea a�sata 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 sadezvolte rapid aplicatii(RAD)

� In general, e mult mai usor din punct de vedere al complexitatii, datorita componentelor (Page, UserControl, Custom Control) care sunt integrate intre ele si necesita mult mai putin cod decat unele detip MVC.

Page 32: HowToAspNetMVC

6 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 MVC4 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, versiuneaaplicatiei si autorul acesteia care se for imbrica in libraria rezultata. Putem observa un exemplu mai jos.

using System.Reflection; \\ librariile folosite in acest fisierusing 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

Page 33: HowToAspNetMVC

1.3. BAZELE ASP.NET 7

// 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 exposedto COM

[assembly: Guid("eac3abfb -9dd4 -410b-9f68 -82 f528c94634")] \\ versiunea unica aacestui 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 �sieretemporare 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 inGlobal.asax. Dintre responsabilitatile care sunt mutate aici putem enumera:

� Autorizarea si furnizorii de securitate(AuthCon�g) ne va ajuta in con�gurarea partii de securitate, �eca este implicita sau explicita, interna sau externa.

� Impachetare si prezentare(BundleCon�g) �sierelor care se vor incarca in pagina cum ar � �sierele detip javascript si CSS3. Mecanismul descris aici va � referit doar ca impachetare (bundle), dar are multmai multe functii decat cea declarata.

� Filtrare(FilterCon�g) impacheteaza o serie de functionalitati care se refera la auditarea aplicatiei,securitate si altele create de noi cu alte scopuri

� RutareRouteCon�g se refera la mecanismele con�gurate prede�nite care vor � tratate de catre FrontController si vor � redirectate catre Controllerele speci�ce.

� WebApiWebApiCon�g se refera la mecanismele speci�ce serviciilor de frontend care le-am putea folosiin 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 aplicatiesunt de forma *Controller, aceasta este o conventie de nume la nivelul frameworkului si sunt derivate dinController.

public class HomeController : System.Web.MVC.Controller{

Page 34: HowToAspNetMVC

8 CAPITOLUL 1. ASP.NET

}

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 prede�nite pentru anumite parti aleaplicatiei.

Models va contine o serie de model pentru aplicatia noastra.

Scripts contine o serie de �siere javascript, co�ee script, jquery, etc.

Views Contine o serie de foldere printre care unul pentru �ecare controller nou creat si un folder de Sharedcu o speci�catie un pic mai speciala.

Fav.icon Este un �sier care va � folosit de browser pentru a-l a�sa 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 formssau 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.con�g este un �sier speci�c pentru NuGet si contine informatii legate de pachetele instalate inaplicatia noastra.

Web.con�g o serie de con�gurari, conexiuni la baza de date.

1.4 References

History of MVC so farHistory of ASP.Netasp.net/mvcASP.NET MVC Overview

Page 35: HowToAspNetMVC

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 bazade date utilizand o serie de obiecte. Este o librarie sau un o colectie de librarii care este scrisa in limbajulnativ, cel in care noi scriem codul. Libraria incapsuleaza codul necesar pentru a manipula datele, astfel incatsa 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 sitoate 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 modi�cari 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 con�gurat� 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.

9

Page 36: HowToAspNetMVC

10 CAPITOLUL 2. ENTITY FRAMEWORK CODE FIRST

2.2 Despre Entity Framework

2.3 Con�gurari

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. Aceastacomanda 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 carefacem proiectul

-ProjectName <String> este folosit pentru a face modi�care unui singur context dupa nume� -Force de cele mai multe ori suntem nevoiti sa fortam executia codului pe masina, chiar daca provoacapierderi 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 � deasemenea 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 modi�carea� -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 comandaanterioara add-migration.

Update -Database [-SourceMigration <String >][-TargetMigration <String >] [-Script] [-Force] [-ProjectName <String >][-StartUpProjectName <String >] [-ConfigurationTypeName <String >][-ConnectionStringName <String >] [<CommonParameters >]

� -SourceMigration <String>: vom putea speci�ca 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.

Page 37: HowToAspNetMVC

2.8. MODELE 11

2.8 Modele

2.9 Atribute

2.10 Referinte

EF Code First command

Page 38: HowToAspNetMVC

12 CAPITOLUL 2. ENTITY FRAMEWORK CODE FIRST

Page 39: HowToAspNetMVC

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 damun nume sugestiv Shop si apoi dam OK

� Din urmatoarea fereastra selecta Internet Application, care va genera structura de proiect dorita si oserie de �siere care le vom folosi in continuare.

� Urmatorul pas ar � sa rulam proiectul, iar rezultatul va � a�sat 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 aleatorpe masina pe care rulam proiectul. 3.1

Figura 3.1: Prima a�sare a proiectului

Printre altele in proiectul de mai sus observam urmatoarele elemente speci�ce unei aplicatii web:

� titlu: "Shop Tutorial"� un meniu cu mai multe elemente Home, About, Contact� sectiune de pro�l care in functie de starea utilizatorului: autenti�cat 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

Page 40: HowToAspNetMVC

14 CAPITOLUL 3. CODE FIRST TUTORIAL CURS 1

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

3.1 Inregistrarea unui utilizator nou

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

Figura 3.2: Sectiunea de pro�l

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 paginasi aceasta o sa reprezinte o portiune de pagina in care vom avea numele utilizatorului si un buton de log o�pentru a parasi modul autenti�cat 3.4.

In spatele acestui tip de modi�cari avem o serie de tabele in baza de date, care au inregistrat acesteaspecte 3.5 si 3.6.

Tabela UserPro�le 3.5 contine doar doua coloare: UserId si UserName.

Page 41: HowToAspNetMVC

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

Figura 3.4: Pro�lul unui utilizator

Figura 3.5: Tabela UserPro�le

Figura 3.6: Tabela webpages_Membership

Iar tabele webpages_Membership 3.6 contine o serie de informatii cum ar � parola criptata, o cheie strainapentru user, data la care s-a gresit ultima data parola, daca e contul blocat, detalii legate de con�rmareacontului 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 stocatpe 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" />

Page 42: HowToAspNetMVC

16 CAPITOLUL 3. CODE FIRST TUTORIAL CURS 1

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: "Trus-ted_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 seriede modele, care sunt folosite in aplicatie, pentru inregistrarea unui utilizator, autenti�care si autorizare.

public class UsersContext : DbContext \\ contextul de lucru al luiEntity Framework

{public UsersContext ()

: base("DefaultConnection") \\ conexiunea default la baza dedate , e exact numele conexiunii de mai sus

{}

public DbSet <UserProfile > UserProfiles { get; set; } \\ un set deutilizatori din baza de date , practic tabela de UserProfile

}

[Table("UserProfile")] \\ numele tabelei din baza de datepublic class UserProfile \\ numele modelului din aplicatia web{

\\ specificam faptul ca e cheie primara[Key]

\\ specificam faptul ca aceasta cheie esteautoincrementata

\\si baza de date va avea grija de generareaacesteia

[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 bazade date, in care sa stocam informatiile legate de produs.O sa adaugam in directorul models o noua clasa numita Product.

[Table("Product")] \\ numele tabeleipublic class Product{

[Key] \\ cheie primara[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]

\\ autogeneratapublic int ProductId { get; set; }public string ProductName { get; set; } \\ numele produsuluipublic decimal Price { get; set; } \\ pret

}

Page 43: HowToAspNetMVC

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. Vomfolosi Nuget Package Manager Console 3.7, iar in partea de jos va aparea o fereastra, care va � folosita pentrua 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 numitcon�guration.

PM> enable -migrationsChecking 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 dedate nu se vor aplica automat ,

\\ ci se va astepta o comanda de tipupdate -database

AutomaticMigrationsEnabled = false;

Page 44: HowToAspNetMVC

18 CAPITOLUL 3. CODE FIRST TUTORIAL CURS 1

}

protected override void Seed(Models.UsersContext context){

// This method will be called after migrating to the latestversion.

// 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 modi�cari asupra bazei de date. Vomfolosi Package Manager console ca si mai devreme si vom rula urmatoarea comanda.

PM> add -migration firstMigrationScaffolding 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 yourmodel when you scaffold the next migration. If you make additionalchanges to your model that you want to include in this migration , thenyou can re-scaffold it by running ’Add -Migration201403152013151 _firstMigration ’ again.

public partial class firstMigration : DbMigration{

// script de upgradepublic 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),

Page 45: HowToAspNetMVC

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 dinPackage Manager console a comenzii: Update-database.

PM> Update -databaseSpecify 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 sca�olding care ne va genera pentru un controller si un model o seriede functionalitati prede�nite, pe care noi le vom extinde in proiectul nostru.

Pentru a efectua aceste schimbari vom da click dreapta pe Controllers -> Add ControllerDupa 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 veri�ca functionalitatea tocmai adaugata, va trebui sa rulam proiectul din nou. Apoi sa modi�camurl-ul din http://localhost:XXXXX/ in http://localhost:XXXXX/Product/Index

Page 46: HowToAspNetMVC

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

Page 47: HowToAspNetMVC

3.6. PRIMUL PRODUS ADAUGAT 21

Figura 3.10: A�sarea listei de produse

Figura 3.11: Adaugarea unui nou produs

Page 48: HowToAspNetMVC

22 CAPITOLUL 3. CODE FIRST TUTORIAL CURS 1

Figura 3.12: Adaugarea unui nou produs

Figura 3.13: Lista cu produsul nou adaugat