100% found this document useful (1 vote)
154 views

Udemy From A Nonprogrammer To FullStack

This document is a step-by-step guide for creating a first web application as a full stack .NET developer. It introduces key concepts needed for full stack development like databases, frontend and backend programming. It then guides the reader through setting up tools, creating a database, basic programming concepts, and building an MVC web application with C# and .NET that connects to a SQL database and has CRUD functionality. The guide explains concepts in a beginner friendly way and ensures the reader has everything they need to build their first full web application from start to finish.

Uploaded by

vio gby
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
154 views

Udemy From A Nonprogrammer To FullStack

This document is a step-by-step guide for creating a first web application as a full stack .NET developer. It introduces key concepts needed for full stack development like databases, frontend and backend programming. It then guides the reader through setting up tools, creating a database, basic programming concepts, and building an MVC web application with C# and .NET that connects to a SQL database and has CRUD functionality. The guide explains concepts in a beginner friendly way and ensures the reader has everything they need to build their first full web application from start to finish.

Uploaded by

vio gby
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 111

From A Non-Programmer To Full Stack .

NET Developer
Step-by-step guide for your first web application (includes setup tutorials for the tools you need)

ION-COSMIN GRIGORE
ABOUT THE AUTHOR

Cosmin grew up in Ploiesti and graduated from the University Politehnica of Bucharest. He
has over 7 years of professional experience in software development, having had the opportunity
to improve his teaching and leadership skills.

He is passionate about personal development, nurturing emotional intelligence, social and


financial skills in every possible way, this being proven by the numerous personal projects we
worked on, including some related to cryptocurrencies.

With an exceptional eye for details when it comes down to helping others achieve their goals, he
considers everyone can learn if they take the right path.

If you want to find more about him, we recommend following him on Facebook & LinkedIn.

Personal Note:

Hey everyone! I like people who want to overcome their current condition and hate arrogant
people and those who do not want to evolve.

I hope my lectures help you achieve your extraordinary goals.


Table of Contents
Course overview ........................................................................................................................................... 6
The Purpose Of This Guide........................................................................................................................ 6
What Is Programming? ............................................................................................................................. 7
What Is A Full Stack Developer? Database, Frontend and Backend explained ........................................ 7
Obstacles & You: One Step Ahead Of Everyone Around You ................................................................... 8
Before writing code....................................................................................................................................... 8
What is a web browser? ........................................................................................................................... 8
What is an IDE? ......................................................................................................................................... 9
Microsoft Visual Studio: Setup................................................................................................................ 10
How Web Applications Usually Work ..................................................................................................... 12
What is Hosting? ..................................................................................................................................... 14
Choosing Our Database: Setup ............................................................................................................... 15
Pop Quiz 1 ............................................................................................................................................... 18
Summary ................................................................................................................................................. 18
Starting Slowly, Decoupled ......................................................................................................................... 19
Database System Introduction: understanding Microsoft SQL Server ................................................... 19
Database Schema Using Medieval Methods: the magical pen and the paper ....................................... 22
Creating Our First Database: a new love story ....................................................................................... 23
Adding Test Data To Our Tables.............................................................................................................. 27
Pop quiz 2 ................................................................................................................................................ 29
What Is T-SQL: examples......................................................................................................................... 30
Pop quiz 3 ................................................................................................................................................ 32
Basic Programming Knowledge .................................................................................................................. 32
Our Backend: C#...................................................................................................................................... 32
Class, methods, variables, namespaces and types ................................................................................. 33
Pop quiz 4 ................................................................................................................................................ 36
Our Frontend: Html, css and Javascript .................................................................................................. 37
Summary ................................................................................................................................................. 42
First Steps With Our IDE.............................................................................................................................. 43
Solution, Projects And The Right Architecture: using the magical pen again......................................... 43
One Step Closer: creating our digital project .......................................................................................... 44
Few Programming Terms Explained: you will always hear them ........................................................... 47
Linking The Database .............................................................................................................................. 48
Elegant Way Of Writing T-SQL Queries: lambda expressions ................................................................. 54
Pop Quiz 5 ............................................................................................................................................... 59
Summary ................................................................................................................................................. 61
The Management Layer .............................................................................................................................. 61
What is mapping ..................................................................................................................................... 61
Data Transfer Objects ( DTOs ): MovieDTO ............................................................................................ 62
MovieManagement ................................................................................................................................ 63
Pop Quiz 6 ............................................................................................................................................... 72
The API ........................................................................................................................................................ 72
What Is An API......................................................................................................................................... 72
Some More Programming Terms Explained: related to APIs ................................................................. 73
Our First API ............................................................................................................................................ 74
Debugging Our Simple API ...................................................................................................................... 80
Pop Quiz 7 ............................................................................................................................................... 83
Summary ................................................................................................................................................. 84
The Frontend Layer ..................................................................................................................................... 84
What is Bootstrap? ................................................................................................................................. 84
Using Our Frontend Project: First MVC Controller ................................................................................. 90
Pop quiz 8– CRUD ................................................................................................................................... 92
The Entire Flow Explained Again: the magical pen ................................................................................. 93
First View: the ‘list’ page ......................................................................................................................... 94
A New View: the ‘details’ page ............................................................................................................... 99
Pop Quiz 9 ............................................................................................................................................. 103
Summary: your first web application .................................................................................................... 103
The End ..................................................................................................................................................... 103
Helpful Links: further reading ............................................................................................................... 103
The Enormous Amount of Frontend Libraries ...................................................................................... 104
Course Wrap Up .................................................................................................................................... 105
Final exam ............................................................................................................................................. 105
Answers ................................................................................................................................................. 109
Course overview

The Purpose Of This Guide

Hello,

My name is Cosmin and first of all I want to say a big Hello and Welcome to From A Non-Programmer To
Full Stack .NET Developer complete course. I am very grateful you decided to take it and I want you to
know how much I value your support!

At the end of this course you should be able to build a web application from the ground-up using the
methods presented here. There are a lot more options, technologies and architectures for creating a web
application, but we will focus only on a few and this is going to be your starting point. After going through
all the lessons, you will have the necessary skills for searching different techniques and you should be able
to try them out by yourself.

I want this course to be your starting point of how you can link everything you’ll learned into a web
application. I will not go into details with every technology we take a look on, because it will take too long
and it will be more confusing than in the beginning. I will explain only the necessary stuff for you to be
able to create a web application. The more time you spend learning, the better that web application will
become.

I’ve built this guide in a way that even people who don’t have anything to do with programming can
benefit from it. So, my first advice for you is “don’t be scared, but in the same time don’t expect it to be
very easy”. Life is not all beer and skittles and for sure I am not here to lie to you that by only taking this
course you’ll become an awesome developer. You must stay motivated and work very hard for it.

Few things about me:

I am 27 years old and I have been working as a programmer for over 7 years. When I was in college, I was
just like you, knowing almost nothing about writing code. I remember I was literally memorizing the
algorithms before exams, because I couldn’t understand them.

During my university years, I started my first job, an internship at a local company here in Bucharest, for
which I am very grateful. The first part of the internship was something like a software academy and during
that time I’ve learned A LOT; basically, I was just starting to become a developer, a very numb one, but
still a developer. That was the boost I needed so much and that’s why, after a few years I want others to
feel the same emotion I’ve felt during that time and during all the years that came after.

I organized this course in a similar way, and by following it step by step, you will for sure learn all the
necessary stuff for building a .NET application.
What Is Programming?

A very good analogy I heard some time ago is this one: coding can be compared to writing cooking recipes.
A recipe is the program and the cook is the computer. A recipe is a list of instructions for a cook to follow
and a program is a list of instructions for a computer to execute.

A computer can only understand two types of data: 0 and 1 or better called on and off, because computer
is just a collection of transistors. Everything you write it is transformed in a bunch of 0s and 1s that
computer will process by turning these transistors on or off.

Programming helps you to: improve your logical thinking, improve your problem-solving abilities, improve
your search skills, find a nice and well payed job and understand new technologies.

What Is A Full Stack Developer? Database, Frontend and Backend explained

You can split any website into 3 major parts, even if there’s not always the case, but just to simply things
for now, let’s organize it in this way:

- First major part is the database, which is a container where all the data is stored. For example,
think of all the gadgets you have in your house (TV, smartphone, tablet and so on). Database it’s
like a bucket where you put all of them in an organized manner. Each time you need one, you go
to the bucket’s location and extract one from there.
- Second major part is represented by the frontend. Frontend is what you see, the user interface.
When you go to Facebook you see the wall, a search field, some buttons, the design mostly in
gray which is a neutral color expressing calm and balance and blue which creates the sensation of
trust and security. That’s frontend, what you see and happens in front of your eyes.
- And the third major part is the backend, the stuff behind the scenes you don’t see. Whenever you
press a button, go to a page or do any action on a website, something from the backend is
triggered. That’s the place where all the code and the logic of your applications is located. (by the
way, frontend has some logic too, but I don’t want to go to deep into details now). For example,
when you post something on Facebook, a save action is triggered in the backend, which has some
processing logic and then the backend stores the post you made with some more information into
the database.

You can be a database developer, a frontend developer or a backend developer, but a Full Stack Developer
writes code for all the 3 major parts. He knows all of them and he can build a web application from scratch
all by himself and that’s what I will teach you in this course.
Obstacles & You: One Step Ahead Of Everyone Around You

I don’t want to scare you, but becoming a programmer isn’t just taking some lessons, even if these lessons
have outstanding results. This course represents just a very small amount of the pie you must eat to
become a great developer. But trust me, once you start eating from that pie, it’s going to be awesome.

Let’s get this thing right. I don’t want to just sell you a course, I want to teach you something and for this
I need to make sure you have whatever it takes.

I want to make sure you are very motivated to learn, that you will love to stay awake longer just to
understand different programming concepts.

Also, in your first months or years as a programmer you will constantly feel a bit stressed due to all the
pressure that comes from your team leader and from your inner motivation. What am I talking about?
Well, there will be time when you are eager to finish something but don’t have the necessary skills for it
and you must ask a lot of questions. If you’re a bit shy or too concerned of what others think about you,
then there’s the possibility you are going to feel a bit irritated because you’re asking so many questions.

Another obstacle is that you’ll feel a bit weird and not very confident on your abilities, because you will
constantly search for ideas online. Most of the time you’ll just copy-paste parts of the code you need from
other projects or from solutions found online. Don’t worry, everyone does this, even if you have over 20
years’ experience in the field.

And another one: If you’re going to develop web applications for the rest of your life you will discover that
some code that works on Chrome or Firefox doesn’t necessarily means it will run on Internet Explorer, but
I let you discover this by yourself.

There are a lot more obstacles, but it’s best if you discover them by yourself. Finding a solution for
something you don’t know, it’s a big step ahead and it only helps you.

Before writing code

What is a web browser?

This one is very simple and I am going to be very short. Chrome, Firefox, Internet Explorer, Safari, Opera,
these are all browsers. So, it’s a piece of software that can display a web application or in other words, a
software that is used to access the internet.
What is an IDE?

IDE is a software that has multiple scopes:

- code editor – which allows you to write code in different languages like C, C++, C#, Java and so
on,
- a compiler – which transforms your code into machine code- a bunch of 0s and 1s so the computer
can interpret it
- a debugger, which helps you to test your code to see if there are any errors
- the user interface

Debugging is the process when instead of letting the compiler to take care of your code, you manually run
it line by line.

I have this piece of code here, which displays the sum of 2 numbers. By just running the code, it only
displays the result (see the Console.WriteLine(sum) line). But if I debug it, I can clearly see what happens
on each line. This helps you when you need to identify a problem or a wrong result happening in your
application.

For our solution we’re going to use Microsoft Visual Studio 2017 Community Edition as our IDE and in the
next lesson I’m going to show from where you can get it and how can you install it. You must pay attention
because we are going to use it for the rest of our course.
Visual Studio 2017

Microsoft Visual Studio: Setup

Step 1 – google search & download


Step 2 – setup (choose .NET desktop development, ASP.NET and web development, .NET Core cross-
platform development, Node.js development)
Step 3 – finishing up

How Web Applications Usually Work

Meet John!

John knows that any web application can be made using 3 major components: database, frontend and
backend.

John clicks on a button on the frontend, then a component called Controller picks up the action according
to a specific Route the developer has set when coding the application. The Controller knows what to do
next and calls another layer from the application which is usually responsible with the business logic. This
last layer does some processing and then calls the final layer, the Database Access layer which is
responsible with saving or retrieving data from the Database.

Ok, let’s say bye to John for the moment, because I feel you need some explanations.
So, this is a Controller and as you can see it has a bunch of methods written here. I will explain what a
method is, a bit later. Each method represents an action this Controller can perform.

Above each method is a line called ‘Attribute’ which sets some options, some metadata and in this case
our attribute is called ‘Route’, which sets the action URL (by the way, an URL is the address you type in
your browser, like www.google.com).

Let’s say our server is www.myfirstapp.com, the controller’s route is /categories, so the URL for it is
going to be www.myfirstapp.com/categories (coming from the RoutePrefix attribute) and actions are
www.myfirstapp.com/categories/search, GET, DELETE and PUT
www.myfirstapp.com/categories/2f553a6f-83ea-4df5-8c50-bc0fb303cfde, POST
www.myfirstapp.com/categories. 2f553a6f-83ea-4df5-8c50-bc0fb303cfde represents a unique
identifier. Latter we are going to learn that each record in our database must have a unique identifier,
which can be anything, but for this example we chose a GUID (globally unique identifier or UUID –
universally unique identifier). A unique identifier is of course used to identify an object. For example,
you can have 2 persons called John, but by assigning something unique to them, like a text or a number
like 10 for first one and 20 for the second one, you can easily identify them.
I hope now, when using any web application, you can identify routes. For example, when going to events
page from Facebook, the URL becomes https://www.facebook.com/events/ . Looking at this route we
discover that the controller can be ‘Events’ (I’m not 100% sure this is the case, because it depends on the
technology they use and what routing system they chose).

There are a lot of attributes you can set for each action, like [HttpGet], [HttpPost] etc., but we will talk
more about them latter in this course.

What is Hosting?

Hosting is a service that allows people to make a web application, pages or files publicly visible onto the
internet.

A simple way to enable an internal hosting on your computer so you can test your web application is to
enable Internet Information Services, or simpler IIS, a web server that runs on Windows. (don’t worry, it
won’t be accessible from the internet)

In order to do so, press on the start menu icon, type ‘turn windows’ and click on ‘Turn windows features
on or off’. Search for Internet Information Services and Internet Information Services Hostable Web Core
and make sure everything under these 2 options is checked. If you’re asked to restart your computer,
please do so.

We now have the IDE to code our application and IIS to host it. The only thing we are missing is a software
to create and manage our database.
Choosing Our Database: Setup

There are 2 main types of databases: relational databases, which are also called SQL databases, like
Microsoft SQL, Oracle, MySQL, IBM DB2 and non-relational databases, which are also called NoSQL
databases, like MongoDB, Neo4j, Raven.

Each database system comes with its own advantages and disadvantages and have different purposes,
some are used for document storing, some for large media storage, some for scenarios where you can’t
afford to lose any data because operations can be made using a service called Transaction.

However, for our case there is no right or wrong database. We can use any, because we are not in a
business-like environment, but we’re choosing a relational database, Microsoft SQL Server due to a
simpler integration with our IDE, Microsoft Visual Studio.

You must download 2 applications: SQL Server Express, which, as the name suggests is the database
server, the application responsible with holding the database for us and Microsoft SQL Server
Management Studio, which is the user interface we can use manage our database.

SQL Server Express


SQL Server Management Studio
Pop Quiz 1

1. What is an IDE?
a. A software used for compiling code
b. A software used for debugging an existing application
c. A software used for writing code
d. All the above
2. Is Chrome a web browser?
a. Yes
b. No
3. What is a Controller?
a. The first logical layer of our application responsible with routing and processing the
actions user is performing on the frontend layer
b. The last layer of our application responsible with saving and retrieving data from the
database
c. None of the above
4. What is an attribute?
a. A way to associate metadata and declarative information with a piece of code
b. The URL of a specific website
c. None of the above
5. What database we chose for our application?
a. MySQL
b. IBM DB2
c. Neo4j
d. MongoDB
e. Microsoft SQL Server
6. Microsoft SQL Server is?
a. A relational database system
b. A NoSQL database
c. A non-relational database system
d. None of the above
7. What is IIS?
a. A web server from Microsoft that runs on Windows to serve requested web pages or
files
b. Name of a transaction used in relational database systems
c. None of the above

Summary

In this chapter I taught you about all the necessary stuff needed for developing and testing our web
application. I told you what a web browser does, like Chrome, we chose our database system, we
enabled IIS, the web server used to server our application and we chose the IDE, Microsoft Visual Studio
2017.

For your first web application I am thinking of creating a Movie Management system, that will allow
searching, creating, editing and deleting movies.

Starting Slowly, Decoupled

Database System Introduction: understanding Microsoft SQL Server

To open SQL Server Management Studio press Start and type ‘SSMS’; click on it.

You are going to be prompted with the connection for database server. The one we installed was SQL
Server Express, remember? So we choose, Database Engine as our Server type, our server name is
‘.\SQLEXPRESS’ and for Authentication we choose Windows Authentication. Click on Connect.

Before anything else, we need to do one more thing, click Tools from the menu, Options, choose
Designers from this list and uncheck ‘Prevent saving changes that require table re-creation’ and hit OK.

Now we have everything set up. Let’s understand the user interface.
In the left part we have what is called the Object Explorer, where we can find all the databases we
create, all the logins that can access specific databases and some other stuff that is not important for
this course.

First line represents the server you are currently connected to. Being a management software, you can
connect simultaneously to multiple databases. To do so, just click on the Connect button, select
Database Engine and fill the necessary information.

Let’s expand the database node of the first server. That’s the place where all your databases can be
found. Now is probably empty. To create a database, right click on the database node and choose Create
Database. We will do this a bit later.

A bit upper, we can find the SQL Editor line. If you don’t see it make sure it is enabled. Right click in the
right part of the menu and check SQL Editor and Standard.

These tabs have options that we are going to use when we create our database. The SQL Editor one is
used to run different code on a specific database, code that can save, delete or retrieve data and the
Standard tab is used to create a New Query, query meaning a file containing this code.

Let me show how a code responsible with retrieving some data looks like:
select * from Notifications

In the right upper corner, you can see on which database I am executing the query (mine is called
ICOPrepare).

By clicking execute you can see my data is displayed below. The result can be outputted in 3 different
ways, to Text, to Grid and to a File. Leave Grid enabled for now.

We will talk a bit later about queries, but I think you can already understand some part of it. SELECT means
I want to select, I want to retrieve something from the database, the star * means I want to retrieve
everything and Notification is the table’s name. Each database can have multiple tables. For example, you
can have a table called Cars where some data related to cars is saved, another table called Toys where
data related to toys is saved and so on.

In the display grid you can see the result is outputted in a table like structure. So, we have 4 columns in
our Notification table: ID, the unique identifier, Title, Timestamp and Description.

In our case, if we want to retrieve only Title and Timestamp, instead of putting a star * there, we can write
our query like this:

select Title,Timestamp from Notifications

Of course, there is a lot more to talk about regarding SQL, but it’s enough for now. Let’s create your first
database.
Database Schema Using Medieval Methods: the magical pen and the paper

Being a programmer doesn’t mean you would never use pen and paper again. It’s sometimes even better
to do it to organize your thoughts.

So, let’s see what we need. We decided to create a movie management system.

We need a Movies table in our database, of course. Its columns should be:

ID – of type unique identifier, which cannot be null (meaning it must always have a value) ( we set
this as so called Primary Key so we can tell SQL this is our unique identifier )

Title –the movie title of type varchar(400), meaning a string containing no special characters up
to a 400 characters limit. Not null

Release Date – of type datetime, not null

Length – of type int, meaning a whole number, not null

Rating – of type varchar(50), like PG-13, PG-16 and so on. This one can be null

AverageScore – of type float, meaning a real number like 8.75

CategoryId – of type uniqueidentifier, which will be a reference, a link to another table. We could
have created a varchar column for category, but the best practice is to separate different concerns.
Another reason is that once the Comedy category is created, there won’t be duplicate entries like
Comedies.

By the way, I know a movie can have multiple categories, but in our structure, we cannot have more than
1, because each movie has a CategoryId column where you can set only 1 unique identifier linking to a
category from Categories table. I did it intentionally to show you different scenarios. This type of
relationship between tables is called One to Many relation (a book can have multiple pages, a cook can
have multiple recipes, a person can have multiple pictures, a category can be assigned to multiple movies
and so on). So, when you see a column being a reference to another table, that’s called a One to Many
relationship.

The Category table:

ID - again unique identifier and primary key, not null

Name – varchar(100) being the name of a category, like Comedy, Horror, Thriller and so on

There’s also another type of relation called Many To Many and I am thinking on using that for reviews,
because a user can review multiple movies and a movie can have reviews from multiple users, but never
same user with multiple reviews for same movie.
In order to do it we need a Reviews table. This will contain 10 rows, each row being a number from 1 to
10, a score that can be assigned to a movie. I am going to keep it simple by adding only 2 columns:

ID- unique identifier and primary key, not null

Score – of type int, not null

As you can see I don’t have any column that links Movies to Reviews, because if I put a ReviewId column
in movies, that means each movie can have only 1 review and if I put a MovieId in Reviews that means
each score can be assigned to only 1 movie, meaning if a score of 10 is assigned to a movie, no other
movie can have 10.

In order to fix this we need a new table, which will call MovieReviews and this one is going to have 2
uniqueidentifiers, one for each table

MovieId uniqueidentifier

ReviewId uniqueidentifier

And we set both, as primary keys. In an enterprise application we would have another column, UserId,
which represents the user giving the review, so our table is not 100% right. Same movie cannot have 2
reviews with same score at the moment, because we would have a duplicate entry in our table, which is
not permitted with our current structure. If we add a new column, UserId, then something like Movie1-
Review10-User1, Movie1-Review10-User2, it’s permitted, the user who reviewed the movie, being
different.

Let’s stop here for the moment. I more than enough for our simple application. Let’s translate this to SQL.

Creating Our First Database: a new love story

Right click on the database node and select New Database. Give it a name, let’s say ‘MoviesDB’. Expand it
by clicking the plus sign. Right click on the Tables node and select Table.

Let’s start with the simpler ones. Category table.

Add the fields we wrote on paper. Id - uniqueidentifier and uncheck Allow Nulls. Same for Name.
After that, hit Ctrl+S and give it the Categories name. We forgot to set the primary key on unique identifier
(this key helps SQL to know that’s our identifier column). Right click on the Id column and select Set
primary key. A yellow key should appear near that column. Hit CTRL+S again.

If you closed the table by mistake, don’t worry, just right click on the one you want to edit, Categories in
this case (if saved it few moments ago, but you can’t see it under Tables node, select Tables node and hit
F5 on your keyboard) and select Design. It will open the same page.
Do the same for Reviews, Movies and MovieReviews (add all the fields you wrote on paper during the
previous lesson).
We added everything but we don’t have any relationship between our tables. In order to do so, let’s go
to Movies tables, right click on it and select Design. Right click anywhere inside current page (the designer
page from the right part of the screen) and select Relationships. Press the Add button.

A new relationship was created and now we need to set the child and the parent. In the right pane, go to
Tables and Columns Specification and click on the 3 dots (they appear only after you click inside that
textbox). In our case Primary Key table is Category and the column is Id and the Foreign Key table is Movies
with CategoryId column. Hit Ok, close and Ctrl+S again.

Let’s do the same for MovieReviews. The only difference here is that we are going to add 2 relationships
so we can have both directions. So first one, from Movies to MovieReviews. And we need to set only the
column related to MovieId. The second one is from Reviews to MovieReviews and we set only the column
linked to ReviewId. Hit Close and CTRL+S again.
Congratulations. We have our database ready. Next we are going to add some test data.

Adding Test Data To Our Tables

Let’s start again with the simpler ones. Reviews. Select the table in the left pane and click on the new
query button and write the following query

INSERT INTO Reviews (Id,Score) VALUES(NewID(),1)

We are going to do this 10 times for scores 1 to 10

INSERT INTO Reviews (Id,Score) VALUES(NewID(),2)

INSERT INTO Reviews (Id,Score) VALUES(NewID(),3)

….

INSERT INTO Reviews (Id,Score) VALUES(NewID(),10)


The query is kind of self-explanatory, insert into meaning saving into that table, next we set the columns
for the table and then the corresponding values.

So we have same query written 10 times, the only difference being the score. To run it we need to click
on the Execute button.

And done, we finished with Reviews table.

Let’s insert some test data into Categories as well.

Select Category from left pane and hit New Query. If you want to see columns of Category table, expand
it in the left pane and then expand Columns.

INSERT INTO Categories(Id,Name) VALUES(NEWID(),’Comedy’).

INSERT INTO Categories(Id,Name) VALUES (NEWID(),’Drama’).

And click Execute.

Ok. We now have some test data. To see it right click on Reviews or Categories tables and Click Select Top
1000 Rows.
I have good news for you. We don’t add test data to movies because we are going to do it from OUR
application.

In the next chapter I’m going to test what you’ve learned.

Pop quiz 2

1. Considering the following tables Person(Id,Name, CarId) and Cars(Id, Name), what relationship is
between Person and Cars ?
a. Many To Many
b. One To Many
2. Considering the following tables Person(Id,Name), Cars(Id,Name) and
PersonCars(PersonId,CarId), what relationship is between Person and Cars?
a. Many To Many
b. One To Many
3. What is a primary key?
a. A unique identifier, helping SQL to uniquely identify each row of a table
b. A special column that is helping SQL to link a table to another one
4. What is a foreign key?
a. A special column that is helping SQL to link a table to another one in a One to Many
relationship
b. This concept doesn’t exist in SQL

What Is T-SQL: examples

You’ve already used it without knowing this naming. Any query in SQL Sever is called T-SQL or
Transactional SQL. You can select, delete, update, insert and do many more operations against one or
more tables.

I’m going to teach you some simple queries that will help you at the beginning. These are going to be your
starting point.

SELECT queries

You’ve already saw the select query in a previous lesson:

SELECT Id, Name FROM Movies

If you want to select all columns, instead of enumerating them, you can put a start *: SELECT * FROM
Movies.
If you want to select only first 10 results from a table you write

SELECT TOP 10 * FROM Movies

If you want to order the results in a specific way you can do it like this

SELECT * FROM Movies ORDER BY Length

This is going to sort the results ascending, but if you want them in a descending order, just add DESC
keyword at the end of your query.

SELECT * FROM Movies ORDER BY Length DESC

If you want to select only rows that meet a condition you can use a keyword called Where

SELECT * FROM Movies

WHERE Rating IN (‘PG-13’, ‘PG-16’)

or
SELECT * FROM Movies

WHERE AverageScore > 7


INSERT query

You’ve saw this one too and it is very simple.

INSERT INTO TableName (Column1,column2,column3, … and so on) Values (value1,value2,value3,….and


so on )

INSERT INTO Categories ( ID,Name ) VALUES (‘some id’, ‘some name’)

In our previous example we’ve used NEWID() function from SQL, which generates a unique identifier for
us. (its equivalent in C# is Guid.NewGuid())

UPDATE query

Syntax looks like this:

UPDATE TableName Set Column = value or UPDATE TableName SET Column = value WHERE condition in
case we don’t want to update all rows from a table, but only the ones that meet a specific condition.

For our Categories table, an update Query would look like this:

Update Categoreies Set Name =’Comedies’ Where Id=’some unqiue identifier’

This will update the Name column for the row with Id=’some unqiue identifier’

DELETE Query

Delete from TableName or Delete from TableName Where Condition

For our Categories table would look like this

Delete from Categories Where Id=’some unique identifier’

If we don’t put a condition it will delete everything from that table.


Pop quiz 3

1. What does the following query?


SELECT Id, Score FROM Reviews WHERE Score IN (4,5) ORDER BY Score DESC

a. Retrieves 4 or 5 rows from Reviews containing all columns, sorted them in a descending
order
b. Retrieves Id and Score columns from Review, sorted in a descending order and having
Score 4 or 5
2. What does the following query?
SELECT Name FROM Movies WHERE AverageScore >7 AND Rating !=’PG-13’

a. Inserts a new row into Movies table


b. Retrieves Movies with an average score higher than 7 and having Rating different than
PG-13
3. What does the following query?
DELETE FROM Reviews

a. Deletes all rows from Reviews table


b. Deletes all rows that are linked with any row from Reviews table
4. What does the following query?
UPDATE Movies SET Name = ‘a new name‘ WHERE Id= ‘ a unique identifier’

a. Updates all movies from Movies table by setting Name to ‘a new name’
b. Updates only 1 row from Movies table

Basic Programming Knowledge

Our Backend: C#

The programming languages are divided into 2 categories:

• High-level;
• Medium-level;
• Low-level;

Programmers can write code in a natural way using logical words and symbols. There are reserved words
that are used in most programming languages. (ex: Function, while, if, else, common operators like: ==,>,
<, !=). Many high-level languages are quite similar so programmers can easily understand the code written
in several languages.

Examples of high-level languages: C #, Java, JavaScript, Python, Perl, etc.

The problem is that a computer only understands the code written in binary (0s and 1s).

To understand the written code in a high-level programming language, the instructions must be translated
into a binary language. This is what a "translator", the so called compiler deals with.

Middle-level languages: C, C ++, Pascal, and so on

Low-level languages are languages that are translated directly into binary code and do not need a compiler
to be translated. Writing, reading and understanding the written code in a low-level language is tricky.
(Assembly Language is one example)

Of course, these languages are faster than high-level because they are understood faster by the computer,
but they come with a very big disadvantage, very few people are using them these days because they are
pretty hard to understand.

Given these facts, we’re going to use C# for our application. It’s one of the most used languages out there
and it will help you a lot in your career.

Class, methods, variables, namespaces and types

Class is basically a template usually used for modeling real world scenarios.

You are an object of the class 'Human'.


You have functions such as speak, breath etc.
You have properties such as name, age, height, weight and so on.

You can think of a class as a template for creating objects. In our previous example, Human was the class
and you are an object of that class.

For example, you can create a class called Car. Objects like Ferrari, Tesla, BMW are objects of the class
Car, each with specific properties, Tesla being an electric car and BMW a petrol or a diesel car.

To declare a class in C# you can write something like


Curly braces {} are used for everything in C# and they represent the start and the end of something.
Anything between curly braces represents the body of that thing.

Namespace is just a container for classes. It will prevent problems with 2 classes that share the same
name. We can have 2 completely different classes named Car, each in a different namespace, but never
in the same namespace.

Syntax for namespaces looks like this:

Public keyword means the class accessible from another namespace.

Type

A type is classification of data which tells the compiler how the programmer intends to use that data.
Example of types: string which refers to text, like “some text“, int means it is a natural number, like 2019,
bool for true and false, class for Classes we just talked about, char is for letters ‘c’.

Methods

Think of methods as verbs in grammar. They are like an action that can be performed by something. Take
for example the Human class. Some methods can be: speak, breath, walk, swim and so on.

In the example below, we have 1 property – Name and 2 methods – IsBreathing and SetName.
Public keyword when linked to a method means that method is accessible outside of the class (in antithesis
with private). After public the next word represents the output type of that method, bool in first case,
which as I said can be true or false and void in the second one, which tells the compiler that SetName
method does not return anything, it has no output. In our case just sets a name, so it doesn’t have to
return anything. So void=nothing. After that, between parenthesis are the parameters that method
receives. In the first case there is no need for any parameter. In the second case, we need a value for the
Name property and that value can be sent using parameters.

A method can have as many parameters as you want, but it’s better to limit them to 4 or 5. If you need
more than 5 parameters for a method, maybe it’s a better idea to group them in a class.

Variables

One of the most used and important concepts and of the simplest ones. Think of variables as some little
boxes. You store and retrieve values from them. You can store text (string), numbers (int, float, double)
and many more other types. Latter maybe you want to verify what’s inside the box or even to update the
value from that box.

To declare a variable in C# you can write something like

string myString = “this is a text”

int myNumber =10;

string is the type, myString or myNumber is the name of the variable (each variable is identified by a name)
and “this is a text” and 10 represents each variable’s value.

In C# you can also write a variable like this

var someVariable = “some text”

var someOtherVariable = 1;

Var is like a placeholder. Instead of writing the type directly, the type is assigned by what is written after
the equal sign.
Pop quiz 4

1. What type does this variable have in C#? var myVariable = “example”;
a. Int
b. Number
c. Text
d. String
2. What type does this variable have in C#? var myVariable =1;
a. Int
b. Number
c. Text
d. String
3. In the following example, public void myFunction (string one, string two), what are one and two?
a. Return Type
b. Parameters
4. What is the return type of the following function?
public ComputerInfo GetComputerDetails(Guid id)

a. Guid
b. ComputerInfo ( class defined by the user )
c. Public
d. None of the above
5. What Run represents in the following situation?

a. A class (defined by the developer)


b. A function (method)
c. None of the above
Our Frontend: Html, css and Javascript

HTML

HTML is one of the easiest, or maybe the easiest language a full stack developer must learn.

It’s written in a node like structure and each html page is a file with .html extension.

Example:

This example can be a complete, but very basic HTML page. Let’s save this code into a html file to see
what’s the output. (don’t forget the .html extension)

As you can see it displays a title, a header (due to the h1 node).

Each HTML page must start with an html node. Inside the HTML node, we can find Header and Body nodes.
Everything you write for now will be placed inside the Body tag. That’s the content of your web page.

For example, the following html displays a table with 3 columns


Tr is the tag for creating a new table row.

Td is the tag for creating a new table column.

Th is the tag for creating a new table header column. Basically, is the same thing as td, but it displays the
text in bold.

Some more usual html tags: div, span, h2, h3, h4, h5, h6, img, p , ul. Use them in a .html file and see what
happens. Also, I advise you to read about them.

Once you finished learning all these tags, come back here because we will start learning about CSS.
One more thing before we start learning about CSS. To identify HTML elements, you have multiple options,
but most common ones are using attributes class and id. A tag having these attributes would look like this

Id attribute is optional, but it must be unique on a page. Each element must have its own id, different
from the others. Class doesn’t have this requirement. You can assign same class to multiple elements and
one element can have multiple classes.

Ok, let’s head to CSS now where we’re going to see how to make use of these attributes.

CSS

We’ve learned how to display html elements but they look very basic, they are not as impressive as all the
modern web applications you’re using every day.

CSS is one of the solutions for this problem, because CSS is used to style the HTML you wrote, by assigning
different colors, sizes, positions (where to be placed on the screen), animations and many more other
properties. And to assign different properties, you need a way to identify elements. I told you about class
and id attributes, but you can also style all elements of a specific type, all divs from a page, all paragraphs
and so on.

For example, a code to assign a background color to all paragraphs in a page, would look like this:

This is called a selector. It translates something like: selecting all p elements and assigning these
properties, in our case, the background-color.

But, what if you want to assign same color ONLY to paragraphs having the class ‘red-background’? You
just append the class name at the end of the selector. Like this:

And if you have different html elements with same class, you don’t need to write them all like, div.red-
background, p.red-background and so on. You can remove the element from our selector and write only
the class name:
This way, any element having red-background as a class, no matter if it’s a paragraph, a div, a span or
whatever.

So ‘.’ Is the selector for class. The selector for id is #.

Before going into Javascript code, pause reading here, learn more about CSS and when you think you’re
ready, come back. I don’t want to insist more on CSS because it can be a totally new course. There is a lot
to explain and it will only make you very confused if we start talking about positions, importance level of
selectors, key frames and so on.

But you can learn them in your own rhythm and then return here.

Javascript

As w3schools states:

JavaScript is one of the 3 languages all web developers must learn:

1. HTML to define the content of web pages

2. CSS to specify the layout of web pages

3. JavaScript to program the behavior of web pages

Javascript, from a programmer perspective, is much simpler than C#. It is used to enhance the interactive
features of your web page by allowing you to have some processing logic embedded in the header of the
page. You can verify or modify your web page, the HTML code, add special effects, or even write games.

By the way, if you’ve heard of Java, I want to let you know that Java is a completely separate program. It
doesn’t have anything to do with Javascript. Java is a high level programming language like C#, and also
just like C# it’s so called strongly typed. That means you can’t write string myString = 1; You will get an
error, because you can’t assign a number to a variable of type string.

Well, in Javascript you can do it, because it’s not strongly typed.

However, there are a lot more differences. The important thing here for you to remember, is that
Javscript is a programming language used for HTML and for Web and it’s easy to learn.
Javascript can be even easier to learn by using jQuery, a wrapper over Javascript. A wrapper is when
someone takes an existing code and writes some other code that makes use of the initial one and adds
more features. It was also designed to make Javascript development tasks much easier so it will reduce
our development time significantly.

Let’s see some basic jQuery examples:

In the above example <script type=”text/javascript”> represents a placeholder where a jQuery code can
be written. So, if you need to write jQuery inside a html page, you must put it inside a script node.

On the next line $(document) means we are selecting the current document, the current web page and
by $(document).ready it means that when the ready event is happening, which happens when all the html
has been loaded, the .ready event body is executed.

So this is how a Javascript code looks like.

You can even assign CSS properties from Javascript. Assuming you did what I told you, learning CSS and
then returning to this course, I will now show you how easy it is to change the background color of all my
paragraphs from current page.

However, Javascript should not be used for this. It is usually used to make requests to a backend or to do
things that are impossible to do in CSS.

To make requests we create a so called Ajax request. The syntax looks like this
This will just send some data to a URL, the route assigned to one of your controllers and waits for a
response. This response can be a valid one or an error and you can treat them differently.

One real like scenario where you’ll use this, can be, for example, if you want to populate a html table with
some data existing in the database. You make an AJAX request to a URL responsible with retrieving that
data and in the success method of your Ajax request, you append data to your HTML table.

Another example. You have a button in a page, which is used to delete a row. When clicking it, an ajax
request is triggered and inside the data property will have the unique identifier of the row you want to
delete. The backend deletes it and outputs the success result (In the case you don’t send the unique
identifier, the backend won’t know what to delete and it will output the error result).

We’ll learn more about this latter in the course when we’re going to write ajax requests for our
application.

Summary

There are 2 ways of summarizing this chapter.

If you followed what I’ve said, to use the external links to learn more about the technologies presented
here, you should be able to create a HTML page, style it and add a bit of Javascript into it. Basically to build
a very simple web page without any interaction with the backend. That’s what a frontend developer does.

If you just looked over this chapter, without learning anything else, you have an idea about what are
HTML, CSS and Javascript and what they can do for a web application. However, you can’t use them to
create an entire web page that can be used inside a web application.
If you feel you’re in the 2nd category, I recommend you to look over the links again. It will help you latter
in the course when we are going to build our web pages.

First Steps With Our IDE

Solution, Projects And The Right Architecture: using the magical pen again

Every project starts with the architecture. You have to think of how many users the system should support
simultaneously, if it’s going to support multiple databases at once, if it should be scaled on multiple servers
and so on.

However, to simplify things and in the same time to have a modern architecture, we’re going to use 4
layers for our application: the frontend layer, the models layer, the management layer and the data access
layer.

The Frontend layer communicates with the Management layer and this one communicates with the Data
Access layer. The Models layer or Data Contracts layer can be referenced in all layers, because it is
responsible with sharing classes across the application.

The Model layer is the simplest one, holding only data, not doing any processing. Here we will have all the
classes for our application, Movie, Review, Category and so on. These classes will be used to send data
between layers.

The Frontend layer is responsible with serving our HTML pages, CSS and Javascript files. It also holds our
Controllers which calls the management layer.

The Management layer has all the necessary logic of our application. Anything that must be done between
Frontend and Data Access layer, is done by this one.

The Data Access layer sole responsibility is to store, retrieve, update or delete data from the Database.

Let’s start using our IDE to create these layers.


One Step Closer: creating our digital project

To create a new project in Visual Studio go to File > New > Project and choose Web from Installed > Visual
C# from the left pane. In the right pane choose ASP.NET Web Application (.NET Framework). Give it
MovieManagement.Web name and choose MVC from the list. Be sure you have Web API checked.
In the right part you can see the Solution Explorer, which is a pane showing all of your projects from
current solution. If you don’t see it, go to View from the menu and click on Solution Explorer. Let’s delete
the Models folder because we won’t use it. If you expand Content and Scripts folders, you should be able
to recognize some files. Exactly. CSS files are placed in the Content folder and Javascript files in the Scripts
folder.

Let’s leave everything else like this for the moment. We need to add 3 more projects to our solution.
In the right pane, right click on the Solution name Add > New Project. Choose C# and select Class Library
.Net Framework and name it MovieManagement.DataContracts

Do the same for MovieManagement.Management and MovieManagement.DataAccess.

Our solution is complete now, but we don’t have any reference between projects. As I said, Frontend will
communicate with Management and DataContracts, Management with DataAccess and DataContracts,
and DataAccess with DataContracts.

Expand the .Web project, right click on the References node and select Add Reference. Select Projects in
the left pane and select DataContracts and Mangement.

Add the right references for the rest of the projects. (Management: references DataContracts and
DataAccess; DataAccess: references DataContracts).

We have everything we need now. In the next lesson we will take a break from our solution and talk about
common programming keywords and what they mean, because you are going to hear them a lot in the
future.

One last thing to do before that. Hit CTRL+ Shift+ b or F6 to build our solution. You should receive a build
succeeded message in the bottom left corner.
Few Programming Terms Explained: you will always hear them

Algorithm – one or more methods written to achieve a specific goal (ex: I’ve wrote an algorithm for sorting
lists)

Debug - the act of investigating and fixing bugs

Bugs – problems that can appear in your application

Comment – text written by the user and it’s ignored by the compiler. It is often used as side explanations
for the written code. In C# can be written using double / (ex: //this is a comment)

Instance – A new object. If you have for example the class Human, creating an instance of that class looks
like this: var myHuman = new Human(); myHuman is the variable holding an instance of class Human

Invoking – Just a synonym for calling (ex: You should invoke that function before this condition)

Condition – A rule that can have 2 outcomes. If true do this, otherwise do that. (ex: If ( a > b ) { //do this
} else { //do that }, a and b being 2 integer variables)

GUI – general user interface, it refers to the frontend

JSON – a format for transmitting information between locations which is based on Javascript.

API – a set of controllers, each one respecting the REST principles

REST – representational state transfer, a complicated name for something very simple. It is a software
architectural style that defines a set of constraints to be used for creating APIs.

Loop – a piece of code which keeps running until a certain condition is fulfilled (ex: for loop, while loop)
for(var i=0;i<100;i++) { //do this } while(i<100){ //do this }

Array or List – a type of value containing a sequence of other values

DLL file – a compiled C# project


Nuget – a server containing a lot of commonly used DLLs

Refactoring – the act of optimizing an existing code, making it simpler to understand and to read

Linking The Database

We created our database using SQL Server, but we can’t use that directly. We need a simpler way of
accessing it from Visual Studio. In order do to it, we need to add 2 references inside our DataAccess
project: a reference to Entity Framework which we’ll get from NuGet and another reference to our
database.

To add the nugget reference, right click on DataAccess project and go to Manage NuGet Packages. Make
sure Browse is selected in the window that just appeared and search for EntityFramework. Click on it (the
latest version at current time is 6.2), latest version is chosen by default and click install. Click Ok or Accept
whenever you’re asked.

Not let’s link our database with the C# project.

Right click on the DataAccess project’s name > Add > New Item. Choose Data from the left pane and
ADO.NET Entity Data Model from the right one and give it MovieDB name. By the way, if you can’t see
ADO.NET Entity Data Model it means the project you created is not using the right .NET Framework (you
might have selected .NET Core instead of .NET Framework 2 lessons ago). If that’s the case, close the
current window, select the project and delete it. Return to One step closer: creating our digital project
lesson and re-create it (don’t forget to add all the references again).
Let’s get back to linking our database. So you gave it MovieDB name and another window appeared on
screen. Select EF Designer from database (should be selected by default) and hit Next.

In the next screen click on New Connection and choose Microsoft SQL Server if you’re asked.

Fill Server name field with the right naming. It is the same used when connecting to SQL Server
Management Studio. If you followed this tutorial step by step it should be .\SQLEXPRESS.

Make sure Windows Authentication is selected and under the Connect to database box, select your
database, which should be called MovieDB.
Hit Test Connection button. If you received an Ok message, click Ok button.
Hit Next. Select Tables and hit Finish.
A diagram with your database should appear and if we collapse everything and go to our DataAccess
project, we can find a file with .edmx extension.

Expanding that, we discover some newly added files. The .tt files are templates used to generate other
files. That’s why if you expand them as well, there are some .cs files under each one. Expanding
MovieDB.tt we discover our tables, translated to C# classes. Open them to see how they look.
By the way, you can write down some keywords found in these files, like partial, virtual, ICollection and
search for related information on google in your free time to find out more about them.

If we changed our SQL database for whatever reason, we must update our classes from C#, but don’t
worry, we don’t do it manually. Double click on .edmx file. Right click somewhere in the diagram window.
Update model. Go to Refresh tab. Select Tables and hit finish. Click inside the diagram window and hit
CTRL+S to save the file.
Build the solution using F6 or CTRL+Shit+B key combination. You should receive build succeeded message.
If not, it means you did something wrong.

Elegant Way Of Writing T-SQL Queries: lambda expressions

Remember SQL queries?

For example, this one selects all movies from our database

But in Visual Studio we don’t have the same query editor. We must write our queries in a different way.
We will be using LINQ.
LINQ is a bit complicated to explain it at the moment. But remember the name. If you hear it, remember
that you can use to execute query over a specific set of data. In our case, this set of data is our database.

The previous query can be written in LINQ like this:

moviesTable.Select(a=>a);

If we want to select only some specific columns we write it like:

moviesTable.Select(a=> new SomeClass { Title = a.Title, Rating = a.Rating });

I think it’s better if you see a real example with this. Let’s build our DataAccess layer. Each file responsible
with database interactions it’s called repository.

Let’s start with a simple one, CategoryRepository.

Right click on the DataAccess project. Add > Class and name it CategoryRepository.

Let’s add a method to return the list of categories.

public List<Category> SearchCategories(){

We could add parameters to be used for filtering like: name or how many results to retrieve, but let’s not
go too deep into details now.

We need the database context, which can be created like this using (var dbContext = new
MoviesDbEntities()){}

And then return the actual list from the database.

Return dbContext.Categories.ToList();

That’s it!
Let’s add 4 more methods here: add, update, delete and get category by id.

Starting with the Get method. It returns the category and we need a parameter of type GUID to identify
the category we want to retrieve.

Using the FirstOrDefault LINQ method, we search for the first category with its Id equal to the parameter,
categoryId. If nothing is found, category variable will be null.

AddCategory. We need a parameter of type Category, the new one that we want to add.

And in our dbContext.Categories table, we call the .Add function with our parameter.

The last thing we need to do is to save our changes, so we need to call dbContext.SaveChanges() method.
Remember that for all write type queries (update, save, delete) you need to call .SaveChanges. Only when
you call this method, your actual code is sent to the database.

Let’s create DeleteCategory. We need a parameter of type GUID, the unique identifier.
First of all, we need to retrieve the category from the database, check if it exists and if that’s positive, we
delete it.

We’re checking if category != null. Remember that FirstOrDefault can also return null? That’s why we are
doing this check here.

Inside the if condition, we call the Remove function on Categories table.


dbContext.Categories.Remove(category);

The last thing we need to do is to save our changes, so dbContext.SaveChanges().

And the last one, Update category. It’s similar with the save method.

We are searching for the category with the same GUID and if it exists, we set the name to be the one
received as a parameter. You can update multiple fields here, but we have only the Name column in our
Categories table. For example, when building the MovieRepository.cs class, you may want to update some
other properties as well, like: Rating, Length, Title and so on.

And this is our first repository. We checked if the category exists inside our delete and update methods.
However, there is another option, we could have thrown an exception if it didn’t exist. Let’s leave them
like this but make sure you read about C# exceptions.

You can see we have some duplicate code. We are creating a new context in every function. What if we
create only 1 for all of them? Also, think that we are going to add more repositories and it will be very
annoying to write same thing over and over again.

So we need a solution, we need to make some optimizations. This is called refactoring. In order to do it,
create a new class in a separate file called BaseRepository (right click on the DataAccess project > Add >
Class). This will act as a base class for the rest of our repositories, holding common information.

One common information is this dbContext, so let’s add a property for it. protected MoviesDBEntities
DbContext = new MoviesDBEntities();
Let’s return to our CategoryRepository now. After class name put a colon and write BaseRepository. This
means the CategoryRepository inherits everything that has not private in front of it from BaseRepository.
Our property DbContext, has protected in front, so we are good.

Private, protected and public are called access modifiers. Private means it is accessible only from that
class, protected means it is accessible from that class and from the classes that inherits that class and
public means it is accessible by anyone.

Let’s remove all the usings from CategoryRepository, and use the DbContext property directly.
By the way, to format your code, press Ctrl + K + D.

Congratulations. You finished your first repository.

Pop Quiz 5

1. How can you write following query in LINQ?

a.

b.

c.

d. None of the above

2. How can you write following query in LINQ ?

a.

b.
c.

d.

3. How can you write following query in LINQ ?

a.

b.

c. None of the above


4. How can you write following query in LINQ ?

a.

b.

c.

d. None of the above

Summary

This section was a bit harder than the previous ones because of all the information presented. If you feel
you did not understand it fully, please watch it again.

You’ve learned about project’s architecture and what’s the right approach when building an enterprise
level software application, about Entity Framework and how can you link an SQL database with your C#
project, about LINQ and how to translate T-SQL queries into C#, about how to write your own Repository
and last but not least, about few programming terms you are going to hear a lot.

The Management Layer

What is mapping

It’s a mathematical concept. It establishes a correspondence between 2 distinct data models. If you have
class A and class B, a mapping from A to B, means moving data from an instance of class A to an instance
of class B. It’s often used when sending information between different layers of your application. In our
case, the DataAccess layer can retrieve all information from a table, but we don’t want sensitive
information like passwords at the other end, on the UI. I know we don’t have now, but if you extend the
application to have user related information, you must not retrieve an actual user password to frontend.
It’s a major security breach. That’s why we define another class which will contain only the user
information we need for the UI or for other layers, like management layer and return that one from our
API’s actions.

Data Transfer Objects ( DTOs ): MovieDTO

Let’s define some data contracts that we are going to use for mapping from and to data access entities.
Right click on the DataContracts project and add a new class. Let’s name it MovieDTO. Make sure you add
the public access modifier in front of the class keyword if you don’t have it.

We are going to add a few properties: like title, release date, length, average score, category name, rating
and ID. It will be pretty like the DataAccess one, but as a best practice it’s better to define another one to
communicate between layers instead of using the generated one.

This is our MovieDTO. It has a bunch of properties here, each having the get and set keywords, meaning
you can retrieve and assign a value to them. You can have also have something like { get; private set; },
meaning you can assign value to that property, only from the current class, due to the private access
modifier (I told you about access modifiers few lessons ago).

You need to create the other ones, CategoryDTO and ReviewDTO.


MovieManagement

Right click on the Managemnet project and add a new class. Name it MovieManagement and make sure
it has the public identifier in front of it so it will be accessible from the other layers.

Management classes are responsible with holding all the logic necessary to process the data retrieved
from the DataAccess layer.

Let’s create the Search function. By the way, at this point you should have created the MovieRepository
into the DataAccess project as I’ve told you. Without it, you won’t be able to continue this lesson.

The search function should return a list of MovieDTO we just defined.

At this point, MovieDTO was not highlighted. That means Visual Studio was unable to find that class, even
if we defined it. That’s because it was defined in a different namespace (actually, in a totally different
project). In order to fix this, we need to add a reference to that project, but we already did this at the
beginning of our lessons and the other step is to tell Visual Studio which namespace to use. 2
You don’t have to write it manually. Just click on MovieDTO and press CTRL + . on your keyboard and click
on the first option which should contain using and the namespace’s name. This will add a new using
directive at the start of your file and now Visual Studio will recognize everything from that namespace.
In the body of our search method we need to get the result from MovieRepository which is defined in the
DataAccess layer, process it by mapping to our MovieDTO and return it.

So we need to instantiate the MovieRepository class and put it inside a variable. If Visual Studio it’s unable
to find it, and it shouldn’t be at this point. Select it, CTRL+. and add the using. Call the Search method from
MovieRepository and put the result inside a variable.

Now we need to map that result to our needed result. A list of MovieDTO.

First, we need to define this type. And then, for each item inside the search result, we map it and add it
to our list.

At the end of our method we return our list.

Let’s create the rest of the methods: get one movie instead of an entire list, delete, update and save.
The Get method, returns only one movie and receives an ID as parameter. We need the repo again. We
call the Get method from repo and put the result inside a variable. We map it to a MovieDTO class and
return it.

The Delete method. Returns nothing and receives an ID as parameter. We need the repo again. This time
because we don’t return anything and we don’t have to process the result, we just call the repo delete
method.

The Save and the Update methods. Those 2 are similar and that’s why I am thinking on creating a
combined method which we are going to call it AddOrUpdate. Returns nothing and receives a MovieDTO.
We need the repo again.

Here’s the entire code. Take a look at it, try to understand and then look at my explanations.
In both cases, Add or Update, we need a model to send to our repository. That’s why we defined that
model outside of the if clause (if we were to define it inside the true branch of our if clause it would have
been available only inside that branch – same for the else branch).

When assigning the Id to my movy variable, I had to write an inline if there. That translates to: if movie.Id
is different than Guid.Empty, then put movie.Id inside the Id property, otherwise create a new GUID.

After creating the movy variable, I am filling the CategoryId property of the movy object. Here’s a bit tricky.
Imagine this: you are looking over the website and you need to update a movie by assigning it a new
category. On the UI, you have a list of existing categories you have to choose from. If Ids were shown to
you, you would have understood nothing. That’s why every dropdown (list of countries, list of movies, list
of cities and so on) contains strings, in our case the category name. After the request is done, in the
backend part of our application, we receive a category name, but we cannot assign that to our movie, we
need the Id of that category, because our property (and database table’s column) is CategoryId. So, we
need to search for the category with that name to get its Id.

Let’s add the GetCategoryByName method into the CategoryRepository.cs class from the DataAccess
project.
We are transforming our strings to lowercase and then compare them, because we want string like
dRama, Drama, dRAMA, DRAMA to match.

Back to our method from the Management project. After assigning the category Id, we have to see
which method we call, the add or the update?

One way to check that is to verify the Id property. If the Id is different than Guid.Empty, it means the
model is new and we have to add it. Otherwise we need to update it. Why this works? Because every
movie saved in our database, must have an Id, because it’s the Primary Key of our table.

And that’s it!

One last thing before finishing our MovieManagement class. As you can see, we are instantiating the same
repository multiple time. We need to refactor that. Instead of doing like that, we could use a property.
So, let’s define the MovieRepository property.

We define it as private because it is going to be used only inside this class. It’s a best practice to name our
private properties with an underscore at the beginning.

Let’s replace the repository usage with our property.


Hit CTRL+SHIFT+B to check if your project builds.

Ok. And this is our first management class.

Your homework is to do the same for Category and Review. Try to do them by yourself first and then look
below.
Pop Quiz 6

1. What is mapping?
a. A type in C#
b. An operation to move values from one model to another model
c. A layer responsible with application logic
d. None of the above
2. How can you check if a GUID has value?
a. Check if its value it’s different than Guid.Empty
b. Check if its value it’s different than null
c. Check if its value it’s different than 0
d. None of the above
3. How can you map a List to another List?
a. Iterate over each element from the first list, create a new object of the second list type,
put values in each object’s properties and add it to the second list.
b. There’s no way you can map a list to another list
c. None of the above
4. How can you make Visual Studio understand what’s inside another namespace?
a. If that namespace if it’s inside another project, add a reference to that project
b. If the namespace it’s in the same project, just write the using clause at the beginning of
your file
c. If you don’t have the using written, hit CTLR+ . combination and select the using
namespace_name option
d. None of the above
e. All of the above

The API

What Is An API

An API is like a template for how a software application can be used: it defines what operations are
available to the user and what types of data those operations can accept and return.

It very simple terms can be explained as a language that users use to communicate with your application.

A TV remote can be an API for the TV. It has different operations implemented like: volume up, volume
down, switch to a specific channel and so on and the person using it calls these commands.
Actual examples of APIs: Facebook API, Twitter API, Maps API and so on. For example, whenever you see
the buttons: Connect with Facebook or Connect with Google, these ones are calling an API in the back.

Let's head to the next chapter to find out more about most common programming keywords related to
API.

Some More Programming Terms Explained: related to APIs

Request – the action done from the user interface that calls an API in the back. Going to profile page on
your Facebook, it’s one or more requests to an API, which returns the profile information

Request Header and Request Body – Information that can be included either in the header or in the body
of a request to be sent to the API. Header is responsible with common information like: the format of data
sent, authorization if any, cache and many more. Body is responsible with user information: data sent by
the user to the API.

HTTP methods: Request can have 4 states: GET, POST, PUT and DELETE. Those are called http methods.
Get it’s used to retrieve information, POST to save information, PUT to update information and DELETE
it’s self-explanatory.

JSON – the most common data format used to communicate with an API. Request is sent in json format.

API Action – Destination of a specific request. Each request calls an API action.

API Route or Endpoint – When calling an API, you need to specify a path in order to identify the API action.
That path represents the route of an API action. It’s also called an endpoint.

Action result – The return of an API action. What is sent back to the client.

Model validation – Validation rules for the request received. Example: Max string length, an int greater
than 0, string to be an email address and stuff like this. A great example for this one is when you are trying
to create an account somewhere. There are a lot of validations in place: the email has to have an email
format, the password must be between 6 and some other number characters, the password must contain
one upper case letter, one lowercase and so on. This is done both on the UI side and the backend part
using model validation.

Mock data = Test data. Instead of returning or using real data, we make use of mocked data.
Our First API

Ok. You know everything about APIs. I’m joking! But don’t worry, I am going to help you with building
your first API. In fact, this is the best way of learning programming. Having a code or someone else as an
example.

Right click on the .Web project and select Add > Area. Give it API name a press the enter key. This area
will contain all our APIs controller. We did it this way, because Visual Studio will automatically create a
route rule for us. For example, all requests coming with an url similar to api/a controller/an action will
search for the controller and for the action in this area. However, I want to show you how you can
create routes manually. So, go to APIAreaRegistration.cs file and delete the default route.

Another thing we need to do before starting our API is to make sure the project has what it needs to
communicate with all the other layers. Because our DataAccess uses EntityFramework and talks with a
database through a connectionString property (that has been set automatically when we added .edmx
model) we need to include EntityFramework and set the same property in our web project. Sounds
strange, but the .Web project is the starting point of our application and this is the one which tells to the
other layers, which database to use, even if it does not talk with it directly.
Let’s do this. Add the EntityFramework reference from Nuget Manager, by right clicking on the .Web
project and selecting Manage NuGet Packages. Be sure you add the same version you added into the
DataAccess project.

Go to App.config file from DataAccess project, copy connectionStrings property and paste it into
Web.config file from the .Web project (make sure you paste it in the right place).

App.config (DataAccess project)

Web.config (Web project)

Now let’s define an API controller for Movies.

Right click on the Controllers folder and add a new controller. Select Web API 2 controller–empty and
name it MovieController.

Set the [RoutePrefix(“api/movies”)] on the controller and let’s define our actions.
First one will be the Search action which returns a list of MovieDTOs, so:

As I thought you before, we need to include MovieDTO namespace here. Hit CTRL + . and select the first
option, which should be using namespace name.

We need to call the management class, so let’s define a property of type MovieManagement because we
are going to use it multiple times. (remember when we had to refactor our MovieManagament and
instead of instantiating the repository multiple times, we stored an instance of MovieRepository into a
property?)

Private, because it’s going to be used only inside this controller.

Ok, back to search action. Let’s add the route for it with the name Search. In this case, the full URL will be
something like local_url_with_port/api/movies/search

We are going to keep it extremely simple, by just calling the management search function without any
other logic here. And then return the result.

One last thing here. We need to set the Http method for this action. Add the [HttpGet] attribute.
And this is our first action. Let’s do the rest.

Delete. Returns nothing and receives the ID of the movie we want to delete. As attribute we set
HttpDelete and as for the route, I guess ‘delete’ would be very good.

And we just call the management layer as I said before.

One last thing before going to the other methods. As you can see we receive a parameter here and at the
moment, the full route would look like: local_url_with_port/api/movies/delete?id=some_id.

We can make it a bit more beautiful. To follow the REST best practices, we can remove the delete naming,
because the type of action it’s given by the HTTP method, which, in this case is Delete and instead of that
put id in curly braces {id}. The text between the curly braces must be the same as the parameter name. If
the parameter name was foo, we would have put foo between the curly braces. The route will look like
local_url_with_port/api/movies/some_id.

We can have another method with same route, but the HTTP methods must be different for the routing
system to identify the correct action.

Let’s make the Get method next because it’s similar. We have the same route, only the HTTP method
being different. It returns a MovieDTO.
The Update method is pretty similar too. The HttpMethod we are going to use it’s HttpPut.

Returns nothing and it receives another parameter of type MovieDTO. However, we need to specify that
movieDTO parameter comes from the request body, so before the parameter we set the attribute
[FromBody].

Route it’s empty in this case, because we don’t need another parameter of type GUID. We already have
the Id property inside our MovieDTO parameter. Full URL will look like: local_url/api/movies

And the Save action it’s the same as the Put action. The only difference it’s the HTTP method, which is
going to be HttpPost.

And yes! I’m happy to say we finished your first controller. Simple right? Don’t worry if you feel a bit
overwhelmed now. There are a lot of new things and it’s natural to feel like that. You’ll get used to them.

Considering we have the Id 20860132-fc43-4b49-8c02-cded207f407f, routes for our MoviesController are:

Search – local_url/api/movies/search

Get – local_url/api/movies/20860132-fc43-4b49-8c02-cded207f407f [HttpGet]

Save - local_url/api/movies [HttpPost]


Update - local_url/api/movies [HttpPut]

Delete - local_url/api/movies/20860132-fc43-4b49-8c02-cded207f407f [HttpDelete]

Your homework, as usual, is to do the controllers for Reviews and Categories.

Good luck!
Debugging Our Simple API

UI is not mandatory to test our API. We can use software like: Postman or Fiddler which allows us to create
requests. However, GET requests can be tested by just accessing the URL in your browser.

Let’s download postman. Go to google and type download postman. Go to getpostman.com (by the way
by just going to this page a get request is done in the back). Download the app. Open the setup and let it
install. Create an account or Sign in with Google.

Leave it open and return to our Visual Studio solution. Right click on the .Web project and select ‘Set as
startup project’. Hit F5 on your keyboard or click on the little play button from top.
local_url

It will open the project in your browser, and you can see it has a default design and some default elements.
We are going to test the search action from our MovieController class, because it will be the only one who
won’t return an exception. It is returning a list of elements existing in our database and if there’s none, it
will return an empty list, compared to the other methods where we need to specify a unique identifier
and we don’t have any now.

Remember the route? It was api/movies/search so let’s add this at the end of our URL. Copy everything
and paste it into Postman. Make sure the selected HTTP Method is GET and click the send button.

To debug the code you wrote, we need some breakpoints in our application.

A breakpoint is like a point where Visual Studio should stop the execution of the program until the
programmer is telling to resume it.

To add one, go to Visual Studio, in the method you want to debug, in our case Search action from
MovieController and click in the left side of the first row from Search action’s body. A red circle should
appear on screen.

Now go to Postman and click Send again. As you can see, that row is now highlighted because our
breakpoint was hit.
When debugging an application, you have 3 options to tell Visual Studio to resume its execution plan.

F5, F10 and F11

If you press F5 it will jump to the next breakpoint you set. For example, if I put a breakpoint all the way
up to DataAcess layer and press F5, it will jump to that breakpoint. Now I don’t have any other breakpoint
set and by pressing F5 it will finish the execution plan.

F10 is for going to the next row. However, as we have only 1 row, I can press F10 2 times and then it
finishes the execution plan.

Last Options is stepping into a method. You can do that by pressing F11.

After stepping over a row, you can hover over previous variables to see their values. This is very useful in
cases when you don’t know why a variable has a wrong value or when you want to see the result of a
method call.

And this wraps up the introductory lesson for debugging. I recommend you play with it because you’re
going to use a lot in your career. There’s no code without bugs and to fix bugs you need to learn how to
debug your application.

What I’ve shown you it’s just the tip of the iceberg. There’s much more to be discovered when talking
about debugging an application, but you can’t just learn everything from the beginning. You must find
out in your own rhythm.
Pop Quiz 7

1. What is JSON?
a. An open standard file format, derived from JavaScript usually used to communicate with
an API
b. The return of an API action
c. An HTTP Method
d. None of the above
2. What HTTP method is used for updating data?
a. GET
b. POST
c. PUT
d. DELETE
3. What HTTP method is used for retrieving data?
a. GET
b. POST
c. PUT
d. DELETE
4. What HTTP method is used for saving data?
a. GET
b. POST
c. PUT
d. DELETE
5. What is an Endpoint?
a. The part responsible with holding a set of data sent by the user to the API
b. The route of an API action
c. Test data used to debug your API
d. None of the above
6. When debugging how can you step into a method?
a. By pressing F10
b. By pressing f11
c. By pressing f5
d. None of the above
7. When debugging how can you step over a row?
a. By pressing F10
b. By pressing f11
c. By pressing f5
d. None of the above
8. When debugging how can you continue normal execution flow (it will stop at another
breakpoint if any)?
a. By pressing F10
b. By pressing f11
c. By pressing f5
d. None of the above

Summary

In this chapter you’ve learned about APIs, routing, HTTP methods, JSON and how to debug your
application. There was a lot of information and I know it may seem a bit confusing for you at the moment.
That’s why I gave you an assignment to create the other controllers by yourself.

In the next chapter we are going to learn how to create our HTML pages and how to call the API we just
coded.

The Frontend Layer

What is Bootstrap?

You've learned about CSS. You might have loved it or not.

However, styling a website is very subjective. What I like, you may hate. That's why we won't create our
design from the ground up. We are going to use a free theme we can find online. And this is great because
I will also show you how you can style your website by just adding a theme.

However, I just realized I haven't told you what Bootstrap is. Bootstrap is a collection of CSS styles pre-
built, free, that anyone can use. That means there are already a lot of CSS classes useful for text sizes,
button colors, pop up boxes, positioning and so on. There are a lot of themes based on Bootstrap and
that's what we are going to use to ease our development.

Download this theme: https://github.com/BlackrockDigital/startbootstrap-sb-admin-2/archive/gh-


pages.zip

Now let’s look for index.html page from the downloaded theme. It usually contains all the necessary stuff
for our theme to work properly.

I found it under pages folder. Open it in an editor. I’ve used Visual Studio Code. You can use whatever you
like, Notepad, Notepad++, and so on.

We look at the head tag and see that it includes some CSS files. We need to add them in our Layout.cshtml
page.
Why in Layout? We are using what’s called MVC and Layout.cshtml it’s like a template that is rendering
behind every HTML page from our application. To be 100% right, Layout is like a parent container and
each HTML is render inside this container.

This line here RenderBody is responsible with rendering the <body> tag of our HTML pages. If you
remember each HTML page must contain html, head and body tags, but because Layout is like a parent
container, we add those tags in layout and each of our HTML pages starts directly with its content.

Also, you know that HTML pages have the .html extension. In MVC HTML pages are a bit special and they
are having .cshtml extension. Remember that C# files have .cs extension? Well MVC’s HTML pages, which
are called Views by the way, are a combination of C# and HTML. Writing C# inside a .cshtml file is not a
must, but you have this option and sometimes it is useful.

MVC – stands for Model, View, Controller. I’ve already told you what a View and we are going to talk
about Model and Controller in the next lesson. These Controllers are different than the ones we wrote for
our API. Code structure is similar, but they are serving a different purpose.

Ok. Back to adding our theme.

In the .Web project let’s create a folder Theme and inside this one add 3 new folders, one called js, the
second one called css and last fonts.

Back to our index.html theme page and let’s see what we need to add to our folders. So bootstrap.min.css,
metisMenu.min.css, sb-admin-2.css, morris.css and font-awesome. Each at a time. Remember to add
fonts when reaching font-awesome part. We follow the path from where they are inserted in index.html
page.
When finished with the css and fonts files, scroll to the bottom of index.html page and look for the js files.
Do the same thing.

Ok. We added all the necessary files. Now we need to include them in our Layout page. Open it and
delete everything that says Styles.Render or Scripts.Render. Those lines include some specific scripts or
styles that are defined in your BundleConfig.cs file under App_Start.

Open it.
BundleConfig is just a way of grouping css and js files and instead of writing all of them in the
Layout.cshtml, you can just call the Styles.Render(“name_you_set_in_bundle_config”) and it will include
all the files defined in the BundleConfig file.

However, let’s add them manually, directly in Layout. You can play with BundleConfig on your own.

You can copy-paste from index.html, but make sure you replace it with the right path. CSS files in the head
tag and JS files at the end of the body tag.
Ok. We finished with including all our css and js files. This is first part you need to do when adding a
theme.

Now we need to look at the structure of index.html. (because each css file can work only on a specific
HTMl structure; remember the .someClass .anotherClass {} selector?)

If we look at the body tag there’s a div with an id called wrapper. We must add that one too, instead of
our container. And move everything inside of it, as shown in index.html. In the same, we observe that
there’s another wrapper for pages. Let’s add that one too, just above our RenderBody call.

To test our theme, let’s replace our navigation with the one from index.html.

CTRL+ SHIFT+B to build our application. It should not have any errors.

Ok. We need to run our application to see the changes. Right click on the .Web project’s name and select
‘Set as startup project’. Remember that when debugging we had to press F5, if we just need to run it, we
can press CTRL+F5.

Wow! And it works. Let’s clean the navigation by having only the dashboard link and replace it with one
of our actions.
To create a path to one or our actions, we use what’s called a helper in MVC. In our case Url.Action. So, in
the href attribute write @Url.Action, which has 2 important parameters:

- First one is the action’s name, in our case Index


- And the second one is the controller’s name, in our case Home

There are a lot more helpers in MVC, like Html.ActionLink, RenderPartial. You can search for MVC helpers
on google and read whatever link you find interesting.

CTRL+F5 and let’s see the results.

Great! Before wrapping up this lesson let’s use another helper. I don’t like we have the navigation in the
same file with Layout, because it might get big in an enterprise application. Let’s create another view
under Shared folder. Name it _Navigation and make sure ‘Create as partial view’ is checked. This tick says
to the MVC project, the page we are creating must not use Layout.cshtml as a template.

Move our navbar in the newly created file. Go back to layout and instead of what was written, include our
new partial view by writing Html.Partial and its as parameter.

CTRL+F5 again and see the results.

Great! This lesson was a bit longer than expected. Take a break and return the next one!
Using Our Frontend Project: First MVC Controller

Controllers again, you might wonder. Well, not really. We wrote those Controllers that are calling the
Management layer, which in the end calls the DataAcess layer and retrieves or saves data to our database.
Those were API controllers.

Now, we are going to focus on MVC controllers, which are responsible with retrieving our Views. Let me
show you one to see what I am talking about.

By opening HomeController, you see we have 3 actions here Index, About and Contact. By going to Views
folder, under Home, you see we have same 3 views. Each action returns a view with the same name, if
not mentioned otherwise. (you can specify what to return, but it defaults to a view with the same name).

So, under the Views folder there must be a folder for each of our controller. Don’t worry, Visual Studio
will create it automatically if you add the controller in the right way.

MVC controllers are responsible with retrieving our Views and API controllers are responsible with
validation and calls to the upper layers. However, this is not a rule. You can use MVC controllers for all the
cases, but most enterprise applications have an API and that’s why I chose to do it like this, for you to get
used to this type of architecture.

Ok. Let’s create our first MVC controller.

Right click on the Controllers folder (make sure it’s the right one) and click Add > Controller. Select MVC
Controller – EMPTY and name it MoviesController.
We need a page which displays a list of movies and another page to display details of a movie. So, we
need 2 actions. One, called Index, which it’s already created by default and we are going to use that for
the list and the other one Details which must receive a unique identifier as parameter.

And when returning the View we need to send the Id. Here we can send much more if we need. We just
define a class, a model, which stands for the M from MVC and just return it here.

We’ve sent it, because when the page is opened, we must make an API call to retrieve the actual data for
that Id. We are going to do this in our next lessons.

The view for our actions can be added automatically. Right click on the action’s name and select Add View.
Make sure Create as a partial view is unchecked, because we want this page make use of the layout
template. Do the same for Index action. Now, when looking under Views>Movies, you will find 2 views
there.

And, surprisingly, this is our first MVC controller. Your homework is to do the rest: CategoriesController
and ReviewsController.
Pop quiz 8– CRUD

1. What does Url.Action?


a. Builds an entirely <a> tag
b. Build the url for an action
c. None of the above
2. What is Layout.cshtml?
a. A template for all of the other pages
b. A normal html page
c. None of the above
3. What is a View?
a. A file with .cshtml extension which can contain HTML,CSS, Javascript and C# code
b. A file which cannot contain c# code
c. A file without a template
d. A partial view
e. None of the above
4. What is a PartialView?
a. A view without a template having .cshtml extension
b. A view without a template having .html extension
c. None of the above

The Entire Flow Explained Again: the magical pen

Let’s see the entire flow really quick.

Users see our Views, which are retrieved by our MVC controllers. Together with the API, this forms our
frontend layer.
Going to the backend layer, from the same views, an API request is sent, its goal being saving or retrieving
data that will show up inside our views. API then sends the received data to the Management layer, which
processes it and then sends it to the DataAccess layer. DataAccess is the ONLY layer which can talk directly
with our database and you must keep it like that. Also, the DataAccess project must be referenced ONLY
inside the Management project.

The API and the Management layers share a common code, the DataContract project. This one can be
shared with any other layer if needed, so feel free to play with it.

First View: the ‘list’ page

We have everything set up, except our Views. Let’s start with creating a list page for Movies.

I’m thinking at using a table-like structure. Let’s go through our theme to see if there’s any table design
we can use.

I found this one:

Copy paste the html to our Index.cshtml page under Movies folder. And delete all rows except the first
one because we’ll use that as a model to know how to add data to our table.

Let’s change the header to something similar to our needs, like: Movie Title, Category, Rating, Score and
an empty column, used for placing different buttons like delete, go to details and so on.
Let’s go to Navigation partial view and add a new menu option for our Movies list.

Hit CTRL+F5 to see your page.

Ok. Now let’s add some actual data into our table. To do that, we need to create an Ajax request to the
search action from our API.

I’m going to use the same file for the Javascript code, but you can do it in a separate file if you want. (don’t
forget to include it in the HTML page if you do)

Because we are using MVC, don’t forget the @section scripts helper. So, we define our script tag inside
the scripts section and then the Ajax request.

The base URL for our Ajax request is the one seen in browser after hitting CTRL+F5 (when deploying on a
public server, you have a domain assigned to you, like google.com and that’s your base URL).

Before filling our table, we need what structure the response has. So, write debugger keyword in our
success function.
Hit CTRL+F5 and open the browser’s debug window by clicking F12. Refresh the page. The debugger will
stop at that row and you can see what’s inside the result parameter (in the right pane, the Watch pane)

By the way, F10 and F11 does the same thing as in C# (stepping over a row and stepping into a method).
The only difference is that for browser’s debugging we use F8 instead of F5, because F5 will refresh the
entire page.

So, it seems we have an array of movies. Let’s get back to our code. We need to iterate over this array and
fill the table using jQuery selectors. Let’s assign an id to our tbody tag and add the results to it.
var newRow = "<tr><td><a href='/Movies/Details?id=" + result[i].Id + "'>" + result[i].Title +
"</a></td><td>" + result[i].CategoryName + "</td><td>" + result[i].Rating + "</td><td>" +
result[i].AverageScore + "</td><td>" + result[i].ReleaseDate + "</td><td><button class='btn btn-default
delete' data-id='" + result[i].Id + "'>Delete</button></td></tr>";

You can copy-paste the newRow variable’s content from above.

Hit CTRL+F5 and see the result.

Great! Our table is now filled with real data.

Let’s code the delete action too. After adding the data to our table, we need to assign a click event to our
delete button. If you wrote the code exactly like me, each delete button has the class delete. So, let’s
assign the click event for that class. We do it in the previous ajax success function, because we want the
click event to become available after adding all the elements, otherwise there won’t be any button on the
page to respond at our event.
We get the id of the movie from the data-id attribute we set previously.

The success function does not have any parameter because the API method for delete returns void.

If the delete was successful, we need to remove that row from our table. In our case the jQuery this
element is represented by the delete button and we need to go 2 levels above to reach the tr.

First parent is the td and the second one is the tr and then call the .remove jQuery function on the table
row element.
We have to define it outside the success function because, the this keyword has a special meaning in
Javascript, a very complicated one to explain it at the moment. You can read about it, but I won’t say you
will fully understand it.

By the way, I’m calling hide first to create a fade out animation and after that, on hide’s callback (when
finished) I am removing the row. You can call remove directly if you want.

Wow! I am very happy for you at this moment. You are now able to say you have built your first web
page from the ground up. It’s a very simply one, but it’s still a web page. Congratulations!

A New View: the ‘details’ page

Let’s create this awesome page too. We will do it very simple by just adding some inputs on the screen.
Oh, and, I am thinking of using it as an update page too. Let’s do this!

We need to add a razor specific line in this document @model Guid. This will tell the View that it receives
a model of type Guid. Instead of GUID, as I already said, it can be a more complex object, like a class.

Ok. We encapsulate everything in a row and each element will have the col-sm-12 class.

By using Bootstrap, a row is portioned in 12 equal columns. And using the col-something class you can
specify how much of the screen that element will occupy. There are multiple col classes like col-xs, col-
sm, col-md, col-lg, each one responsible with a specific resolution. For example, you can assign col-xs-12
and col-lg-3 on the same element, meaning that it will occupy 12 columns on very small displays (col-xs)
like how old phones have and only 3 columns on large, tv monitor displays (col-lg).

Back to our view.


I added text inputs for Title and for Rating so we can edit them and spans for the rest.

Let’s create the Ajax request.

For building the URL, we use the Model of the page (remember that when defining the model you write
it with lowercase m and when using it with uppercase M) which gives us the id of the current Movie. We
could have also got it from the URL, but it’s better and simpler this way.
And this is our very very very very very simple details page.

Let’s add the update button and create an ajax request for it. Ajax will fire when the click event happens.

For this Ajax request we need some data to send to our API.
And on the success event, we can only show a message.

Great! This was our details & update page.

Your homework is a bit bigger than usual. You must style this page, to give it a personal touch.

Besides this you must do the Create page for Movies and all the other pages for Categories and Reviews.

Good luck! By the way, you’ll find a download link for the complete project at the end of this course. Try
to do everything by yourself and after that look the uploaded project.
Pop Quiz 9

1. How can you send data to an API using an ajax request?


a. By adding parameters to its URL
b. By using the JSON.stringify on a model placed inside the data property
c. None of the above
d. All of the above
2. How can you resume execution when using browser’s debugging tools?
a. By pressing f10
b. By pressing f5
c. By pressing f8
d. None of the above
3. How can you assign a value to a span element?
a. By setting the .val attribute
b. By setting the .text attribute
c. None of the above
d. All of the above
4. How can you trigger an action when clicking a button?
a. By setting the .click event
b. By setting the .pressed event
c. By setting the .touched event
d. None of the above
e. All of the above

Summary: your first web application

In this chapter you’ve learned how to create the app’s frontend. You’ve learned what bootstrap is, how
to add a theme to your web application and how to create ajax requests to save and retrieve data. I hope
you are going to do your homework because it’s an opportunity to practice those skills learned here.

The End

Helpful Links: further reading

We've almost reached the end of this course. You will do a lot of searching and researching when coding
and you must know which websites are best for getting the right advice.

If you're looking for a solution, I recommend you adding 'stackoverflow' keyword at the end of your
search. Stackoverflow is probably the biggest forum for programmers and you will find a lot of
information. You can post your question there, but only after you did some research and tried different
solutions, otherwise you will get down votes and probably your question will be closed or deleted. People
will start answering and you can accept the best answer and up vote it. It is very useful. I use it at least
once a day when I need a quick solution for something. You will find almost anything there.

Another great website is w3school, the one you already used when we were at the HTML, CSS and
Javascript lessons. It's full of tutorials and free useful courses and I recommend it for moments when you
want to learn anything new at a basic level.

Another useful tool I can recommend is Youtube for quick tips and tricks and common problems. Even for
interview questions.

And finally, books or learning platforms. Compared to others, these are giving you to opportunity to learn
things on all proficiency levels, in order to boost your job related skills.

So, keep in mind. Stackoverflow for quick solutions and in case you have a question you can’t find a
solution by yourself.

W3school for basic tutorials about common technologies.

Youtube for video explanations to common interview questions and problems and books and specialized
platforms for learning new things from the ground up in an organized manner.

The Enormous Amount of Frontend Libraries

During our course we've used plain ajax requests and manual mapping the result to our HTML. Ok, this is
one option. However, these days everyone uses a frontend library to do this job. A frontend library,
depending on its purpose, usually has auto mapping, auto updating HTML (which is called binding) and
different built-in helpers you can call directly (for example, instead of writing your own Ajax, you just call
a .get or .post method from the library).

A library is a collection of functions and properties having the purpose of simplifying the user workload.

However, each library is different from one another and this is a disadvantage. You must learn something
else again each time you decide to use a new one.

Some libraries let you build even the HTML from Javacript code, which makes them even more
complicated for a beginner.

However, I recommend you looking into Knockoutjs which is not very complicated. Once you master it,
give Angular a chance. Angular is one of the most used one these days.
Course Wrap Up

Congratulations! You finished the course From A Non-Programmer To Full Stack .Net Developer. You
should be able to identify portions from a web application, build your own simple website and change and
optimize an existing one. These steps include running, testing and debugging it.

However, at this point you might not be able to build one without looking over an existing code. Don’t
worry, it’s normal. You’ll get used to it in time. You just have to practice a bit more.

In the next lesson you’ll find a final exam and for passing it there’s a minimum score requirement set to
80 out of 100. If you feel you’re not ready for it yet, watch the course again and practice your searching
skills by looking over the links I told you about in the previous lessons. I know I can’t verify you, but please
remember that each question is scored with a 5. If, at the end, by summing all answers you get less than
80, it means you need to read the book again. You are doing it for you!

Good luck and hope to see you again!

Final exam

1. What’s a Data Access Layer?

a. A layer responsible with processing requests coming from the user interface
b. A layer responsible with direct communication with the
c. A layer responsible with model definition
d. None of the above

2. For what is the success method used in an Ajax request?

a. The success method is triggered if the Ajax is successfully and if the API action does not return
an error message
b. It can be used as an event, to do something after Ajax starts and it is triggered after Ajax
finishes, no matter of the response status
c. It’s a property of an Ajax request used to identify which action from an API should be called
d. None of the above

3. A route for a get method looking like this [Route(“parents/{id}/children/{childId})] can be translated
to:

a. Getting details from child having the id childId from parent having the id parentId
b. Getting details of all parents having children with id childId
c. Getting details of a parent having the id parentId
d. None of the above

4. Considering you are debugging a web application in your browser and the execution stopped at a
breakpoint just before calling a method, how can you debug the code inside that method without
passing it?

a. By pressing F5
b. By pressing F8
c. By pressing F10
d. None of the above

5. Can you return nothing from a method in C#?

a. Yes, using void keyword


b. Yes, using null keyword
c. No
d. None of the above

6. Considering the following function in C#, Public List<MyDTO> GetAll() , which of the following
variables can be returned inside its body, without getting any error?

a. string myVar = new List<MyDto>()


b. var myVar = new List<MyDTO>;
c. var myVar = new List<MyDTO> { new MyDTO(), new MyDto() }
d. None of the above

7. What does the following SQL query?

SELECT TOP 15 Id, name, rank FROM cars WHERE name like ‘%ced%’ AND category NOT IN
(“sports”,”suv”)

a. Selects top 15 id, name and rank from cars


b. Selects top 15 id, name and rank from cars where name contains the string ced and category is
not sports or suv
c. Selects top 15 id, name and rank from cars where name starts or ends with the string ced and
category is not sports or suv
d. None of the above

8. What does the following linq query ?

Context.People.Where(a=> a.Name.Contains(“foo”)).Select(a=> new MyDTO { Id= a.Id, Fullname =


a.FirstName + “ “ + a.LastName }).ToList()
a. Updates People table with a new entry containing the string foo in name
b. Selects a list of MyDTO custom objects (classes) from People where Name contains the string
foo
c. Selects a new MyDTO class containing all people where Name contains the string foo
d. None of the above

9. On which elements this CSS definition applies? div#bg-custom .bg-red { background-color:red }

a. On all elements having the bg-red class which are inside a div having bg-custom id
b. On all elements having the bg-red class
c. On all divs elements having the id big-custom and class bg-red
d. None of the above

10. Which elements are selected using following jQuery selector? $(‘.bg-red .bg-reddish’)

a. All bg-red and bg-reddish elements


b. All elements having the bg-reddish class which are inside elements having bg-red class
c. All elements having bg “-reddish class
d. None of the above

11. What represents mapping one class to another in C#?

a. Creating a new instance of the same class


b. Creating a new instance of another class and filling properties with values from the first one
c. Creating a new instance of another class
d. None of the above.

12. What’s a front end library?

a. A collection of C# classes
b. A collection of models
c. A collection of functions and properties for CSS, Jquery and sometimes even for HTML
d. None of the above

13. An MVC controller is part of the front end side of an application?

a. Yes
b. No

14. How can you write following query in LINQ ?

INSERT INTO SomeTable (Name,Description) VALUES (‘name’,’description’)

a. Var toInsert = new SomeTable { Name=’name’, Description=’description’};

DbContext.SomeTable.Add(toInsert);

DbContext.SaveChanges();

b. DbContext.SomeTable.Add();
DbContext.SaveChanges();
c. None of the above

15. What is IIS?

a. A web server from Microsoft that runs on Windows to serve requested web pages or files
b. Name of a transaction used in relational database systems
c. None of the above

16. A primary key in a Microsoft SQL database table represents:

a. A unique identifier, helping SQL to uniquely identify each row of a table


b. A special column that is helping SQL to link a table to another one

17. How can you make Visual Studio understand what’s inside another namespace?

a. If that namespace is inside another project, add a reference to that project


b. If the namespace is in the same project, just write the using clause at the beginning of your file
c. If you don’t have the using written, hit CTLR+ . combination and select the using
namespace_name option
d. None of the above
e. All of the above

18. When talking about an API, what is an Endpoint?

a. The part responsible with holding a set of data sent by the user to the API
b. The route to an API action
c. Test data used to debug your API
d. None of the above

19. What type does this variable have in C#? var myVariable = 3;

a. Int
b. Number
c. Text
d. String

20. What type does this variable have in Javascript? var myVariable = 3+”a”;

a. int
b. number
c. text
d. string
Answers

Pop Quiz 1

1-d

2-a

3-a

4-a

5-e

6-a

7-a

Pop Quiz 2

1-b

2-a

3-a

4-a

Pop Quiz 3

1-b

2-b

3-a

4-b

Pop Quiz 4

1-d

2-a

3-b

4-b

5-b
Pop Quiz 5

1-e

2-d

3-a

4-a

Pop Quiz 6

1-b

2-a

3-a

4-e

Pop Quiz 7

1-a

2-c

3-a

4-b

5-b

6-b

7-a

8-c

Pop Quiz 8

1-b

2-a

3-a

4-a

Pop Quiz 9
1-d

2-c

3-b

4-a

Final exam

1-b

2-a

3-a

4-d

5-a

6-c

7-b

8-b

9-a

10 - b

11 - b

12 - c

13 - a

14 - a

15 - a

16 - a

17 - e

18 - b

19 - a

20 - d

You might also like