You are on page 1of 326

Upgrade

Your Job
The Easiest Guide to Making Extra Money as a Web Developer
By C.J. Tran

Dedication

To Tracy, my wife, Emma, my daughter, and Tristin, my son; thank you for all your love!

January 2016

Table of Contents
Upgrade Your Job
Dedication
Table of Contents
Step 1.0 Getting Started
Step 1.1 Installing Visual Studio 2015
Step 1.2 Creating Your First Website
Step 1.3 Publishing Your Website Online
Step 1.4 Where to Go from Here
Step 2.0 SQL Server Installation
Step 2.1 SQL Creating Databases and Tables
Step 2.2 SQL Databases Attaching and Restoring
Step 2.3 TSQL CREATE
Step 2.4 TSQL READ
Step 2.5 TSQL UPDATE
Step 2.6 TSQL DELETE
Step 3.0 MVC Basics
Step 3.1 MVC Areas
Step 4.0 CSS Bootstrap
Step 5.0 Models with EF
Step 5.1 Models C-Sharp
Step 6.0 C-Sharp Creating Data
Step 6.1 C-Sharp Displaying Data
Step 6.2 C-Sharp Updating Data
Step 6.3 C-Sharp Deleting Data
Step 7.0 JavaScript Introduction
Step 7.1 JS Setup
Step 7.2 JS Read
Step 7.3 JS Create
Step 7.4 JS Update
Step 7.5 JS Delete
Step 7.6 JS Conclusion
Step 8.0 CSS Basics
Step 9.0 Final Thoughts
Appendix A - Programming Languages
Appendix B - Creating Your Own Domain
Appendix C - Installing the dot NET Framework
Appendix D - Getting a Job
Appendix E Resources
Appendix F Sample Resume


Step 1.0 Getting Started

Hello, thank you for selecting my book and choosing to read it!
Many other web development books take you through confusing programming concepts
and rarely teach you anything practical. In contrast, my goal in this book is to give you the
knowledge to get up and running as quickly as possible so that you can see how web
development works without getting bogged down in unnecessary details.
I believe the best way to learn something new is by doing it, and that’s exactly what we
are going to do in the first part of this book. We are going to build a website and put it
online following these three steps:
1. Install Visual Studio
2. Create your first website
3. Publish your website online
Once we complete those steps, you will have the necessary foundational knowledge to
build on. Then, the rest of the book will be dedicated to more advanced web development
techniques. If this is all new to you, don’t worry if you don’t understand everything we are
about to do; just follow along, and I will explain as we go.
Ultimately, what I will do in this book is help you become a money-making web
developer who can build awesome websites. Let’s face it, in today’s fast-paced world, we
don’t have the time to spend hours sitting in classrooms getting new degrees or years
learning new skills. We need to learn it now so that we can get out there and start earning
money. And that is my goal in this book, to help you get up to speed and be a great,
profitable web developer.
So if you are ready, let’s get started!

Step 1.1 Installing Visual Studio 2015

In order to build a website, you will need something to build it with and in this book we
will be using Microsoft Visual Studio 2015, from here on abbreviated as VS.
If you do not have VS on your computer, it can be downloaded here:
https://www.visualstudio.com/en-us/downloads/download-visual-studio-vs.aspx
Click the “Download Community Free” button.
As of this writing, you can also use this link to download VS:
https://go.microsoft.com/fwlink/?LinkId=691978&clcid=0x409
If both links do not work, download it from my website here: http://www.cjtran.com/uyj.
The file is an ISO, and you will need to open it using the proper software, like 7zip,
http://www.7-zip.org. If you are using Internet Explorer and are having trouble
downloading, use a different browser like Firefox or Chrome.
Unless the default download location in your web browser was changed, it will most likely
download to the Downloads folder located at
C:\Users\YourWindowsAccountName\Downloads.
Find the folder where the file for VS was downloaded and open the file to begin installing
VS.
Once opened, if you see this screen, just click Continue:




The first installation screen will ask if you want to install as Default or Custom. If you are
new to VS, I would suggest picking Default. If you know what you are doing, feel free to
pick Custom and select the options you want.




As VS installs, it should automatically check for prerequisite software and dependencies,
and install them for you. However, your computer may be lacking other essential
components, like the .NET Framework (pronounced as dot net framework) or the latest
Windows Updates. If the installation is not working for you, follow the error message and
try to fix it. You can also search online for answers. If you see this message, click Restart
Now:



It can take up to an hour to install depending on how fast your computer is, so in the
meantime let’s multitask and talk about VS.
If you are new to all of this, right now you are probably asking a lot of questions, like,
what is Visual Studio, why do I need it, and what does it do? No worries, here is the
explanation.
Besides these basic resources, you can do an online search and find out more about Visual
Studio:
https://en.wikipedia.org/wiki/Microsoft_Visual_Studio
https://www.visualstudio.com/en-us/visual-studio-homepage-vs.aspx

Simply put, Visual Studio, is a software, Integrated Development Environment (IDE), and
the tool which we will use to build your website.
For example, in order to edit pictures, you can use the expensive professional Adobe
PhotoShop or the simple free basic Microsoft Paint. With both software you can crop
pictures, add colors, and save images in different formats, like PNG or JPEG. However,
PhotoShop has many more features than Paint, and allows you to turn images into almost
whatever your mind can imagine.
Just as different tools or software are used for different purposes, we can use VS to build
websites, mobile applications for Android, iOS and Windows phones, web services and
many other things. What you can build with VS can be overwhelming at first, so for now,
let’s just concentrate on building your first website.
A website contains a bunch of files, like HTML, CSS, and JavaScript, and those files
make up a web page. Don’t worry if you do not know what those files mean now, I will
explain as we go along. Usually websites have many pages, which means there will be
many files, filled with lots of code, which you will need to create.
There are many other IDEs out there and doing a quick online search will show you many
different tools you can use to build websites. In this book, we will specifically be using
VS and as we go along you will see the benefits.
If VS is still installing and you want to keep reading, checkout the links above and
Appendix A - Programming Languages. If VS, is done installing, you should see this
screen and should restart your computer before continuing:


Once your computer has been restarted, go to the Start menu, search for VS, and open it.
If this is the first time you are opening VS, it will ask you to sign in and if you want to,
click Sign in.


If you do not want to sign in, click “Not now, maybe later.”
If you want to sign in but do not have a Microsoft account, you can create a free account
by going here: https://www.microsoft.com/en-us/account. Under the big blue Sign in
button, click the link “Create a free Microsoft Account”. Follow the instructions on the
page and fill in the required information.
If that link does not exist, do a search online for “create new Microsoft account” and you
should be able to find the create page to make yourself a new Microsoft account. There are
many benefits to having a Microsoft account and you can read about it here:
http://windows.microsoft.com/en-us/windows-8/microsoft-account-tutorial.
It is highly recommended you have a Microsoft account since we will use that later to
deploy your website online.
Once you have a Microsoft account, sign in by entering your email and password and
click Continue. On the next screen, if you are asked to “Host your next project in Visual
Studio Team Services”, click the link “Not now, maybe later” at the bottom.

On the next screen, you will be asked to select a development environment. Since we are
building a web application, use the dropdown and pick Web Development.
The last step is to pick a theme, which is just a way to tell Visual Studio how you want
your IDE to look. You can always change it later if you don’t like how it looks by using
these links:
https://www.youtube.com/watch?v=vk6JQwTonXA
http://stackoverflow.com/questions/9594433/how-can-i-switch-themes-in-visual-studio-
2012
http://edglogowski.azurewebsites.net/?p=10991

Finally click Start Visual Studio.


If this is the first time you are opening VS, it should look similar to this:



With Visual Studio installed, let’s go on to the next step where we will create your first
website!

Step 1.2 Creating Your First Website

Now that Visual Studio 2015 (VS) has been installed on your computer, let’s start building
your first website. As mentioned there are many different types of applications you can
build using VS. and in this book, we are going to concentrate on building a web
application, specifically one called MVC. I will explain what MVC is later, but for now
just know that it is a type of website.
In order to build a website, we need to create a solution and then add projects to it. Think
of a solution as a big container which holds all of your projects, and think of a web project
as a big folder which holds all of your web pages and resources. A solution and a project is
just a way for VS to keep track of all your files, images and code.
Before we begin, I want to give you some words of encouragement. If you are new to all
of this, what we are about to do has many steps, can feel overwhelming and may be
confusing. Take it slow and if you have issues, start over. Like anything else, the more you
do it, the better you will get and the easier it will become, and soon you will be able to do
this in your sleep. Are you ready? Let’s do this!
With Visual Studio 2015 open, go to File, New, and then select Project. With the New
Project dialog open, in the left panel, under Installed, Templates, expand Other Project
Types and select Visual Studio Solutions. Enter “MySolution” for the Name and set the
Location to the root of your C drive and then the folder named Projects or wherever you
prefer. Make sure everything looks like this screenshot and then click OK:


With a new solution created, your Visual Studio should look like this:




Now let’s add a MVC web application to the solution. Right click on the solution, and
select Add, New, and then Project.



On the left side, under Installed, expand Visual C#, and click on Web. In the center panel,
select ASP.NET Web Application. Enter “Web.UI” in the Name textbox (UI stands for
User Interface). Leave the Location textbox as is. Your dialog should look like this and
then you can click OK:



On the next screen select MVC and uncheck Host in the cloud, and click OK:



If all went well, your default view should look like this:



Let’s see what this MVC web project looks like in a web browser. In your Web.UI project,
expand the Views folder, then the Home folder, right click on the Index.cshtml, and select
View in Browser. (You can also use the keyboard shortcut, by selecting the file and press
at the same time, Ctrl+Shift+W )



Your site should look like this: (Feel free to click around and explore the site.)



At this point, there’s a lot we can discuss. What is a MVC website and how does it differ
from other websites? What does MVC even stand for? What can we do with a MVC
website? Why does the Index page have a CSHTML extension and not HTML? To answer
those and probably many other questions you may have, I would point you to this
beginner’s resource: http://www.w3schools.com/aspnet/mvc_intro.asp
For now, just know that an MVC website basically has to do with a design pattern that
uses separation of concerns. Simply put, the Model is the structure of your website, the
View displays what your Model defines, and the Controller is the way your site functions.
I can image that if you are brand new to web development, you may have no idea what I
just said. Don’t worry, as we go along you will start to understand MVC. And hopefully, if
you take some time to do your own research, it will help fill in the missing pieces.
So that’s it, you did it! You have installed Visual Studio, created a web project, and have
successfully created your first website! Give yourself a pat on the back, do your happy
dance, and know that you have crossed the barrier and are now a web developer.
Next we will publish your website online so the whole world can see it.

Step 1.3 Publishing Your Website Online

The destiny of every website is to be online so everyone can benefit from it. In this step
we will put your website on the internet so all your families and friends can admire your
work!
In order to put your website online, we need to pick a web hosting provider. There are lots
of different web hosting providers you can choose from. We will use Microsoft Azure and
you can read more about it here: https://azure.microsoft.com/en-us
As we go through this step, keep in mind that your account name, URL, and other settings
will be different than the screenshots I provide. As long as you are following the steps,
don’t worry if things don’t match exactly.
To start go to: https://azure.microsoft.com and click on Try for free:



On the next page click Try it now:



Sign in with a Microsoft account. If you don’t have an account, it is highly recommended
that you create one using the link at the bottom of the page:



Once signed in, enter the information in the section About you and Verify by phone and
click the Send text message (or you can use the email verification method):



You will receive a text with the verification code, enter it in the textbox and click Verify
code.

Once verified check the I agree at the bottom. Enter your payment information. Since this
is a 30-day trial, you should not be charged and can cancel anytime. Azure gives 200
“fake” dollars so you can see how much data your site uses in a month. Check out the
FAQ here: https://azure.microsoft.com/en-us/pricing/free-trial-faq

If you don’t want to use a credit card, then you won’t be able to continue with this step
and will have to find another way to publish your website online.




After successful card verification, click Sign up. You’ll see the setup page:



If all went well, you will see the welcome page and can click on Start managing my
service:


As of this writing the default dashboard is the “older” version. You can always go back to
the “older” dashboard here: https://manage.windowsazure.com



The newer dashboard is located at https://portal.azure.com and if asked, sign in.

Now that we have an Azure account, let’s create a web application to host our website.

In the left menu, click on Web Apps:


Click the plus Add icon:


Enter in a Web app name and click the blue Create button at the bottom.
The Web app name is the URL people will use to see your website, for example:
http://www.myfirstwebsite.azurewebsites.net
In this example my URL will be: http://www.demo1123.azurewebsites.net


Once the web application has been created, click on Web Apps and you should see this
view:



Notice the center panel has the URL for your new website:


Click that URL to display a default page:


Now that we have a URL, let’s use Visual Studio to publish your website online!
Go to your web app console and click Get Publish. That will download the configurations
and settings needed to deploy your site.



Notice the path to where it was downloaded. In my case it’s here:



Open VS and then open the solution called, MySolution. Right click on your project and
select Publish:


Click on the Import:


Enter in a path to your publishing file or use the Browse button and navigate to it, and then
click OK:


Notice the publishing credentials for your new website. Click Publish to put your website
online:


While publishing you will see the status in the output window:


When publishing is finished, your browser should open to your new website:


Congratulations, you just published your first website online and can go tell all your
families and friends to check it out!

Since this is a trial Azure account, keep in mind that there are data limits. The more times
you publish or the larger the files and images, you may use up your data:
https://azure.microsoft.com/en-us/pricing/free-trial-faq
If you had trouble publishing your site, take a look at this link:
https://azure.microsoft.com/en-us/documentation/articles/web-sites-dotnet-get-started
You can checkout other ways to deploy your work here: https://azure.microsoft.com/en-
us/documentation/articles/web-sites-deploy
To create a custom domain name, like www.JaneDoe.com, check out Appendix B -
Creating Your Own Domain.
To cancel your Azure account, go to https://account.windowsazure.com/Subscriptions and
click on Free Trial:


Then in the right side navigation, scroll down the page until you see the Cancel
Subscription link and click on it:


Select “Yes, cancel my subscription” and follow the rest of the instructions provided.


Step 1.4 Where to Go from Here

If you are brand new to web development and have successfully completed the previous
steps, I want to congratulate you on a job well done! Although it may not seem that
significant right now, you have just accomplished something amazing. You now know
how to use Visual Studio to build a simple website and publish it on the internet. The rest
of this book will use and explain more advanced web development techniques. In order to
become an experienced web developer, you will need to be able to create cutting-edge
websites, understand the many terms, technologies, aspects of web development, and have
a good understanding of information systems. In this book, I will walk you through each
step in order to help you become a great and profitable web developer.
The journey to becoming a successful web developer can be a long uphill road. You may
be a beginner today and have no idea where to start. You may have gone to a book store,
headed to the computer section, and stared at the countless books about web development
with titles you could not even pronounce, asking yourself, “Where do I start?” Or you may
have Googled it, read many forums, and followed tons of online guides, and still have a
vague idea what it all means or how it works. There is no need to be confused any longer,
because I am going to help you get started, explain what we are doing along the way, and
then move on to more advanced web development techniques. If you are willing to put in
the time to finish this book, you will have a good understanding of web development and a
strong foundation on which you can continue to build your web development skills to
become an outstanding web developer!
If you are a self-starter and want to try using Visual Studio to build other applications, like
mobile apps, I totally encourage you to skip the rest of this book for now and go for it.
Once you feel you are a “bad ass” developer and want to start making money, check out
Appendix D - Getting a Job.
For the rest of us, here is the plan for the rest of this book:
1. Creating a database and working with data
2. Working with a MVC website
3. Making your site look good using Bootstrap
4. Using C# code to work with data
5. Using JavaScript and jQuery
6. CSS Basics

Let’s get going and learn how to become a great, money-making web developer!

Step 2.0 SQL Server Installation

The general purpose of websites is to display information. Some display static content
while others have dynamic data, like a website that displays the stock exchanges. All that
information is stored in a database on a server sitting somewhere around the world. Just as
a web server holds web pages, a database server will store data. Before we can build a
website to display information we first need to setup a database server, create a database,
and add data to it.
Microsoft SQL Server (Sequel Server), is a relational database management system
(RDBMS) and the database we will work with. There are many other databases out there,
like Oracle.
When coding against SQL databases, the programming language used is TSQL, which
stands for Transact Structured Query Language. There are lots of other database
programming languages, like PL/SQL (Procedural Language/SQL) which is used for
Oracle databases.
T-SQL is used by Microsoft and is specific to SQL Server. You can read more about it
here: http://www.w3schools.com/sql
Just as Visual Studio is used to build websites, SQL Server management Studio (SSMS) is
used to work with databases to manage and manipulate data.
To download SSMS, go here: https://www.microsoft.com/en-us/server-cloud/products/sql-
server-editions/sql-server-express.aspx. Click on the “Download SQL Server 2014
Express” link.
You can also download it from my website here: http://www.cjtran.com/uyj.


If asked, go ahead and sign in with a Microsoft account.


Enter your information on the Profile Center page. Complete all the required fields. For
the version, pick SQL Server Express with Advanced Services (32 or 64 bit, depending on
your computer). In my case, it is 64 bit.




You can find your computer bit type by going to the Start menu and searching for
“system”:



Next to the System type will be your computer’s type.



Once all required information is filled in, click Continue at the bottom of the page:



Once downloaded, open the file:


Pick a directory to extract the files. In my case, it’s the C drive in a folder called
SQLExpress. Click OK:



Once extracted, the installation window should automatically open. If not, go to the
location where you extracted the file and open the SETUP.EXE:



When the installation window opens, pick the first option to install a “New SQL Server
stand-alone installation or add features to an existing installation”:


Pick “I accept the license terms” and click Next:


If you see this screen, click Next.



If you get to the Feature Selection window, click on Select All and click Next.



You’ll see the progress as SQL Server is installing:



If you see this error message, click Cancel:



Then click Yes:


Close the window for SQL Server Installation Center.
At this point, your computer is missing important prerequisites and you won’t be able to
continue installing SQL Server until you update your computer. Go to Appendix C -
Installing the dot NET Framework. Once you have completed that appendix, start the SQL
installation from the beginning of this step.

If you get to this point of the installation and see the Instance Configuration screen, leave
the default instance name as is and click Next:


On the Server Configuration screen, click Next:


On the Database Engine Configuration screen, leave all the default settings, and click
Next:


On the Reporting Services Configuration screen, leave all the default settings, and click
Next:



You will see the progress bar as SQL Server installs:


If you see this message, click OK:


If all went well and the installation completed successfully, you can click Close.



Close the installation window and restart your computer.



If you had trouble installing SQL server, check out these videos:
https://www.youtube.com/watch?v=E_zFM7mzFUg
https://www.youtube.com/watch?v=SfwD_Gq0qek

With SQL Server installed, let’s move on to the next step where we will create a database
and add some data.

Step 2.1 SQL Creating Databases and Tables

In this step we are going to use SQL Server Management Studio (SSMS) to create a
database, create a table and add some data.
To open SSMS go to the Start menu and search for “ssms”. You can also open it by going
here: C:\Program Files (x86)\Microsoft SQL
Server\120\Tools\Binn\ManagementStudio\Ssms.exe



With SSMS open, you will see the default server name, which is your computer name
followed by the server instance name. In my case, it will be different than yours. What
matters is the instance named SQLEXPRESS. If you don’t see it, use the dropdown to
open the sever name and pick it. Once your server name is selected, click the Connect
button:


Notice there are many folders in the Object Explorer, but for now let’s just expand the
Databases folder, which contains all your databases.
Simply put, a database is a location on a computer where data is stored. There can be
many different types of data, like people’s personal information or more generic data. This
is a big topic, so let’s just keep it simple and focus on creating a database and then add
some data to it.
If you have trouble with any of the code in this step, download the full code from my
website and use it as a reference as you go through this book: http://www.cjtran.com/uyj.
Right click on the Databases folder and select New Database…



Enter a database Name, for example, MyFirstDatabase and click OK:


Expand the database MyFirstDatabase by clicking the plus sign to the left of it. Now
expand the Tables folder which will be empty, so let’s add a new table.
You can think of a table as the core entity of a database. For example, if you think of the
whole world as a database, then each person is like a table. Let’s create a new table by
right clicking on the Tables folder and select Table…



Enter a name in the Column Name and select the Data Type as seen below. There are lots
of different data types, for now just select int, and make sure the Allow Nulls is checked.
NULL means that there is no value in that cell, in other words there is nothing there.
NULL is the default value when you create a datatype. NULL is different from blank or
empty. You can read more about SQL data types here:
http://www.w3schools.com/sql/sql_datatypes_general.asp



Add more fields and make your data table match this image:



You’ll notice I tried to use different data types and its precisions. For example, Email has
a precision of 100 in length where LastName is 25 in length. You’ll also notice the
DateCreated field will be used as a time stamp the very instant data is created. This is
helpful for when you have to go back and determine when the data was created, like in the
case of looking up historical data. It is a good idea to have a DateCreated field in every
table, unless you know it’s not important to keep track of when data is added to your table.
The next important aspect to set on the data table is the primary key, although in some
circumstances you will not need to do that. You can think of a primary key as the unique
identifier for a data table. If we go back to the analogy used before, where a database is
like the whole world and each person is a data table. Then each person’s finger print, is
like the primary key in the data table.
To set the primary key on a data table, right click on the row you want to set the primary
key, in this case, MyFavoriteFriendsID, and select Set Primary Key. You’ll now see
there is a key icon next to the column and the Allow Nulls column is unchecked:


A field with a primary key cannot be NULL. Can you figure out why that is?
There are more advanced techniques we can perform on this data table, like multiple
primary keys, setting foreign key constraints, indexing, and so on.
Going back to the analogy before where each person is like a data table, even though each
person has a different face, when it comes to identical twins, how can we distinguish
them? We can use multiple factors to identify them, like using both their face and finger
print. So it is the same technique when working with similar data tables. We will want to
use different methods to ensure that our data table is unique. For now, just understand that
it is important to make sure your data table contains the proper data structure to hold the
data in it.
With our new data table created, let’s save it by going to File, and select Save:


As a good practice, name your primary field the same as your table name and make the
primary field plural. For example, in this case, the table name is MyFavoriteFriends and
the primary field name is MyFavoriteFriendsID. The reason being is that if you ever
accidentally change the table name, you can always look at the primary key field and
figure out what the original table name was. And it is just logical to pluralize the primary
key field, because there will be many “favorite people” in that data table. This practice is
debatable, but it has been a convenient convention in my experience.
Go back to your Tables folder, right click and select Refresh. Click on the plus sign to
expand the Tables folder, you will see the newly created table:



Notice that there is a dbo before the table name, which just means database owner. This
is one of the many schemas built in to SQL Server. This is an advance topic, so don’t
worry about it for now. You can learn more about it here: https://msdn.microsoft.com/en-
us/library/bb669061(v=vs.110).aspx
Go down to the Column Properties window and expand the Identity Specification and set
it to Yes, and then Save the table:



If you get this message, click Cancel:



And if you see this message, just click OK:


This message is saying you have set a data type for a column and now you are changing it
which will cause some of the data to get messed up. For example, you have a field for a
birth date, and you change it to a data type for a phone number, the actual dates may not
format correctly and your data will be corrupted or lost.
If you know that changing the data type will not cause data issue, and want to remove this
error message, you can go to Tools, Options:


Click on Designers, and unchecked these three options and click OK:


Simply put, by setting the Identity Specification, when a new row is added, it tells SQL
Server to increment each row in that table by one. We will see this in action later.
Think of a row in a table as the actual data in a database. If we go back to our analogy,
where a database is like the world, and each person is like a table, then each row in the
table is like each cell in the person’s body. Just as there are billions of cells in the body, so
a table can have billions of rows and all those rows hold the actual values for the data we
are storing.
If you were not able to create the table above or had trouble, you can quickly create it by
executing the TSQL script below and it will create the table for you. Before we run that
script, right click on the Tables folder and refresh it. If there is a table there, right click and
delete it. If we don’t delete it now, when we run the script in the next step you will get an
error that will basically say that table already exists.
To create a table using TSQL script, execute the code below. Right click on your database
and select New Query:



Copy and paste this code in to the query window and hit F5 on your keyboard or click the
execute button:


USE [MyFirstDatabase]
GO


SET ANSI_NULLS ON
GO


SET QUOTED_IDENTIFIER ON
GO


SET ANSI_PADDING ON
GO


CREATE TABLE [dbo].[MyFavoriteFriends](
[MyFavoriteFriendsID] [int] IDENTITY(1,1) NOT NULL,
[FirstName] [varchar](50) NULL,
[LastName] [varchar](25) NULL,
[Email] [nvarchar](100) NULL,
[MobilePhone] [nvarchar](25) NULL,
[Age] [tinyint] NULL,
[DateOfBirth] [date] NULL,
[DateCreated] [smalldatetime] NULL,
CONSTRAINT [PK_MyFavoriteFriends] PRIMARY KEY CLUSTERED
(
[MyFavoriteFriendsID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF,
ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]


GO


SET ANSI_PADDING OFF
GO





Now that we have created a database, and added a new data table, let’s move on and
actually enter data. You can imagine it can take hours to add more data, so in the next step
we are going to download a sample database, and use SSMS to do more advanced SQL
Server techniques.


Step 2.2 SQL Databases Attaching and Restoring

In order to work with data and not have to spend time creating it, we can download a
sample database by going to: http://msftdbprodsamples.codeplex.com


Download the zip file:


If that link no longer works, go to my site and download it here:
http:/www.cjtran.com/uyj.

Go to the location where it was downloaded. If you are using Chrome you can click on the
little down arrow to Show in Folder as seen here:



Unzip the file by right clicking and select Extract All:




Leave the default location and click Extract:



Once extracted, you should see the extension bak (short for SQL database backup file):


Now that we have a backed-up database, we can use SSMS to restore it.

Open SSMS and connect to your server. In Object Explorer, right click on the Databases
folder and select Restore Database:




Select the Device radio button and click on the ellipses button:

Click the Add button:



Using the file locator window, navigate to where the AdventureWorks2014.bak file was
extracted above. Select the AdventureWorks2014.bak file and click OK:



Once added, your bak file should appear in the center panel showing the path to that file as
seen below, and you can click OK:



Then click OK to restore the database:



Once restored you should get this message:



You should see the new AdventureWorks2014 database in Object Explorer. Feel free to
click around and explore the AdventureWorks2014 database. Notice there’s a lot of tables
in there:



Restoring a database requires a .bak file, while attaching a database requires a .mdf file.
Let’s quickly attach a database.
Since the database we will be working with is already attached to SQL Server,
MyFirstDatabase, we will first need to detach it and then re-attach it.
To detach a database, right click on the database and select Tasks, then Detach:



Click OK:



If you get this error message, click Cancel, restart SSMS and start over from the
beginning:



Once detached it will disappear from the Databases folder in Object Explorer.


To attach a database, right click on the Databases folder and select Attach:




Click Add:




Notice that the file extensions is .mdf. Find your database using the file locator and
navigate to the database you want to attach, and click OK:




Once attached you will see your database and can right click the Databases folder and
select refresh, to see all the databases attached to your server:




Another common task is to back up your database and you can read more about it here:
https://msdn.microsoft.com/en-us/library/ms187510.aspx

To back up a database right click the database and select Tasks, then Back up:




Notice the path to where the backup will be saved. You can Remove and Add the
destination by naming it properly and setting the path to where it will be saved. Click OK
to back up the database.




Click OK:




You can verify that the backup was successful by going to the saved location and in my
case it is: C:\Program Files\Microsoft SQL
Server\MSSQL12.SQLEXPRESS\MSSQL\Backup





In this step we downloaded a sample database, restored, detached, attached, and backed-
up a database. Let’s move on and learn how to put data in and get it out of our database.

Step 2.3 TSQL CREATE

There are four basic database operations, create, read, update and delete, also known as
CRUD operations. In this step we will use the CREATE operation to add new data to our
table.
There are many ways to create or put data into a database. You can use the GUI, graphical
user interface, and manually enter the data. Let’s do that now.

Right click on the table and select Edit Top 200:



Your Edit Top number may be different than mine and you can always change it. This
number is the default number of rows we can edit at a time and in this case, it is 200 rows.
As mentioned earlier, your table can have millions of rows, if you set this number too
high, it can take a long time to open.
To change the default edit row number, go to Tools, and select Options:



Select SQL Server Object Explorer and enter a new value:



With the edit view open, since we have not added any data, your first row will be blank:



Let’s add some data!

Enter all the information for the first row as seen below, hit the Enter key or use the mouse
and click somewhere outside of the first row. (NOTICE: You cannot enter a value in the
first column, MyFavoriteFriendsID, because it is a primary field. SQL Server will
automatically enter a value in there when it saves the row.)


Age is NULL because later we will use C# code to calculate it using the DateOfBirth and
the current date.
To change data in any column, click in a cell and enter a new value.


To delete a row, right click the very left side of the row and select Delete:



Try adding more rows of data and notice how the Identity Specification increments for the
MyFavoriteFriendsID column.

Another way to add data is to use T-SQL code/scripts. Script allows fast data creation
without having to manually enter data in each cell. Go to the MyFavoriteFriends database, right
click and select New Query:




Add the following script/TSQL code:

USE [MyFirstDatabase ]
GO


INSERT INTO [dbo].[MyFavoriteFriends]
([FirstName]
,[LastName]
,[Email]
,[MobilePhone]
,[Age]
,[DateOfBirth]
,[DateCreated])
VALUES
(
‘John’
,‘Jones’
,‘john@email.com’
,NULL
,NULL
,NULL
,GETDATE()
)
GO





Let’s explain that code.

The USE [MyFavoriteFriends] tells SQL Server to look in the proper data context, and in this
case, the MyFavoriteFriends database.
The code GO is a way for SQL Server to know when you want a specific bunch of code to
end. Read more about it here: https://msdn.microsoft.com/en-us/library/ms188037.aspx?
f=255&MSPPError=-2147217396
We use the keyword INSERT INTO, to add data to a table, followed by all the fields we will
be inserting.

The next keyword is VALUES, which is followed by the actual values we will be inserting
into our table. The next three fields is NULL, and the last field uses the SQL function
GETDATE(), which will get the current date and time the instance that row is added to our
table.

The order of your code is also important. If we flipped the field FirstName with
LastName, and executed the script, the result would be, Jones as the first name and John
as the last name.


Go ahead and execute the script by clicking the Execute button or pressing the F5 key:




The result message should be this:




Go to your table in edit view and hit the Execute button or press the key Control+R and
you will see the new row:



Notice the MyFavoriteFriendsID has incremented to two, and the DateCreated is different
than the first row:




Besides manually entering data, or running TSQL scripts, a much faster method is to
import it from a data source, like an Excel file. In cases where there is lots of data, we will
want to use the import method.
Right click on the database, select Tasks, and Import Data: (Notice you can also export
data too)



Click Next:



Open the Data source dropdown and you will see many options to import your data. For
now, select Microsoft Excel and click Next:



Click Browse and navigate to where your file is located. In my case it’s in the root of the
C drive:



If you don’t have an excel file you can download it from my website here:
http://www.cjtran.com/uyj, or create one to look like this: (Notice that the column names
must match those in our SQL data table and make sure you save the excel file with the
extension of XLS and not xlsx)



Then click Next:


Open the dropdown and select SQL Server Native Client 11.0. Leave all other settings as
is and click Next:

Select the first radio button and click Next:


Open the Destination dropdown in the right column, select [dbo].[MyFavoriteFriends] and
click Next: (Make sure the right column does not have a dollar sign ($) after the table
name.)


On the next screen, it is making sure the data types match and for now you can just
continue by clicking Next:


Make sure Run immediately is check and click Next:


And finally click Finish:


Once all your data has been imported you can click Close:



Go to the table, right click and select top 1000 rows and you will see the new imported
data:



You’ll remember there are other data sources you can use to import data into SQL server:



If you had trouble adding data to the table, go to my website and download this file
MyFavoriteFriends.sql. Open SSMS, and execute the scripts which will add all the data
for you.

Or You can download the excel file, MyFavoriteFriends.xls, and import it. Both files can
be found from my website: http://www.cjtran.com/uyj.



When working with data, there are four basic CRUD operations, Create, Read, Update,
and Delete. We just went over how to create or add data with the CRUD operation which
is also known as the INSERT statement. Data can be added to SQL server in many ways,
like manual entry through the GUI, running TSQL scripts, importing, and using C# code,
which we will do later.
The next step will cover the READ operation, which is used for querying of data.

Step 2.4 TSQL READ

Of all the CRUD operations, the most commonly used is READ, which is used to search
for data and is also known as SELECT. Let see how this works.
Open SSMS, go to the AdventureWorks2014 database, and go to the Person.Person table
in Object Explorer. Right click and Select Top 1000 Rows.



If this is the first time you are opening a SELECT query, let’s explain what it means:


At the top of the window, you will see Transact Structured Query Language, T-SQL. Just
as CSS is code for styling, and JS code is for working with browser behavior, T-SQL is
code for working with SQL Server databases. The first line of code is in green which
indicates it is commented out and will not be executed in the query because it is just for
humans to read.




In the top left of SSMS, the default database context is “master” and can be changed to
AdventureWorks2014. This tells SSMS the current context you are working in. If you are
working with many databases and do not switch the context, your query may not work
properly.
For example, go to the context dropdown and pick MyFirstDatabase, delete the code
[AdventureWorks2014]. (including the dot after the right square bracket).


Execute the code using F5 on your keyboard or the button. The Messages window tells
you what the error is:


Since we are using a different context, SSMS does not know where to find the table
named Person.Person.
Change the context back to AdventureWorks2014, put back the code “
[AdventureWorks2014]. ”, execute the query, and you will see the correct results:



SELECT and TOP is a T-SQL reserved keyword and there are many other keywords. You can
learn more about them here: https://msdn.microsoft.com/en-us/library/ms189822.aspx
If we remove the TOP keyword (and the 1000), we will get all the rows in that table. It is a
good practice to limit your SELECT statements to a specific number of rows. As mentioned,
if your table has millions of rows and you query for all of them, it will take a long time to
get the results.

To get the total row count in a table quickly, you can use the built in SQL function,
COUNT() , and put in between the parenthesis the name of the column you want to query, in
this case we are using the column BusinessEntityID :


The result is 19,972 rows.
Notice that when you have two SELECT statements and Execute all the code, it will run both
queries. If you want to run just one query, highlight it and Execute it as seen from the
image above. (Highlight means using your mouse and dragging over all the code you want
to run). You’ll notice that the query SELECT COUNT() is different from the SELECT TOP. With
the COUNT() we are asking for all the rows so there is no need to have a TOP keyword in
there. It would not make sense to have a TOP in that query and if you did, an error would
occur:


Notice the AS keyword used with the ‘Total Rows’ in single quotes. Simply put, the AS
keyword will take what’s before it and rename it to something else. If you run another
query without the AS keyword, you’ll see that the there is no column name.



To make the results column descriptive, we added the ‘Total Rows’ but you can name this
anything, like ‘Row Count’ or ‘All Rows’. The idea is that if you have to run a report for some
department in your company, you will want to put a descriptive column name with the
results.

You can also quickly find how many rows are in each table by using the Object Explorer
Details window.

In your Object Explorer, select the Tables folder:



Go to View, and select Object Explorer Details:


Go to any column, like the Name column, right click and select Row Count:



You’ll see the row count for every table in that database, and in our case the Person table
has the same number as before, 19,972:



The next part of our code to notice is the fields we are asking in our SELECT statement. It
just happens that those are all the fields in the Person table:



You can also use the asterisk symbol, * , to get all the fields in a table. And remember to
limit your results using the TOP keyword.


Using the asterisk symbol is not a good idea, but sometimes you just want to quickly look
at the data in a table and don’t have time to type out all the fields. And remember right
clicking on a table and selecting Select Top 1000 Rows, will give you a query window
with all the fields too.
Let see how removing fields affects the results. Make your query look like this and
Execute it:


The result matches what we asked for:


You can reorder the fields in any way you want as seen here:


Notice that the first field, LastName, has a comma in front of it. An error will result when
executing that code because we have to follow the syntax for TSQL:


In our query the Title and MiddleName fields is NULL, so let’s re-write our code to look
for people who do have a title and middle name:


Notice the keyword WHERE, which is a condition we are asking from our query. We are
asking SQL Server to get us a list of all the people, WHERE, their title and middle name is
not nothing.

The next keyword is AND, which is asking for two conditions to be met, namely that tile
and middle name is not nothing.

The next keyword, IS NOT NULL , is just as it sounds. We are asking that there is something
there.

If you ran the query as, IS NULL, you can see the difference here:




Remember that, NULL is different than empty. Empty is when a field is blank and does not
have a value in it, for example it could have blank spaces. Let’s run a query looking for
empty/blank values and see what we get:



You will see there are zero results for our query and it just happens that the Person table
does not have any rows where the middle name and title is blank.
Notice that we are using the equal symbol to query with. Let’s change our query to look
for people whose last names is equal to ‘smith’:


You can also use the keyword OR which returns TRUE when a condition is met. In other
words, if the middle name is not nothing, it will show up in our results, or if the title is
nothing it will also show up in our results:


The OR keyword may be a bit confusing at first, but play around with different queries so
you get the hang of it.

If we wanted to find out all the last names having the letters “tr”, we can use this query:


Notice the keyword, LIKE, and the percent symbol (%). You can read more about using
wildcards in your queries here: https://msdn.microsoft.com/en-us/library/ms179859.aspx

Another common task is to order the results by using the keywords, ORDER BY and DESC .
You’ll notice in this query, the first names are alphabetized in descending order. If you
remove the, DESC, by default the results will be in ascending order.


With those basic keywords, you should be able to look for data in many SQL database
tables. There are lots other keywords like JOIN, which allows you to look at data in
multiple tables. As you work more with T-SQL you will get to know many of the other
keywords and built in functions and store procedures for working with SQL data.
When working with data, there are four basic operations, Create, Read, Update, and
Delete. We just went over the Read operation, also known as the SELECT statement, and
in the next step we will cover another operation.


Step 2.5 TSQL UPDATE

As mentioned earlier, there are four basic database operations, create, read, update and
delete, also known as CRUD operations. In this step we will use the UPDATE operation to
modify the data in our table.

Go to your database named MyFirstDatabase, right click and select New Query:




Add the following code:

USE [MyFirstDatabase]
UPDATE [dbo].[MyFavoriteFriends]
SET [Email] = ‘ken@email.com’
WHERE [MyFavoriteFriendsID] = 3




Using the keyword UPDATE, we can modify the data in our table. We use the keyword SET
to tell SQL Server what fields we want to change and the value we want to update. The
keyword WHERE is very important because it specifies the part of our table we want to
update. If you forget to put the WHERE, you will update the whole table, unless that is the
intention. In this example, we will update Ken’s email.


Run the code above by using the Execute button or press F5. To see the change, right
click on the table and Select Top 100 Rows:



You can see that Ken’s email has been updated:


You can update many fields at once by Executing this code:


USE [MyFirstDatabase ]
UPDATE [dbo].[MyFavoriteFriends]
SET
[Email] = ‘ken@email.com’
,[MobilePhone] = 7894561230
,[DateOfBirth] = ‘01-22-1995’
WHERE [MyFavoriteFriendsID] = 3




Go to your SELECT query window and Execute it to see the change:


As mentioned, the WHERE clause is very important when updating records. Let’s see this
in action by Executing this code:

USE [MyFirstDatabase]
UPDATE [dbo].[MyFavoriteFriends]
SET [DateCreated] = GETDATE()


You’ll notice that the whole table has been updated for the DateCreated field, because we
did not use the WHERE keyword:


There are more advance UPDATE statements, which will depend on what data you are
trying to update. For example, let’s say you have three tables that depend on each other. If
you try to update one table and there is a constraint on the other table, the update will fail.
You will notice that the UPDATE statement is similar to the SELECT, especially in the
WHERE clause. Usually you can use the SELECT statement to find the row or rows you
are looking for and then execute the UPDATE statement using the WHERE clause from
the SELECT statement.

For now, you should have the basic understanding of the UPDATE statement. The next
step will cover the DELETE operation, which will allow you to remove data in your table.


Step 2.6 TSQL DELETE

As mentioned earlier, there are four basic database operations, create, read, update and
delete, also known as CRUD operations. In this step we will use the DELETE operation to
remove data in our table.

Go to your database, right click and select New Query:




Add the following code:

DELETE FROM [MyFirstDatabase].[dbo].[MyFavoriteFriends]
WHERE [MyFavoriteFriendsID] = 16751



Using the keyword DELETE, we can remove data in our table. Just like the UPDATE
statement, the keyword WHERE is very important because it specifies what part of our
table we want to delete. If you forget to put the WHERE, you will delete all the records in
the table, unless that is the intention.

Run the code above by using the Execute button or press F5:

Now verify that the delete was successful by executing a SELECT statement on the table
where the MyFavoriteFriendsID = 16751 and you will see that it is no longer there.
You can also use the TRUNCATE keyword, instead of the DELETE. Read more about it
here: https://msdn.microsoft.com/en-us/library/ms177570.aspx?
f=255&MSPPError=-2147217396
The delete operation is very straight forward. Use the DELETE keyword to describe what
you want to delete and the WHERE keyword to filter the items you want to delete.
By now you should have the basic understanding of the DELETE statement, which will
allow you to remove data in your table. Always remember to use the WHERE clause
when deleting.
With the four CRUD operations mentioned, you should be able to do basic data
manipulation. Later we will use C# code to do the same operations but only using C#
code. Now that we have a database with data, let’s move on and start building our website
to display and work with that data.

Step 3.0 MVC Basics

In the beginning of this book, we created a new MVC website, Visual Studio added a lot
of stuff, which we are now going to delete so we can have a basic project to build a new
website from.
If you have trouble with any of the code in this step, download the full code from my
website and use it as a reference as you go through this book: http://www.cjtran.com/uyj.

To delete something, right click the item and select Delete:



Delete the following items:
1. Delete the App_Data folder
2. Under the App_Start folder, delete these files:
a. FilterConfig.cs
b. IdentityConfig.cs
c. Startup.Auth.cs
3. Delete all files in the Content folder
4. Under the Controllers folder, delete these files:
a. AccountController.cs
b. ManageController.cs
5. Delete the fonts folder
6. Delete the Models folder
7. Delete all files in the Scripts folder
8. Under the Views folder
a. Delete the Account folder
b. Delete the Manage folder
9. Under the Views folder, and under the Home folder, delete these files:
a. About.cshtml
b. Contact.cshtml
10. Under the Shared folder, delete these files:
a. _LoginPartial.cshtml
b. Error.cshtml
c. Lockout.cshtml
11. Under the Web.UI project, delete this file:
a. favicon.ico
b. Project_Readme.html
c. Startup.cs


Your Solution Explorer should look like this:




We have removed all nonessential files, well what I consider nonessential. However, doing
that caused errors in our project. Let’s take a look and see what happened.
Right click the project and select Build:


Building your project is just a way to tell Visual Studio to inspect your code to make sure
there are no errors. You should get this error message:



Double clicking on that error message will take you directly to the file and the line of code
that is causing the error, or you can find the Global.asax.cs file and open it as well:



Basically that line of code was used in one of the files we deleted and by building the
project, VS noticed that code was missing.
Delete the code that has the red squiggly line under it:
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);



Let’s delete more nonessential C# code.

In BundleConfig.cs, delete all the code and add this code:


using System.Web.Optimization;

namespace Web.UI
{
public class BundleConfig
{
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle(“~/bundles/jquery”).Include(
“~/Scripts/jquery-2.1.4.min.js”
, “~/Scripts/bootstrap.min.js”
, “~/Scripts/main.js”
));


bundles.Add(new StyleBundle(“~/Content/css”).Include(
“~/Content/bootstrap.min.css”
, “~/Content/site.css”
));


BundleTable.EnableOptimizations = true;
}
}
}





Go to the HomeController.cs and delete this code:

public ActionResult About()
{
ViewBag.Message = “Your application description page.”;


return View();
}


public ActionResult Contact()
{
ViewBag.Message = “Your contact page.”;


return View();
}




Right click and build your project:




Expand the Views folder, then Home folder, open Index.cshtml, and delete all the code in
that file.

Go to _Layout.cshtml which is under the Views, Shared folder, delete all the code and add
this:

<!DOCTYPE html>
<html>
<head>
<meta charset=“utf-8” />
<meta name=“viewport” content=“width=device-width, initial-scale=1.0”>
<title>My First Website</title>
@Styles.Render(“~/Content/css”)
</head>
<body>
@RenderBody()


@Scripts.Render(“~/bundles/jquery”)
@RenderSection(“scripts”, required: false)
</body>
</html>




Build the project. Go to Views, Home folder, right click on Index.cshtml and select View
in Browser.



You will see the error:


Basically this error means that the browser is trying to display this page, but can’t find the
proper code to use because we deleted it earlier. You’ll notice the resolution to this error is
towards the bottom:



There are two ways to fix this error, one is to remove Owin references, and the other is to
open web.config:



and add this code after the <appSettings> section:

<add key=”owin:AutomaticAppStartup” value=”false”/>






Go to File, and Save all your changes. Right click on Index.cshtml to view in browser, and
you will see a blank white page.

Our page is not too exciting anymore, is it? We have removed everything that makes it
pretty and function well. We have removed nonessential files and nonessential code from
our project, and for now have a bare bones working project. No worries we will make it
beautiful and responsive soon, but now, let’s go through and understand our project. And
don’t worry if you don’t understand everything we are about to go through, just get an
understanding of how the project is organized.
Expand Properties and open AssemblyInfo.cs you will see the general information about
your project. You don’t have to worry about this now, just know that it exists:



Next expand the References and you’ll see lots of them. Simply put, References are a
punch of other code that makes your code works. When you get more advanced you can
remove and add references as needed to your project.



The App_Start folder has two files that will run when the website starts.

BundleConfig.cs will take all our code and combine them into small compact files which
will make the website run faster.
The RouteConfig.cs manages how people will navigate our website. For example, when
people go to a site like, www.YourSite.com/About, the RouteConfig.cs knows to take the
“About” path and send the user to the proper part of the site.




The Content folder is empty now and later we will add more files to make the site look
pretty, specifically CSS files.


The Controllers folder has a HomeController.cs and an Index action. Simply put, a
Controller’s job is to control or direct which page to display when users click on different
pages of your site. The RouteConfig.cs works with the Controller to direct users to the
proper pages. For example, if people go to www.YourSite.com/Home, it will take them to
the HomeController and the default action of Index.
Simply put, the action (ActionResult) is like the specific location in your site. You can
think of a Controller as a street and the action is the driveway. So when someone visits
your house, they need your address, which is the URL, www.YourSite.com. Then they
need to know what street you live on, which is like the Controller. And then they need to
know which driveway is yours, which is like the Action. This is a very simple example,
but you can think of a Controller that way. It’s just code that tells other code where to send
users when they visit your site.



The Scripts folder is empty now and will later contain JavaScript files which will manage
the behavior of your site:



The Views folder has all the HTML files for your site and directly maps to the Controllers.
For every Controller and Action, there will be a corresponding View. You’ll notice that
there is a Home folder with an Index.cshtml which is the same structure as the
HomeController.cs and the Action Result Index:



MVC files have the extension CSHTML instead of HTML, because it allows for C-sharp
code inside HTML code. This coding style uses the Razor syntax. For example, go to
Index.schtml and add this code:
@DateTime.Now.Millisecond




Save your file and refresh your browser 3 times in a row. Notice each time the browser
refreshes the milliseconds changes.


The C-sharp code we added in the HTML file, tells the browser to display the current
millisecond the instant it refreshes. So it is very convenient to use Razor to add C-sharp
code to our HTML files because HTML code can only do so much. HTML is meant to
give pages a structure but using Razor syntax with C-sharp you can do much more, like
fetching data from a database to display to users.
Next is the _Layout.cshtml file.



This file defines the look for all your pages. This is where we will want to put the
navigation menu, the header, and footer for your site. Anything we put on this page will be
consistently displayed on all pages that inherits, or uses _Layout.cshtml. The key code on
that page is @RenderBody(). If you delete that code, save the file and refresh your browser,
you will get an error. The reason is because the browser doesn’t know what page to
display because we haven’t told it. The error will look like this:



Another key file is the _ViewStart.cshtml



Notice this code points to the _Layout.cshtml. When the browser tries to display
Index.cshtml, it will start with the _ViewStart.cshtml then go to Layout.cshtml, and then
show the Index.cshtml.
By now you may have already figured out that you can create multiple Layout pages,
which is very common for sites that want to have a different look for different users. For
example, let’s say you had a site where you want all the “regular” users to have one view,
while the “upgraded” users have a different view. The Layout page allows to you easily
manage the look of all your pages without having to add or change each page in your site.
Next is the web.config file under the Views folder, which you don’t have to touch but just
know that it’s there and can be used for custom settings.



Another key file is the Global.asax.cs which is the entry point or starting point for your
website. When your website starts, it runs this code first. and so any code you add here
will run when the application starts.



The next file is the packages.config, which you don’t have to worry about and contains the
settings for packages for your project. You can read about it here:
http://stackoverflow.com/questions/6304293/asp-net-mvc3-what-is-the-packages-config-
for

And the last file is the web.config, which is the main file that has all the configurations for
your website. For example, if you want to have a secure page and want to make people
sign in to your site, you would add special code to the web.config. Or if you want to add a
connection to a database, you would add code to the web.config file. There are lots of
settings you can add to the web.config, because it contains all the settings for your
website.
Go back to Index.schtml and delete the code we added earlier: @DateTime.Now.Millisecond
Now that we have completely stripped our MVC website down to the bare minimum, let’s
build it back up and make a great looking and functioning website.

Step 3.1 MVC Areas

One useful feature of MVC is called Areas, which is intended to organize your website
and you can read about it here: https://msdn.microsoft.com/en-
us/library/ee671793(v=vs.100).aspx

An Area is like a big subset of your website. For example, you can have an Area called
www.YourSite.com/Secure or www.YourSite.com/Public. Think of an Area as a city. Just
as every city has many houses, buildings and streets, an Area can have lots of pages that
are organized in specific sections.

You can add an area by right clicking on your project, select Add and then Area:



Name your area Friends and click Add:



Your default area should look like this:



Notice that in the Content folder, there is now a Site.css. It was added by default when the
area was added. Open it and delete all the code in that file.
Right click the Controllers folder and add a new one:




Pick the empty controller and click Add:


Name it “MainController” and click Add:


Right click to Build the project:



Right click on the Index action and select Add View:



Leave the View name as is and click Add


Delete all the code and add this code:

<div class=“container”>
<h2>This is my friends area!</h2>
<hr />
<table class=“table table-hover”>
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
</tr>
</thead>
<tbody>
<tr><td>Frank</td><td>Faust</td></tr>
<tr><td>Dillion</td><td>Nguyen</td></tr>
<tr><td>Christopher</td><td>Tran</td></tr>
<tr><td>Elon</td><td>Musk</td></tr>
</tbody>
</table>
</div>



Right click the Index.cshtml and select View in Browser.

The important part to notice is that the URL says Friends. When users visit your site and
enter the forward slash Friends, they will be taken to the “Friends area”. Try to go to the
Friends area, by going to the address bar, delete the “/Main/Index” and hit the Enter key.
You will see that the browser can’t find your area:


Let’s fix that by going to FriendsAreaRegistration.cs and open the file. Add this code after
the new keyword and the left squiggly bracket symbol (including the comma):

controller =“Main”,


Your complete code should look like this:


Build the solution.
Adding the controller code is the key to making areas work. You have to tell the controller
what area you want it to go to.
Refresh your browser and notice the Friends area now appears.
Another thing to notice is that there are two _layout.cshtml files. Since we want the same
look for the entire site, delete _Layout.cshtml in the Friends area.




Change the code in _ViewStart.cshtml in the Friends area to this code:

@{
Layout = “~/Views/Shared/_Layout.cshtml”;
}




Save your changes, refresh the browser and see the difference:


Since we don’t need the Models folder, you can delete it.


Sometimes you may want to take a user to a specific Area when they visit your site. You
can add this code to the Home controller and it will redirect users to the Friends area:


using System.Web.Mvc;


namespace Web.UI.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return RedirectToAction(“Index”,“Friends/Main”);
}
}
}



Build your project.
Right click on Index action and select Go to View. Then on that view, right click and
select View in Browser. Notice that instead of going to the Home view, the page is
redirected to the Friends area and the Index action.
You can use areas to help keep your website organized and can create as many Areas as
needed.
Now that we have a basic MVC website and have one area, let’s move on to make it look
more lively.

Step 4.0 CSS Bootstrap

One of the most noticeable aspects of your website will be how it looks. With many tools
available on the web, you can build absolutely spectacular websites. Since you are just
beginning and don’t know much about coding with Cascading Style Sheets (CSS), we will
use existing CSS frameworks to get up and running quickly. There are lots of them out
there, and we will use Bootstrap.
Bootstrap is basically a big CSS file (and JavaScript), with lots of code that predefines
colors, fonts, and many other styling features. For example, later when we work with a
data grid, we will use the Bootstrap’s CSS table class to show row hover and other grid
specific styling. Bootstrap has lots of other CSS classes for buttons, textboxes, modals,
dropdowns, and much more to make every piece of your website look and respond well on
a desktop computer and mobile devices. You can read more about Bootstrap here:
http://getbootstrap.com
There are two types of code, one is client side and the other is server side. Client side code
is mainly referred to as HTML, JavaScript and CSS. Server side code, in this book is C-
sharp. Client side code is code that the web browser uses to display a web page. Server
side code is code that a web server will execute, like checking if the user has logged in
properly or going to the database to get data.
CSS is a client side code which makes websites look good and respond well to different
devices. When you go to a webpage, the browser will look at all the code on that page and
find the CSS code that defines what that page should look like. For example, CSS code
will tell the browser how big the font should be or what colors the buttons are, or what
images to load. CSS allows developers to control the look of their websites.
In order to use Bootstrap, let’s download it and add it to our project. Go here:
http://getbootstrap.com/getting-started/#download and click on the Download Bootstrap
button.
You can also download it from my website here: http://www.cjtran.com/uyj.
Find the location on your computer where it was downloaded, most likely the Downloads
folder, and unzip the file. Once extracted open the folder bootstrap-3.3.5-dist:



You’ll notice that there are three folders: a css folder, a fonts folder, and a js folder. The
fonts folder contains Glyphicons, which you can read about here:
http://getbootstrap.com/components . The js folder is for JavaScript files specific to
Bootstrap which we will use later.
For now, open the css folder and find the file bootstrap.min.css:


Add bootstrap.min.css to the Web.UI project by dragging it from the extracted folder and
dropping it into the Content folder in your project.
Or you can add the bootstrap.min.css file to your project by right clicking on the Content
folder, select Add and then Existing Item.



Use the window to locate your bootstrap.min.css file that was just extracted and click the
Add button.



With Bootstrap added, your Solution Explorer should look like this:



Remember we already have code in BundleConfig.cs for the styling to work:


bundles.Add(new StyleBundle(“~/Content/css”).Include(
“~/Content/bootstrap.min.css”
, “~/Content/site.css”
));


BundleTable.EnableOptimizations = true;



Let’s see how bootstrap makes our website look better. Open the Index.cshtml in the
Friends area we created in the step for MVC Areas. Right click on Index.cshtml and select
View in Browser.



Your webpage should look somewhat better now with Bootstrap added to your project.
Notice that we added the CSS class “hover” to the table, so whenever you move your
mouse over the rows, it will highlight that row.
Although this is a simple example, you can see how quick and easy it is to apply Bootstrap
and make your site look good. Check out their website for other features you can use:
http://getbootstrap.com/css

We will put aside working with CSS code until the end of this book because hopefully as
we go through the book and add more CSS code to the project, you will start to see how it
works and get familiar with it.

Step 5.0 Models with EF

To work with data, we need a way to tell C# code what data means. Remember that T-SQL
code is a programming language for SQL database, and since C# is a .NET programming
language, it doesn’t understand the database unless it is translated. Since we already have
the data in the database from the previous step, like the FirstName and LastName fields,
we just need a way to convert that data into objects that C# code can understand. One way
to do this is to reverse engineer the database using a tool called the Entity Framework
(EF). You can read about it here: http://www.asp.net/entity-framework
Instead of having to manually write code for every object in the database, EF will quickly
look at everything in our database and map the code for us. Then all we have to do is use
C# code to access those objects and display the data to users.
To get access to our data using C#, let’s first create a data project, then map our database
objects using EF. The mapped objects are what we call a “Model”. We could just create a
“Data” folder in our Web.UI project, but we want to keep things organized based on the
entities we are working with. This technique is just good programming practice and you’ll
see it more in the business world. As you work with larger projects, there will be hundreds
or even thousands of code files, and creating a project for each entity is a good way to
keep things organized.
Right click on the solution and select Add, New Project:




In the left panel, select Installed, Visual C#, then Windows. In the center, click Class
Library. Enter a project name, like “Web.Data”. Pick a Location for the project or just
leave it as is. Click OK:



Your default project should look like this and you can delete the Class1.cs because we
don’t need it:



The job of the Web.Data project is to handle all data related tasks, like fetching data or
updating the database. The job of the Web.Model project is to define the objects you are
working with, which we will create in the next step. And the job of the Web.UI project is
to display whatever we tell it.
For example, let’s say you ask your friend to go get you a pizza. The Model would be the
Pizza, which has toppings, the size of the pizza, and the type of pizza, like round, square,
or flat. The UI would be how it will look, like the cheese color will be yellow, the veggies
colors will be red and green, and the box will have the logo of the company that made it.
The Data would be like the price of the pizza, your credit card information, and address.
The purpose of each project is to do a specific task and manage that task. When projects
get very complicated, this is a good way to keep your work organized but it is also a
standard pattern design and has to do with the design pattern called “Separation of
Concerns”. A good book is Professional ASP.NET Design Patterns Kindle Edition by
Scott Millett: http://www.amazon.com/Professional-ASP-NET-Design-Patterns-
Millett/dp/0470292784/ref=sr_1_1?ie=UTF8&qid=1449251371&sr=8-
1&keywords=Professional+ASP.NET+Design+Patterns

Now that we have a data project let’s add the Entity Framework to map our data.
Add a new folder named “EF”:



Right click on the EF folder, and select Add, New Item:



In the left panel select Data. In the center panel, select ADO.NET Entity Data Model. At
the bottom, leave the Name as is, and click Add:




Make sure EF Designer from database is selected and click Next:



Click New Connection:



If asked, select “Microsoft SQL Server” as the Data source and click OK:



Enter your SQL server name:



(If you completed the step for SQL Server Installation, you should have SQL server
express installed. Open SSMS to find your server name)





Open the database name dropdown and select your database and click OK:



Leave the default values and Click Next:





You can leave the default framework as 6.x and click Next:



Expand Tables, then dbo, check your table, and click Finish:





Once EF finishes mapping all of the database tables, expand Model1.edmx and notice all
the tables in the database are now generated as C# code. The EDMX file should look like
this:




Remember that if your SQL table does not have a primary key you won’t be able to map
it.
Right click and build Web.Data. If the build fails and you have errors, delete the EF folder,
close Visual Studio and start from the beginning.
Notice that there is now a connection string to the database in the app.config:


Simply put, a connection string is XML code that tells C# code where to look for the data.
Think of a physical string that is used to connect something together, like a kite. The string
connects the person holding it to the kite. So in this case, the data connection string just
points to the database with values specific for EF so that it knows how to map the data.
XML is outside the scope of this book. For now, just know that it exists and if you want to
add more database connections or make changes, you will do it in the app.config.
The key thing to notice is the data source is the name of your actual SQL server, and the
initial catalog is the name of the database.



Copy the connection string from the app.config in the Web.Data project and paste it in the
web.config in the Web.UI project:



Save all changes.
Since EF mapped new C# code to the project, it is always a good idea Build your project
when there is a C# code change. If you get errors in your project, try to resolve them or
start this step over.
Now that we have a mapping of our data, let’s move on and create C# code for the models.

Step 5.1 Models C-Sharp

C# (pronounced like the musical note, see sharp) is the programming language of choice
for this book. You can read more about it here: https://msdn.microsoft.com/en-
us/library/z1zx9t92.aspx and
https://en.wikipedia.org/wiki/C_Sharp_(programming_language)
Most of the time C# is used with the term .NET (dot NET) and you can read about .NET
here: https://msdn.microsoft.com/en-us/library/zw4w595w(v=vs.110).aspx and
https://en.wikipedia.org/wiki/.NET_Framework
Simply put, C# is a programming language and .NET is a big library of C# code which
developers use to make their code more powerful.
For example, if you wanted to dig a pool in your back yard you can use a shovel or a
Backhoe loader. The shovel works fine but would take a long time to dig a big enough
hole for a pool. However, if you run into a big rock, the shovel will not be big enough to
move it out of the way. If you used the Backhoe, it would be much easier and faster. So
the Backhoe is kind of like the .NET library. Instead of writing lots of code over and over,
developers can use the .NET library to write more powerful code with less work.
C# is a huge topic so let’s just keep it simple and work with basic programming
techniques. In this step we will start using C# to define our models.
Think of a model as the object or core entity of our code. For example, there are objects
everywhere in our daily lives. A car is an object, and has many properties, like the wheel,
trunk, gas tank, windshield, and so on. Just as we know what a car is, a computer needs to
know what objects it is working with. The model is a way to tell a computer about
different objects and their properties. Let’s see this in action by creating a Friend model.
Go to your solution, right click and Add and New Project. In the left panel select
Windows. In the center, pick Class Library, and enter “Web.Model” for the Name. Then
click OK:


Once the project is created, you can delete the Class1.cs file that was created by default.
Right click Web.Model, and Add and New Item. Add a new class file and name it
FriendModel:


If you have trouble with any of the code, download the full code from my website and use
it as a reference as you go through this book: http://www.cjtran.com/uyj.


Delete all the code in FriendModel.cs, and add this code to your file and make sure it
looks like this:


using System;
using Web.Model.Common;


namespace Web.Model
{
public class FriendModel
{
public int MyFavoriteFriendsID { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public string MobilePhone { get; set; }
public Nullable<System.DateTime> DateOfBirth { get; set; }


private string dateOfBirthAsString;


public string DateOfBirthAsString
{
get
{
if (DateOfBirth != null)
{
dateOfBirthAsString = DateOfBirth.Value.ToShortDateString();
}


return dateOfBirthAsString;
}
set { dateOfBirthAsString = value; }
}


private string dateOfBirthAsStringForInput;


public string DateOfBirthAsStringForInput
{
get
{
if (DateOfBirth != null)
{
dateOfBirthAsStringForInput = DateOfBirth.Value.ToString(“yyyy-MM-dd”);
}


return dateOfBirthAsStringForInput;
}
set { dateOfBirthAsStringForInput = value; }
}


public Nullable<System.DateTime> DateCreated { get; set; }


private byte? age;


public byte? Age
{
get
{
if (DateOfBirth != null)
{
age = UtilitiesModel.CalculateAge(DateOfBirth.Value);
}


return age;
}
set { age = value; }
}


private string firstName;


public string FirstName
{
get
{
switch (firstName)
{
case “Frank”:
firstName = “Franky”;
break;


case “Dillion”:
firstName = “Mr. Million”;
break;


default:
break;
}


return firstName;
}
set
{
if (value == “Christopher”)
{
value = “Yin”;
}


firstName = value;
}
}
}
}



Create a Common folder and add a UtilitiesModel to it:


Any code that is used often can go into the “Common” folder. For example, if you know
you need to format phone numbers for different countries, that code can go into the
Common folder. Instead of having the same code scattered throughout your project, you
can keep it in one place in the common model.
The “utilities” model is just another naming convention to identify what that object is
doing. You can put other methods in here, like to validate a phone number and to make
sure that it is actually a number and does not contain letters or special characters. A
utilities model is just another way of organizing code so we know that its job is to do
something useful for us.

Delete all the code in UtilitiesModel.cs and add this code:


using System;


namespace Web.Model.Common
{
public class UtilitiesModel
{
public static byte? CalculateAge(DateTime input)
{
byte? result = null;
try
{
if (null != input)
{
var birthYear = Convert.ToInt16(input.ToString(“yyyy”));


var currentYear = DateTime.Now.Year;


result = Convert.ToByte(currentYear - birthYear);
}


return result;
}
catch
{
return null;
}
}
}
}


Right click Web.Model and Build it.
Let’s examine that code.
Open FriendModel.cs and notice the C# types for each property, like string and byte. You can
read about C# types here: https://msdn.microsoft.com/en-us/library/ya5y69ds.aspx
Simply put, a C# type tells the computer what kind of property the object is. For example,
if I said Salmon, you already know it is a fish. And if I said poodle, you know it is a dog.
When we declared phone as a string, we are letting the computer know that that property
will be used for people’s names instead of a number.
We will use the current year and the birth year entered to calculate the person’s age: public
byte? Age.


Notice the age uses more code to calculate with which is found in the UtilitiesModel:
age = UtilitiesModel.CalculateAge(DateOfBirth.Value);


To find out where code is coming from, right click the code and select Go To Definition.
For example, right click on CalculateAge and select Go To Definition:


A good way to use the model is to set and get the value of your objects as seen in the first
name property. For example, every time you have a friend named Frank, you can use the
set accessor to change his name to Franky.
In a large project, if you didn’t use the set accessor to change the values, you would have
to find every place in your code and make the change. Instead of having to do that, the
solution is to write code in the Model layer. That way you can make the change in one
place and no matter what changes, either the database or the user interface, your code will
still work.
In order to see how this works, we have to create code that simulates pulling data from the
database.

Go to Web.Data, add a new class file and name it “DataDemoGetAccessor.cs”:


Delete all the code and add this:


using System.Collections.ObjectModel;
using Web.Model;


namespace Web.Data
{
public class DataDemoGetAccessor
{
public static Collection<FriendModel> FetchData()
{
var results = new Collection<FriendModel>();


var model1 = new FriendModel();
model1.FirstName = “Frank”;
model1.LastName = “Faust”;
results.Add(model1);


var model2 = new FriendModel();
model2.FirstName = “Dillion”;
model2.LastName = “Nguyen”;
results.Add(model2);


return results;
}
}
}


That code simply fills two objects and returns it to the method that called it.

Right click to add a reference:


In the left panel, select Projects then Solutions. In the center check Web.Model and click
OK:


Adding a reference is just a way to link code in different projects. Remember that we have
three different projects, and each project only knows about code within it. If we have code
in the data project that is written in the model project and don’t add a reference, the data
project won’t know where that code is.

Right click Web.Data and build it.

Go to Web.UI, the Friends area, and add a new controller and name it “TestController”.
Delete all the code in that file and add this:

using System;
using System.Web.Mvc;
using Web.Data;
using Web.Model;


namespace Web.UI.Areas.Friends.Controllers
{
public class TestController : Controller
{
public ActionResult Index()
{
return View();
}


public ActionResult Getter()
{
var data = DataDemoGetAccessor.FetchData();


return View(data);
}
}
}



Right click the getter action and add a view:


Leave the default values and click Add:



Delete all the code in that view and add this code:


@model IEnumerable<Web.Model.FriendModel>
@if (Model == null || Model.Count() == 0) { return; }


<table class=“table table-hover table-striped” style=”cursor: pointer;“>
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
</tr>
</thead>
<tbody>


@{
foreach (var item in Model)
{
<tr>
<td>@item.FirstName</td>
<td>@item.LastName</td>
</tr>
}
}
</tbody>
</table>


Notice that code has the model count equal to zero, not the letter “O” ( Model.Count() == 0 ).
Right click Web.UI to add a reference:



In the left panel, select Projects then Solutions. In the center panel, check Web.Data and
Web.Model and click OK:



Right click Web.UI and build it.
Now that we have our code in place, let’s see how the getter accessor works.
Right click Getter.cshtml to view in browser:


Notice that any time there is someone named Frank, it will change it to Franky and Dillion
is changed to Mr. Million.
That technique uses the “get” accessor, also called “getters”, and you can read about it
here: https://msdn.microsoft.com/en-us/library/w86s7x04.aspx

The other accessor is called the “set” accessor, also called as “setters”, which can be used
to update our data. Just as the get accessor is use to change data when we get/fetch it from
the database, we can use the set accessor to set/change the data before it is sent to the
database or whatever the end result is. This technique is helpful when displaying one
format to the user, but you need to save it in another format for the database.
For example, let’s say you want to display a telephone number in this format, (123) 456-
7890. When there are millions or even billions of rows, the left and right parenthesis and
the dash takes up extra space in a database. Therefore, we want to store only the necessary
data in this format, 1234567890.

Notice that the setter says that if there is a first name that equals “Christopher”, then set it to
“Yin”.

set
{
if (value == “Christopher”)
{
value = “Yin”;
}


firstName = value;
}



In order to use the setter, we will create a method to trigger it.

Add a new class file called “DataDemoSetAccessor” to the Web.Data:



Delete all the code in that file and add this:

using System.Collections.ObjectModel;
using Web.Model;


namespace Web.Data
{
public class DataDemoSetAccessor
{
public static Collection<FriendModel> DemoSetAccessor(FriendModel items)
{
var results = new Collection<FriendModel>();


var model = new FriendModel();
model.FirstName = items.FirstName;
model.LastName = items.LastName;
results.Add(model);


return results;
}
}
}



Build the data project.

Go to the Web.UI project and in the Friends area, Test controller, and add this code:

public ActionResult Setter()
{
var model = new FriendModel();
model.FirstName = “Christopher”;
model.LastName = “Tran”;


var data = DataDemoSetAccessor.DemoSetAccessor(model);


return View(data);
}



Right click and add a view:



Delete all the code in that view and add this code:

@model IEnumerable<Web.Model.FriendModel>
@if (Model == null || Model.Count() == 0) { return; }


<table class=“table table-hover table-striped” style=”cursor: pointer;“>
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
</tr>
</thead>
<tbody>


@{
foreach (var item in Model)
{
<tr>
<td>@item.FirstName</td>
<td>@item.LastName</td>
</tr>
}
}
</tbody>
</table>


Notice that code has the model count equal to zero, not the letter “O” ( Model.Count() == 0 ).
Right click and build your solution:



Navigate to the Setter action:


Notice that the first name has been set to the value we wanted, namely Christopher has
been changed to Yin.
Using the setters and getters is handy when there are hundreds of objects and properties to
work with. Instead of changing code everywhere, it can be done in one place in the model
and anytime that object is instantiated or used, the code will know what to do base on
what we coded. With our models created, we can move on and use C# to work with data
using CRUD operations.

Step 6.0 C-Sharp Creating Data

There are many ways to get data into a database. We already know that using SSMS we
can write TSQL script or use the GUI to manually enter data. When working with C#
code, we can use the Entity Framework to insert data to the database. Let’s see this in
action.

Go to Web.Data, add a new folder called “CREATE”, and add a new class file inside that
folder called “CreateEntityFriends.cs”:



Delete all existing code in CreateEntityFriends.cs and add this code:


using System;
using Web.Data.EF;
using Web.Model;


namespace Web.Data.CREATE
{
public class CreateEntityFriends
{
public static string SingleEntity(FriendModel model)
{
try
{
using (var dataContext = new MyFirstDatabaseEntities())
{
var entity = new MyFavoriteFriend();


entity.FirstName = model.FirstName;
entity.LastName = model.LastName;
entity.Email = model.Email;
entity.MobilePhone = model.MobilePhone;
entity.Age = model.Age;
entity.DateOfBirth = model.DateOfBirth;
entity.DateCreated = model.DateCreated;


dataContext.MyFavoriteFriends.Add(entity);
dataContext.SaveChanges();


return string.Empty;
}
}
catch (Exception exception)
{
return exception.ToString();
}
}
}
}



Build the project.
Let’s examine that code.
At the top we have a using statement which simply links to other code needed for our code
to work. The first using is for the System namespace which is for any code that is built in
the .NET framework and in this case it is being used in the catch block for the Exception
object to handle errors. The second using is for the code in the data project, which points to
the data model created in the EDMX. And the third using points to the FriendModel in the
Web.Model project. With the proper references to our code, let’s examine the actual
method that insert the data.
Notice the class is called CreateEntityFriends which is a naming convention and says that code
is for creating data for the “friends” table. It is public so we can call it in our Web.UI code.
If we made it private we would not be able to access it outside of this code file.
The method CreateEntity is static string which means once the code is done, it will return some
message, otherwise it will return an error message. The method has a FriendModel as a
parameter which is seen in between the left and right parenthesis, so we can expect all or
some properties of that model to be passed in, like a phone number or age.
This line of code says we are working with the MyFirstDatabase: using (var dataContext = new
MyFirstDatabaseEntities()).Notice there is another using code here. This using is a block, which is
designed to release the resources declared inside the code block once it is done.
The var entity, says to insert data into the table, MyFavoriteFriends. Then the entity is set to each
property that was passed in to the model.
Next the entity is added to the data context and the data is committed to the database in the
method SaveChanges().

Now that we have C# code to insert data, lets create a way to enter data.

Go to Web.UI, the Friends Area and open the MainController.cs:




Delete all existing code and add this code:

using Newtonsoft.Json;
using System;
using System.Web.Mvc;
using Web.Model;


namespace Web.UI.Areas.Friends.Controllers
{
public class MainController : Controller
{
public ActionResult Index()
{
return View();
}


public ActionResult All()
{
return View();
}
[HttpPost]
public ActionResult Create(string jsonData)
{
try
{
if (string.IsNullOrEmpty(jsonData)) return Json(“Missing Required Data.”);


var model = Newtonsoft.Json.JsonConvert.DeserializeObject<FriendModel>(jsonData);
model.DateCreated = DateTime.Now;
var result = Web.Data.CREATE.CreateEntityFriends.SingleEntity(model);


return Json(result);
}
catch (Exception exception)
{
return Json(“Data error!”);
}
}
}





Right click the All action and add a new View:


Delete all existing code in All.cshtml and add this code:



<div class=“container”>
@Html.Partial(“~/Areas/Friends/Views/Partials/PartialCreate.cshtml”)


<div class=“panel panel-default”>
<div class=“panel-heading”>
<h3 class=“panel-title”>Search for Friends</h3>
</div>


<form class=“form-inline”>
<input id=“inputSearchFriends” onkeyup=”SearchForFriends(this.value)” type=“text” class=“form-control”
placeholder=“Search for a friend” maxlength=“10”>
<div class=“form-group”>
<button onclick=”ClearSearch()” id=“buttonClearSearch” type=“button” class=“btn btn-default btn-sm”>Clear
search</button>
</div>
<button onclick=”ShowAddPanel()” id=“buttonShowAddPanel” type=“button” class=“btn btn-primary”>Add
Friend</button>
</form>
<div id=“divSearchResults”></div>
</div>


<div class=“panel panel-default”>
<div class=“panel-heading” onclick=”CommonToggleDiv(‘#divPanelPartialData’)” style=”cursor:pointer;“>
<h3 class=“panel-title”>All Friends</h3>
</div>
<div id=“divLoading” class=“alert alert-success”><center><h2>Loading…</h2></center></div>
<div id=“divPartialData”></div>
</div>
</div>



A Partial view is used to organize and reuse your code and you can learn more about it
here:
https://msdn.microsoft.com/en-us/library/dd410123%28v=vs.100%29.aspx?
f=255&MSPPError=-2147217396
http://www.codeproject.com/Tips/617361/Partial-View-in-ASP-NET-MVC

Now we need to add a partial view to display a way for to add records to the database.
Create a new folder under the Views folder and name it “Partials”. Right click the folder
and add a new view called, PartialCreate.cshtml. Delete all existing code in
PartialCreate.cshtml and add this code:


@{
var crud = “Create”;
var CreateDivCRUD = crud + “divCRUD”;
var CreateSpanResultMessage = crud + “spanResultMessage”;
var CreateButtonCancel = crud + “buttonCancel”;
var CreateButtonSubmit = crud + “buttonSubmit”;
var CreateModel00 = crud + “FirstName”;
var CreateModel01 = crud + “LastName”;
var CreateModel02 = crud + “Email”;
var CreateModel03 = crud + “MobilePhone”;
var CreateModel04 = crud + “DateOfBirth”;


}
<div id=”@CreateDivCRUD” class=“panel panel-default” style=”display: block;“>
<div class=“panel-heading”>
<h3 class=“panel-title”>Add Friend</h3>
</div>
<div>
<div class=“form-group”>
<label>First Name</label>
<input id=”@CreateModel00” type=“text” class=“form-control” placeholder=“Enter first name” maxlength=“50”>
</div>
<div class=“form-group”>
<label>Last Name</label>
<input id=”@CreateModel01” type=“text” class=“form-control” placeholder=“Enter last name” maxlength=“50”>
</div>
<div class=“form-group”>
<label>Email</label>
<input id=”@CreateModel02” type=“email” class=“form-control” placeholder=“Enter email” maxlength=“50”>
</div>
<div class=“form-group”>
<label>Mobile Phone</label>
<input id=”@CreateModel03” type=“text” class=“form-control” placeholder=“Enter phone number”
maxlength=“25”>
</div>
<div class=“form-group”>
<label>Birthday</label>
<input id=”@CreateModel04” type=“date” class=“form-control” placeholder=“Enter birthday”>
</div>
<button id=”@CreateButtonCancel” type=“button” class=“btn btn-default”>Cancel</button>
<button id=”@CreateButtonSubmit” type=“button” class=“btn btn-primary”>Add Friend</button>
<span id=”@CreateSpanResultMessage“></span>
<p>&nbsp;</p>
</div>
</div>



Build your solution. Right click All.cshtml and view in browser:





Using the browser, navigate to the All view in the Friends area. Click the Add Friend
button to see the panel:



Clicking the buttons won’t do anything now because we have to add more code to make
those buttons work, which we will do later when we work with JavaScript. We could use
the MVC pattern to post our data but I want to show you how to submit data using
JavaScript. You can learn more about MVC here: http://www.asp.net/mvc


For now, let’s add some test code to see how we can insert data using C# code.

Add this code to the Test controller:

public ActionResult CreateTest()
{
try
{
var model = new FriendModel();
model.FirstName = “Test” + DateTime.Now.Millisecond.ToString();
model.LastName = “Create”;
model.Email = “test” + Guid.NewGuid().ToString() + “@email.com”;
model.MobilePhone = string.Empty;
//model.Age = calculated in the model


DateTime start = new DateTime(1990, 1, 13);
Random gen = new Random();
int range = (DateTime.Today - start).Days;
model.DateOfBirth = start.AddDays(gen.Next(range));


model.DateCreated = DateTime.Now;


var result = Web.Data.CREATE.CreateEntityFriends.SingleEntity(model);


return View();
}
catch (System.Exception exception)
{
return Json(exception.ToString());
}
}


Build your solution. Right click the CreateTest method and add a view for it.
That code will create one record of data when executed. Let’s examine it quickly.
It’s always a good idea to anticipate errors and that’s why we have a try/catch statement.
In the try, we initialize a Friend model, which tells the computer we want to work with that
object. We set each property to a value.
Notice for the first name we concatenate the word “Test” with the current millisecond.
This is just to keep the first name relatively different. If we added 100 more records, we
can distinguish them apart. It is not necessary to do this, since we already have a primary
key in the table, named MyFavoriteFriendsID, and that field already makes each record unique.

The email uses a GUID, which is a globally unique identifier, to ensure that the email is
unique. Using GUID’s is a good way to keep your table unique if you don’t want to use a
primary key.

The phone is set to a blank value.

The Age is commented out and will not be set. Remember we have code in the model that
will calculate that.

For the birth date, we create a new object to randomly create the year, month and day.

The created date is set to today.

With all the values add to our model, we then call the create method in the data layer, and
pass in the model.

And last the code returns to the view.


Right click the CreateTest.cshtml and view in browser:



The code will run and create a record in the database and then load the page.


Refresh the browser 10 more times.

Let’s verify that those records have been added to SQL server. Open SSMS, connect to
your server, right click on your database, MyFirstDatabase, to open a query window. Add
this TSQL code and Execute it:


SELECT TOP 1000 [MyFavoriteFriendsID]
,[FirstName]
,[LastName]
,[Email]
,[MobilePhone]
,[Age]
,[DateOfBirth]
,[DateCreated]
FROM [MyFirstDatabase].[dbo].[MyFavoriteFriends]
WHERE [LastName]= ‘Create’



Notice that the new records have been added, and that the Age has been calculated.


So there you have it, we just used C# code to run the create operation. There are more
complex scenarios for inserting data but for now you have the basic knowledge on how to
add data to a database.
Next we will use the READ operation to display data.

Step 6.1 C-Sharp Displaying Data

Of the four C# CRUD operations, READ is used to fetch and display data. Let’s create a
folder in our data project to put C# code for reading data.
Go to the Web.Data project, right click and add a new folder named “READ”. Right click
on the READ folder and add a new item and name it “ReadEntityFriends.cs”:


Notice the naming convention. This is a “READ” operation, which distinguishes it from
UPDATE or CREATE operation. It is an “entity” name “Friends”. You can name these
files whatever you want, but this is a good naming convention.

Your project should look like this:


Delete all existing code in ReadEntityFriends.cs and add this code:


using System;
using System.Collections.ObjectModel;
using System.Linq;
using Web.Data.EF;
using Web.Model;


namespace Web.Data.READ
{
public class ReadEntityFriends
{
public static Collection<FriendModel> FetchManyEntities ()
{
try
{
var data = new Collection<FriendModel>();
using (var context = new MyFirstDatabaseEntities())
{
var query = from entity in context.MyFavoriteFriends
orderby entity.DateCreated descending
select entity;


foreach (var item in query.Take(100))
{
var model = new FriendModel();
model.MyFavoriteFriendsID = item.MyFavoriteFriendsID;
model.FirstName = item.FirstName;
model.LastName = item.LastName;
model.Email = item.Email;
model.MobilePhone = item.MobilePhone;
model.Age = item.Age;
model.DateOfBirth = item.DateOfBirth;
model.DateCreated = item.DateCreated;


data.Add(model);
}
return data;
}
}
catch (Exception exception)
{
return null;
}
}


public static Collection<FriendModel> FetchSearchItem(string searchItem)
{
try
{
var data = new Collection<FriendModel>();
using (var context = new MyFirstDatabaseEntities())
{
var query = from entity in context.MyFavoriteFriends
where entity.FirstName.Contains(searchItem) ||
entity.LastName.Contains(searchItem)
orderby entity.LastName, entity.FirstName
select entity;


foreach (var item in query.Take(25))
{
var model = new FriendModel();
model.MyFavoriteFriendsID = item.MyFavoriteFriendsID;
model.FirstName = item.FirstName;
model.LastName = item.LastName;
model.Email = item.Email;


data.Add(model);
}
return data;
}
}
catch (Exception exception)
{
return null;
}
}


public static FriendModel SingleEntity(int entityID)
{
try
{
using (var context = new MyFirstDatabaseEntities())
{
var query = from entity in context.MyFavoriteFriends
where entity.MyFavoriteFriendsID == entityID
select entity;


var model = new FriendModel();
foreach (var item in query)
{
model.MyFavoriteFriendsID = item.MyFavoriteFriendsID;
model.FirstName = item.FirstName;
model.LastName = item.LastName;
model.Email = item.Email;
model.MobilePhone = item.MobilePhone;
model.Age = item.Age;
model.DateOfBirth = item.DateOfBirth;
model.DateCreated = item.DateCreated;
}
return model;
}
}
catch (Exception exception)
{
return null;
}
}


}
}



Build the solution.
That code has three methods, two will get many records, and one will get one record. The
FetchManyEntities method executes the code in the try block and if an error occurs will return
nothing in the catch block. It is good practice handle errors in a more helpful way but for
now, we will just leave it alone.
Next there is a data variable which will be used to fill each object found from the database
and will be returned to the method that called it.
The using block creates a new instance of the data context and handles the connection to the
database and disposes the objects when done.
The var query is the key select statement which will be converted into TSQL when it hits
SQL server. Notice that code contains LINQ (the part that starts with: from entity) which you
can read more about here: https://msdn.microsoft.com/en-us/library/bb397926.aspx
Then the foreach will loop through each record found, fill up the Friends model with the
value of each property and add it to the collection to be returned.
Notice that although our select statement is getting all the records, it is in the Take()
method that we can restrict the results to 100 records. This is useful because we may not
want thousands of records being displayed at once.
The FetchSearchItem method is very similar to the FetchManyEntities method. The main difference
is that the FetchSearchItem method is searching for the first and last name that matches what
the user has entered. Notice the Contains() method after the first and last name property. The
where clause is looking for all the records in the database where the first or last name has
a specific value.
The FetchSearchItem method only returns 25 records in the Take() method, and is only filling
the properties for the ID, first name, last name, and email.
The SingleEntity method differs from the other two methods in that it will return one object.
The method still goes through the same process as the other two methods in that it uses the
same data context, has a select query, loops through each results found and fills the Friend
model. It is a static method which means it will return something and in this case a
FriendModel.

Now that we have the proper code to get data from the database, let’s move on to other
code needed for the READ operation to fully work.
As mentioned, C# is a programming language and using Razor syntax we can write C#
inside HTML files.
You can read about Razor here: http://www.w3schools.com/aspnet/razor_syntax.asp
https://www.asp.net/web-pages/overview/getting-started/introducing-razor-syntax-c

We will use Razor syntax to display data using the Friends area created in step for creating
MVC Areas.
In the Web.UI project, in the Friends area, and under the Partial folder, add a new view
called PartialData.cshtml. Delete all existing code and add this code:

@model IEnumerable<Web.Model.FriendModel>
@if (Model == null || Model.Count() == 0) { return; }


<div id=“divPanelPartialData”>


<div class=“container”>


<table class=“table table-hover table-striped”>
<thead>
<tr>
<th>@*Delete Colmun*@</th>
<th>First Name</th>
<th>Last Name</th>
<th>Age</th>
</tr>
</thead>
<tbody>


@{
foreach (var item in Model)
{
<tr id=“row@{}@item.MyFavoriteFriendsID” onclick=”ShowUpdateModal(@item.MyFavoriteFriendsID)”
title=“Click to edit” style=”cursor: pointer;“>
<td class=“rowDeleteEntity”>
<button onclick=“SetDeleteEntityID(@item.MyFavoriteFriendsID)” type=“button” class=“btn btn-danger btn-xs”
title=“Click to delete”>X</button>
</td>
<td>@item.FirstName</td>
<td>@item.LastName</td>
<td>@item.Age</td>
</tr>
}
}
</tbody>
</table>
</div>
</div>


<script>
$(function () {


$(‘.rowDeleteEntity .btn’).click(function (e) {
e.stopPropagation();
});
});


$(‘#divLoading’).hide(1000);


</script>



That code will display a list of our friends. It will show their first name, last name, and
age.
Add another view called PartialSearchResults.cshtm, delete all existing code and add this
code:


@model IEnumerable<Web.Model.FriendModel>


@if (Model == null || Model.Count() == 0)
{
<h3><span class=“label label-danger”>No data found</span></h3>
<p>&nbsp;</p>
return;
}


<div class=“panel panel-default”>
<div class=“panel-heading”>
<h3 class=“panel-title”>Search Results</h3>
</div>
<div>
<div class=“container”>
<table class=“table table-hover table-striped”>
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
</tr>
</thead>
<tbody>


@{
foreach (var item in Model)
{
<tr onclick=“ShowUpdateModal(@item.MyFavoriteFriendsID )” title=“Click to edit” style=”cursor: pointer;“>
<td>@item.FirstName</td>
<td>@item.LastName</td>
</tr>
}
}
</tbody>
</table>
</div>
</div>
</div>



Notice that code has the model count equal to zero, not the letter “O” ( Model.Count() == 0 ).

That code will display a list of results in a table. At the top, is an IEnumerable of our Friends
objects, which means it can accept many objects. Next we check if the results are empty in
the Model and display a message if that is the case. Then we have code which displays the
results in a CSS panel. We display the first and last name from the results found in the
database. Then we loop through the entire results object and create a row for each record.
The onclick event will display a popup modal when a mouse click event occurs on a row.
Remember that Razor syntax allows you to write C# code in an HTML page. The
indicator that Razor is being used is the at symbol (@). Any code after that is considered
C# code.

Add this code to the Main controller:


[HttpGet]
public ActionResult FetchAll()
{
var data = Web.Data.READ.ReadEntityFriends.FetchManyEntities();
return PartialView(“~/Areas/Friends/Views/Partials/PartialData.cshtml”, data);
}


[HttpPost]
public ActionResult FetchSingleForUpdate(string JsonData)
{
if (string.IsNullOrEmpty(JsonData)) return Json(“Missing Required Data.”);
try
{
var model = JsonConvert.DeserializeObject<FriendModel>(JsonData);
string results = string.Empty;
var data = Web.Data.READ.ReadEntityFriends.SingleEntity(model.MyFavoriteFriendsID);


var result = JsonConvert.SerializeObject(data);
return Json(result);
}
catch (Exception exception)
{
return Json(“Data error!”);
}
}


[HttpGet]
public ActionResult FetchSearchingForFriends(string searchItem)
{
var data = Web.Data.READ.ReadEntityFriends.FetchSearchItem(searchItem);


return PartialView(“~/Areas/Friends/Views/Partials/PartialSearchResults.cshtml”, data);
}



Build your solution.

That code has three actions which corresponds to the three methods in the data layer. The
first FetchAll action will make a call to the data layer and get all the records, and will return
all that data to the view called PartialData.cshtml.
The second action called FetchSingleForUpdate, will get one record based on an ID and display
that data in the update modal. We are using this query because when we update a record
we need to know what record we are working with. The grid displays all our friends, so
when we click on a row, it captures the ID using JS, then sends that ID all the way to the
database, which looks for the record and if found will return all the data we asked for.
Instead of calling a partial view, this action will convert the data into a JSON object which
is then parsed using JS and set to its corresponding controls.
The last action called FetchSearchForFriends is used for the dynamic search feature. When the
user starts typing a name, JS code will take that name and call that action passing the
values entered. Once the data, if any, is returned, the action loads that data to the partial
view called PartialSearchResults.cshtml, and loads the page with the search results.
Right click the view All.cshtml in the browser. Although we have C# code to load data for
our views, we have not written JS code to trigger it to load, which we will do soon when
we get to the steps for working with JS. For now, the view should look similar to the
previous step:



In this step we wrote code to display data for our views. We first added C# code to the
data layer to pull data from the database. Next we added code in the controller to call the
data layer and bind it to our view. Then we created a partial view to display the data by
adding HTML and C# code to our partial view.
Let’s move on and use C# code for the UPDATE operation.


Step 6.2 C-Sharp Updating Data

Besides creating and displaying data, we can also save changes to data using C# code for
the UPDATE operation.
Add a new folder called “UPDATE” to the Web.Data project, then add a class file called
“UpdateEntityFriends.cs”. Delete all existing code and add this code:

using System;
using System.Linq;
using Web.Data.EF;
using Web.Model;


namespace Web.Data.UPDATE
{
public class UpdateEntityFriends
{
public static string SingleEntity(FriendModel model)
{
try
{
using (var dataContext = new MyFirstDatabaseEntities())
{
var query = from entity in dataContext.MyFavoriteFriends
where entity.MyFavoriteFriendsID == model.MyFavoriteFriendsID
select entity;


foreach (var item in query)
{
item.FirstName = model.FirstName;
item.LastName = model.LastName;
item.Email = model.Email;
item.MobilePhone = model.MobilePhone;
item.Age = model.Age;
item.DateOfBirth = model.DateOfBirth;
}


dataContext.SaveChanges();


return string.Empty;
}
}
catch (Exception exception)
{
return exception.ToString();
}
}
}
}




Build the solution.
That update code has the same structure as the create and read code. The method is a static
string and we can expect it to return some message. The method passes in a Friend model
and we will take each property and set it to the data context so we can save the data. The
query checks the data to make sure we update the proper record, namely where the ID
being passed in matches the ID found in the database. The key code is SaveChanges(), which
is where the whole transaction is committed to the database.

Go to the Web.UI project in the Friends area, and open the All.cshtml file. Delete all
existing code and add this code: (Notice the addition of code for PartialUpdate.cshtml.)


<div class=“container”>
@Html.Partial(“~/Areas/Friends/Views/Partials/PartialCreate.cshtml”)
@Html.Partial(“~/Areas/Friends/Views/Partials/PartialUpdate.cshtml”)
<div class=“panel panel-default”>
<div class=“panel-heading”>
<h3 class=“panel-title”>Search for Friends</h3>
</div>


<form class=“form-inline”>
<input id=“inputSearchFriends” onkeyup=”SearchForFriends(this.value)” type=“text” class=“form-control”
placeholder=“Search for a friend” maxlength=“10”>
<div class=“form-group”>
<button onclick=”ClearSearch()” id=“buttonClearSearch” type=“button” class=“btn btn-default btn-sm”>Clear
search</button>
</div>
<button onclick=”ShowAddPanel()” id=“buttonShowAddPanel” type=“button” class=“btn btn-primary”>Add
Friend</button>
</form>
<div id=“divSearchResults”></div>
</div>


<div class=“panel panel-default”>
<div class=“panel-heading” onclick=”CommonToggleDiv(‘#divPanelPartialData’)” style=”cursor:pointer;“>
<h3 class=“panel-title”>All Friends</h3>
</div>
<div id=“divLoading” class=“alert alert-success”><center><h2>Loading…</h2></center></div>
<div id=“divPartialData”></div>
</div>
</div>




Under the Partials folder, add a view called “PartialUpdate.cshtml”. Delete all existing
code and add this code:



@{
var crud = “Update”;
var UpdateDivCRUD = crud + “divCRUD”;
var UpdateSpanResultMessage = crud + “spanResultMessage”;
var UpdateButtonCancel = crud + “buttonCancel”;
var UpdateButtonSubmit = crud + “buttonSubmit”;
var UpdateModel00 = crud + “FirstName”;
var UpdateModel01 = crud + “LastName”;
var UpdateModel02 = crud + “Email”;
var UpdateModel03 = crud + “MobilePhone”;
var UpdateModel04 = crud + “DateOfBirth”;
}


<div id=”@UpdateDivCRUD” class=” modal fade” tabindex=”-1” role=“dialog”>
<div class=“modal-dialog”>
<div class=“modal-content”>
<div class=“modal-header”>
<h3 class=“panel-title”>Update a Friend</h3>
</div>
<div class=“modal-body”>


<div class=“form-group”>
<label>First Name</label>
<input id=”@UpdateModel00” type=“text” class=“form-control” placeholder=“Enter first name” maxlength=“50”>
</div>
<div class=“form-group”>
<label>Last Name</label>
<input id=”@UpdateModel01” type=“text” class=“form-control” placeholder=“Enter last name” maxlength=“50”>
</div>
<div class=“form-group”>
<label>Email</label>
<input id=”@UpdateModel02” type=“email” class=“form-control” placeholder=“Enter email” maxlength=“50”>
</div>
<div class=“form-group”>
<label>Mobile Phone</label>
<input id=”@UpdateModel03” type=“text” class=“form-control” placeholder=“Enter phone number”
maxlength=“25”>
</div>
<div class=“form-group”>
<label>Birthday</label>
<input id=”@UpdateModel04” type=“date” class=“form-control” placeholder=“Enter birthday”>
</div>
<button id=”@UpdateButtonCancel” type=“button” class=“btn btn-default”>
Cancel
</button>
<button id=”@UpdateButtonSubmit” type=“button” class=“btn btn-primary”>Update Friend</button>
<span id=”@UpdateSpanResultMessage“></span>
<button onclick=”DeleteFriend()” type=“button” class=“btn btn-danger btn-xs”>Delete</button>
<p>&nbsp;</p>
</div>
</div>
</div>
</div>




Now open the Main controller in the Friends area, and add this code:

[HttpPost]
public JsonResult Update(string JsonData)
{
if (string.IsNullOrEmpty(JsonData)) return Json(“Missing Required Data”);
try
{
var model = JsonConvert.DeserializeObject<FriendModel>(JsonData);
var results = Web.Data.UPDATE.UpdateEntityFriends.SingleEntity(model);
return Json(results);
}
catch (Exception exception)
{
return Json(“Data error!”);
}
}




Build your solution.
Let’s examine that code.
The HttpPost attribute says we can only send data and won’t allow users to navigate to that
view if they tried.
The Update method has in between the parenthesis the parameter, string JsonData. This
means that when we collect user input, we will convert it into a JSON object and then
send it to the database. Learn more about JSON here: http://www.w3schools.com/json/
The try/catch block says try to run the code inside that section but if something goes wrong,
jump to the catch part of the code. This is a simple way for us to handle errors.
The if statement checks to make sure that there is data and does not run the rest of the code
if it is missing. It returns the error message when no data is found.
The var model line takes the data coming in and turns it into the FriendModel. This is
convenient because we don’t have to worry about each piece of data. As long as our model
has the proper objects JSON converter will take the data coming in and match it up with
our model.
The var results line sends the data to the Web.Data project, where we have code to save it to
the database. We made this method a string, because we want the data code to return a
success or error message. If the data didn’t save correctly we want to know that so we can
show the user.
The last line of code returns a message if an error occurs.
Right click All.cshtml and view in browser. Once again, although we have C# code to
update data, it won’t work until we wire-up JS code. For now, we will add some test code
to update data.
Go to the Test controller and add this code:

public ActionResult UpdateTest()
{
try
{
var model = new FriendModel();
model.MyFavoriteFriendsID = 3; //Ken Sánchez
model.FirstName = “Ken”;
model.LastName = “Sánchez”;
model.Email = “Ken@email.com”;
model.MobilePhone = “111-222-3333”;
var dob = new DateTime(1990, 3, 29);
model.DateOfBirth = dob;


var result = Web.Data.UPDATE.UpdateEntityFriends.SingleEntity(model);


return View();
}
catch (System.Exception exception)
{
return Json(exception.ToString());
}
}


Build the solution.
Right click the UpdateTest action, add a view and save all files.
Right click the UpdateTest.cshtml and view in browser. When the page loads, it will run
the test update code, and display the update view:


Go to the database, notice that a record has been updated properly when using this query:

SELECT TOP 1000 [MyFavoriteFriendsID]
,[FirstName]
,[LastName]
,[Email]
,[MobilePhone]
,[Age]
,[DateOfBirth]
,[DateCreated]
FROM [MyFirstDatabase].[dbo].[MyFavoriteFriends]
WHERE MyFavoriteFriendsID = 3



In this step we wrote C# code to update data in our views. We added code to update the
data layer which sent data to the database using the update command. We added code to
the controller to call the data layer method and passed in the model to update with. We
added HTML code to create an interface for the user to enter data. After creating some test
code, we ran it, and were able to use SSMS to verify the update was successful.
It is important to remember that when using the UPDATE operation, make sure the
WHERE clause is used otherwise the entire database table will be changed. Notice that
our test update was this code: where entity.MyFavoriteFriendsID == model.MyFavoriteFriendsID
Later when we work with JavaScript, we will connect the save button so that it calls the
C# code, but for now let’s move on to the C# DELETE operation.


Step 6.3 C-Sharp Deleting Data

The C# DELETE operation is self-evident in that it will remove data from the database.
Instead of actually deleting records, it is a good idea to create a column of type bit and
name it something like, IsPermanentlyDeleted. Then using C# code, update that field to
true. What that means is that when we query the data we can put in our WHERE clause to
look for records that have not been “IsPermanentlyDeleted”. If we actually delete a record
using C# code, we will never know if it existed, unless we used the transaction log in SQL
server. This practice is good for historical or auditing purposes. Nonetheless, let’s go
ahead and see how we can use C# code to delete data.
Go to Web.Data, create a folder called “DELETE”, add a class file called
“DeleteEntityFriends.cs”. Delete all existing code and add this code:


using System;
using System.Linq;
using Web.Data.EF;


namespace Web.Data.DELETE
{
public class DeleteEntityFriends
{
public static string SingleEntity(int entityID)
{
try
{
using (var dataContext = new MyFirstDatabaseEntities())
{
var item = dataContext.MyFavoriteFriends.Single(t => t.MyFavoriteFriendsID == entityID);
dataContext.MyFavoriteFriends.Remove(item);
dataContext.SaveChanges();
return string.Empty;
}
}
catch (Exception exception)
{
return exception.ToString();
}
}
}
}



Build the solution.
That code will delete one record where the ID passed in by the model matches the ID of
the record in the database table.
Now go to Web.UI, add this code to the Main controller in the Friends area:


[HttpPost]
public ActionResult Delete(string JsonData)
{
if (string.IsNullOrEmpty(JsonData)) return Json(“Missing Required Data.”);
try
{
var model = Newtonsoft.Json.JsonConvert.DeserializeObject<FriendModel>(JsonData);
var data = Web.Data.DELETE.DeleteEntityFriends.SingleEntity(model.MyFavoriteFriendsID);
return PartialView(“~/Areas/Friends/Views/Partials/PartialData.cshtml”, data);
}
catch (Exception exception)
{
return Json(“Data error!”);
}
}



Build the project.
That code will take the string of JSON data coming in, check if the data is valid, convert it
to the Friends model and send it to the data layer. If there are no errors, it will reload the
data grid.
Similar to the create and update operations, we cannot use this code until we add
JavaScript, so for now let’s add test code to delete a record in the database.
Add this code to the Test controller:

public ActionResult DeleteTest()
{
try
{
var data = Web.Data.DELETE.DeleteEntityFriends.SingleEntity(1501);
return View();
}
catch (System.Exception exception)
{
return Json(exception.ToString());
}
}


Build the project.
That test code will delete the record where the ID equals 1501. (Use a different ID if you
want.)
Right click the DeleteTest method, add a view and save all changes.

Open SSMS, right click the database name and run a query for that ID:

SELECT TOP 1000 [MyFavoriteFriendsID]
,[FirstName]
,[LastName]
,[Email]
,[MobilePhone]
,[Age]
,[DateOfBirth]
,[DateCreated]
FROM [MyFirstDatabase].[dbo].[MyFavoriteFriends]
WHERE [MyFavoriteFriendsID] = 1501



If that ID does not exist, use a different one from your table and change your C# code to
reflect the new ID you want to delete.
Right click DeleteTest.cshtml and select view in browser.
The page will load, execute the delete code and display the page. Go back to SSMS and
execute the SELECT query, and you will see the record is no longer there.
In this step we added C# code to delete a record in the database. We started with adding
C# code to the data layer, and handled the code that is sent to SQL server to delete a
record. Then we added code to the controller to accept in coming data with the ID of the
record that is to be deleted. And we used test delete code to verify that it works.
Just as TSQL allows for CRUD operations, C# code can also be used to create, read,
update and delete data. The CREATE operation, allows us to add data by inserting one or
many records at a time. The READ operation allows us to pull data and display it to the
user. The UPDATE operation can be used to save changes to a record’s information. And
the DELETE operation will remove data from the database.
Remember that when using UPDATE and DELETE to include the WHERE clause,
otherwise the whole table will be affected. And remember that it is good practice to use a
bit field and set it to IsDeleted instead of actually removing the data.
Let’s move forward and use JavaScript to wire-up our CRUD operations so we can
manage the data.

Step 7.0 JavaScript Introduction

There are two main types of code, client side and server side. JavaScript is a client side
code and can be used to validate data, manipulate the browser, and many other things. You
can learn more about JavaScript here: http://www.w3schools.com/js/js_intro.asp
For example, when you create a new online account, some information is required, like an
email address. If you forget to enter the proper information and click the submit button, an
error message will tell you that you must enter in required fields. Most likely the code
used for that validation is JavaScript.
Please don’t confuse JavaScript with Java, which is another programming language and
you can learn more about it here:
https://en.wikipedia.org/wiki/Java_(programming_language)
And please don’t confuse JavaScript with jQuery. Simply put, jQuery is JavaScript code
but it has been organized into a library. If you think about a physical public library, it is
organized by sections. One section has magazines, while another has books, and so on.
Within each section, the items are organized in a certain way, for example, books may be
alphabetical. If you wanted to find a book whose title started with the letter “T”, you can
go straight to that book shelf. It’s the same concept with jQuery. When coding with
JavaScript, there are many things you may want to do, and jQuery has been organized into
a framework which allows you to easily use the proper code to do what you need to. You
can learn more about jQuery here: http://www.w3schools.com/jquery/jquery_intro.asp
and https://jquery.com
Take time to study the links I just provided because understanding JavaScript and jQuery
is a big learning curve. If you have never worked with either, please take the time to learn
them now before continuing.
Almost all up-to-date web browsers have a JavaScript engine. Simply put, when a browser
loads a web page, it uses different rendering engines to look at the code. A JavaScript
rendering engine is used to determine what actions it should take when the browser loads.
You can learn more about how a browser works from these links:
http://www.html5rocks.com/en/tutorials/internals/howbrowserswork/#Rendering_engines
and https://en.wikipedia.org/wiki/Web_browser_engine
To summarize, JavaScript is a client side programming language which is used by a web
browser to do client side actions and functions. jQuery is a JavaScript framework which
allows us to be more efficient when programming.
Let’s move on to the next step where we will put JavaScript in action.

Step 7.1 JS Setup

To work with JavaScript, we will need to setup our project with the proper JS files.
If you have any trouble with the code in this step, you can download the full code from my
website and use it as a reference as you go through this book: http://www.cjtran.com/uyj.
First we need to add the jQuery library to our project. As of this writing the latest jQuery
version is 2.1.4, and we can download the compressed version here:
https://jquery.com/download
Once downloaded, drag it into the Scripts folder of the Web.UI project. You can also add it
by right clicking the Scripts folder, select Add, then Existing Item. With the “add item”
window open, navigate to the file and add it. Just make sure it says “.min”. For example,
jquery-2.1.4.min.js.
Open the jQuery file, and you’ll see lots of JS code. It’s a good idea to not touch that code
unless you know what you are doing.
The second thing we need to do is download bootstrap.min.js and add it to the Scripts
folder in our project. Go here to download it:
https://github.com/twbs/bootstrap/releases/download/v3.3.6/bootstrap-3.3.6-dist.zip.
Once downloaded extract the files, find bootstrap.min.js, and add it to the Scripts folder.
The last thing we need to do is change BundleConfig.cs to reflect the JS files we will need
later. Notice that in BundleConfig.cs we use the code BundleTable.EnableOptimizations = true; to
compact our JS files. If we add more JS files later, we need to update that C# code as well.
For example, later in the book, we will need to add more JS files to create, update, read
and delete data. So let’s do that now.
Open BundleConfig.cs, delete all existing code and add this code:

using System.Web.Optimization;


namespace Web.UI
{
public class BundleConfig
{
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle(“~/bundles/jquery”).Include(
“~/Scripts/jquery-2.1.4.min.js”
, “~/Scripts/bootstrap.min.js”
, “~/Scripts/main.js”
, “~/Scripts/create.js”
, “~/Scripts/read.js”
, “~/Scripts/update.js”
, “~/Scripts/delete.js”


));


bundles.Add(new StyleBundle(“~/Content/css”).Include(
“~/Content/bootstrap.min.css”
, “~/Content/site.css”
));


BundleTable.EnableOptimizations = true;
}
}
}



Build your solution.
The reason JS works in our project is because it is referenced correctly. Notice the code in
_Layout.cshtml: @Scripts.Render(“~/bundles/jquery”)
That code is the connection to all our JS files. When our site loads, the bundling code in
BundleConfig.cs takes all the JS files and compacts them into one file, and puts the path to
that code in a virtual directory. Notice that our project does not actually have a folder
directory of “/bundles/jquery” but our JS files are located at “/Scripts/main.js”. This
prevents users from getting access to the actual location to our JS files.
Another way to protect our JS is to use obfuscation. Once we are ready to deploy our
website online, we can use tools to jumble our code so that others cannot get access to
sensitive data. We won’t be obfuscating JS code in this book, but you can use lots of
different online obfuscation tools, like this: https://javascriptobfuscator.com/Javascript-
Obfuscator.aspx
A good coding practice is to put JavaScript code after HTML and CSS code because it
will help load the page faster. Sometimes you will need to load JS first, but as a general
rule, place it last. Notice in the _Layout.cshtml, JS code is loaded at the bottom of the
page as seen by this code @Scripts.Render(“~/bundles/jquery”)
Here is a good article about it: http://stackoverflow.com/questions/9890349/does-it-help-
page-load-speed-to-place-script-after-body
Since JS is a “behavioral” type of code, that is, it works when something is done, like a
button click action, we will need to add JS code to the create, update, delete buttons, and
other actions to see how it works. Before we can dive in, we need to setup a few more
things.
In the Web.UI project, add a new JS file by right clicking the Scripts folder, and select
Add new item. Name the file “main.js”. Open main.js and add this code:

var CommonCSSLabelDanger = ‘label label-danger’;
var CommonCSSLabelSuccess = ‘label label-success’;
var CommonCSSAlertDanger = ‘alert alert-danger’;
var CommonCSSAlertSuccess = ‘alert alert-success’;
var CommonHasTag = “#”;


function CommonNavigate(Page) {
window.location = Page;
}


function CommonRefreshObject(object, controller) {
$(object).load(controller);
}


function CommonShowModal(modalID) {
$(modalID).modal({
backdrop: ‘static’, //prevents closing modal on mouse click.
keyboard: false //prevents closing modal when escape key is pressed
})
$(modalID).modal(‘show’);
}


function CommonHideModal(modalID) {
$(modalID).modal(‘hide’);
}


function CommonHideDiv(divID) {
$(divID).hide(500);
}

function CommonShowDiv(divID) {
$(divID).show(500);
}


function CommonToggleDiv(divID) {
$(divID).toggle(250);
}


Build the solution.
The code above has the word “common” before the methods, and is meant to be used
anywhere in the site. We could put this code in a new folder called “Common” and have
separate files specific to common functionality. For now, let’s just leave it as is.
That code also has basic common functions to hide and show modals and div tags. There
are also some basic CSS classes that will be used later.
Your Scripts folder should look like this:




Now that we have our JS code setup, let’s move on to the next step where we will finish
wiring up the Create operation so we can insert data.


Step 7.2 JS Read

In this step we will use JS code to display data and do a dynamic search.
Since we already have C# code in the controller that loads the proper view, let’s add JS
code to make everything work properly.
In the Web.UI project, add a new JS file to the Scripts folder, name it read.js and add this
code to the file:

var inputSearchFriends = CommonHasTag + “inputSearchFriends”;
var divSearchResults = CommonHasTag + “divSearchResults”;


$(document).ready(function (e) {
$(‘#CreatedivCRUD’).hide();
LoadData();
});


function SearchForFriends(searchItem) {
if (searchItem != ””) {
$(divSearchResults).show(500);
CommonRefreshObject(CommonHasTag + ‘divSearchResults’, ‘../Main/FetchSearchingForFriends?searchItem=’ +
searchItem);
}
}


function LoadData() {
$(CommonHasTag + ‘divLoading’).show();
CommonRefreshObject(CommonHasTag + ‘divPartialData’, ‘../Main/FetchAll’);
}


function ClearSearch() {
$(inputSearchFriends).val(”);
$(divSearchResults).hide(500);
}



Save all changes.
That code declares and initializes two variables for the controls we will be working with.
There is a document ready function which will run when the page has finished loading. In
this case we want to show the control that has all the grid data.
The SearchForFriends method is used in All.cshtml. When the keyup event is triggered, JS
code will fire to get data for that search.
The LoadData method, will fetch all the data and load it in the proper view.
The ClearSearch method will reset the view when searching is no longer needed.
Right click All.cshtml to view it in a browser. Notice there is data loaded in the grid and
you can enter a name to search for a friend.
If your page is not displaying data, check the Web.UI project in the web.config, in the
connection string section and make sure it’s pointing to your proper SQL server. And
check BundleConfig.cs, and make sure your JS files are referenced properly in
_Layout.cshtml.



Notice how the search panel works. As you enter a name, the list filters based on your
search criteria:

Notice the total records that is return in the grid and the search results. Can you figure out
how to limit the total of rows return? (Hint, it has to do with C# code in the Web.Data
project.)
In this step we used JS code to pull and display data. We also added JS code to do a
dynamic search as the user enters search items. In the next step we will use JS code to
create data.

Step 7.3 JS Create

In this step we will use a JS create operation to trigger C# code which will go to the
database to insert data.
In the Web.UI project, add a new JS file to the Scripts folder and name it “create.js”. Add
this code to the file:



var crud = “#Create”;
var CreateDivCRUD = crud + “divCRUD”;
var CreateSpanResultMessage = crud + “spanResultMessage”;
var CreateButtonCancel = crud + “buttonCancel”;
var CreateButtonSubmit = crud + “buttonSubmit”;
var CreateModel00 = crud + “FirstName”;
var CreateModel01 = crud + “LastName”;
var CreateModel02 = crud + “Email”;
var CreateModel03 = crud + “MobilePhone”;
var CreateModel04 = crud + “DateOfBirth”;


var divPartialData = CommonHasTag + “divPartialData”;
var buttonShowAddPanel = CommonHasTag + “buttonShowAddPanel”;


$(document).ready(function () {
$(CreateButtonCancel).click(function () {
CancelCreate();
});


$(CreateButtonSubmit).click(function () {
CreateData();
});
});
function CreateData() {
var model = {};
model.FirstName = $(CreateModel00).val();
model.LastName = $(CreateModel01).val();
model.Email = $(CreateModel02).val();
model.MobilePhone = $(CreateModel03).val();
model.DateOfBirth = $(CreateModel04).val();


if (model.Email == ”) {
alert(‘At least enter an email.’);
return;
}


$(CreateButtonSubmit).hide(1000);


var JsonDataStringified = JSON.stringify(model);


var status;
$.post(‘../Main/Create’, { JsonData: JsonDataStringified }, function (results) {
if (results == ”) {
$(CreateSpanResultMessage).text(‘Record added!’);
$(CreateSpanResultMessage).addClass(CommonCSSLabelSuccess);
status = “success”;
}
else {
$(CreateSpanResultMessage).show(500);
$(CreateSpanResultMessage).text(results);
$(CreateSpanResultMessage).addClass(CommonCSSLabelDanger);
}
});


if (status = “success”) {
setTimeout(function () {
$(CreateSpanResultMessage).hide(500);
CancelCreate();
CommonRefreshObject(divPartialData, ‘../Main/FetchAll’);
}, 1000);
}
}

function ShowAddPanel(divID) {
$(CreateButtonSubmit).show();
$(buttonShowAddPanel).hide();
$(CreateButtonCancel).show();
CommonShowDiv(CreateDivCRUD);
CommonHideDiv(divPartialData)
}


function CancelCreate() {
$(CreateModel00).val(”);
$(CreateModel01).val(”);
$(CreateModel02).val(”);
$(CreateModel03).val(”);
$(CreateModel04).val(”);


$(buttonShowAddPanel).show();
$(CreateButtonCancel).hide();
$(CreateSpanResultMessage).hide();


CommonShowDiv(divPartialData);
CommonHideDiv(CreateDivCRUD)
}



Save all changes.
Let’s examine that code.
Notice at the top, the JS code named var, which is the same C# var code in Razor syntax.
The only different is in JS code, the hash tag (#) is used: “#Create”. The hash tag is specific
to JS and is used to identify the ID of a control.

The JS code above also wires up the click event for the cancel and submit button when the
page is loaded as seen in the function: $(document).ready(function ().
The function CreateData() collects the values enter in each textbox and saves it to the model
object which is then converted into a JSON object and then is sent to the controller. That
code also does other tasks, like showing and hiding of controls to make the experience
more user friendly.
Right click All.cshtml to view it in a browser. Click the Add Friend button and notice
jQuery slides open the panel. Enter data in the fields and click Add Friend. Notice the new
record added to the grid.
In this step, we added JS code to create data.

Step 7.4 JS Update

In this step we will use JS code to update data.
Go to the Web.UI project and add a new JS file to the Scripts folder and name it update.js.
Add this code to the file:

var crud = “#Update”;
var UpdateDivCRUD = crud + “divCRUD”;
var UpdateSpanResultMessage = crud + “spanResultMessage”;
var UpdateButtonCancel = crud + “buttonCancel”;
var UpdateButtonSubmit = crud + “buttonSubmit”;
var UpdateModel00 = crud + “FirstName”;
var UpdateModel01 = crud + “LastName”;
var UpdateModel02 = crud + “Email”;
var UpdateModel03 = crud + “MobilePhone”;
var UpdateModel04 = crud + “DateOfBirth”;


var deleteEntityID; //deleteEntityID used for updating and deleting records in delete.js


$(document).ready(function () {
$(UpdateButtonCancel).click(function () {
CancelUpdate(UpdateDivCRUD);
});


$(UpdateButtonSubmit).click(function () {
SaveChanges();
});
});


function SaveChanges() {
//deleteEntityID used for updating and deleting records and was declared in update.js
if (deleteEntityID == ”) {
alert(‘Can't delete because of missing ID’);
return;
}

$(UpdateSpanResultMessage).show();
$(UpdateButtonSubmit).hide();


var jsonModel = {};
jsonModel.ActionResult = ‘../Main/Update’;
jsonModel.MyFavoriteFriendsID = deleteEntityID;
jsonModel.FirstName = $(UpdateModel00).val();
jsonModel.LastName = $(UpdateModel01).val();
jsonModel.Email = $(UpdateModel02).val();
jsonModel.MobilePhone = $(UpdateModel03).val();
jsonModel.DateOfBirth = $(UpdateModel04).val();


var jsonData = JSON.stringify(jsonModel);
$.post(jsonModel.ActionResult, { jsonData: jsonData }, function (results) {
if (results == ”) {
//saved!
$(UpdateSpanResultMessage).text(‘Saved!’);
$(UpdateSpanResultMessage).addClass(CommonCSSAlertSuccess);


setTimeout(function () {
CommonHideModal(UpdateDivCRUD);
CommonRefreshObject(divPartialData, ‘../Main/FetchAll’);
}, 1000);
}
else {
$(UpdateSpanResultMessage).text(results);
$(UpdateSpanResultMessage).addClass(CommonCSSAlertDanger);
return;
}
});
}


function ShowUpdateModal(entityID) {
$(UpdateSpanResultMessage).hide();
$(UpdateButtonSubmit).show();
$(divSearchResults).hide(500);

var model = {};
model.MyFavoriteFriendsID = entityID;
var JsonData = JSON.stringify(model);


$.post(“../Main/FetchSingleForUpdate”, { JsonData: JsonData }, function (results) {
if (results == ‘Error’) {
alert(‘Error, can't find data’);
}
else {
var data = JSON.parse(results)


$(UpdateModel00).val(data.FirstName);
$(UpdateModel01).val(data.LastName);
$(UpdateModel02).val(data.Email);
$(UpdateModel03).val(data.MobilePhone);
$(UpdateModel04).val(data.DateOfBirthAsStringForInput);
}
});


CommonShowModal(UpdateDivCRUD);


//deleteEntityID used for updating and deleting records and was declared in update.js
deleteEntityID = entityID;
}


function CancelUpdate() {
$(UpdateModel00).val(”);
$(UpdateModel01).val(”);
$(UpdateModel02).val(”);
$(UpdateModel03).val(”);
$(UpdateModel04).val(”);


CommonHideModal(UpdateDivCRUD);
}

Save all changes.
Let’s examine that code.
At the top, we declare and initialize all variables. The variable deleteEntityID is used to
preserve the value of the ID being updated. That ID is set when a row click event happens
on the grid.
The document ready function adds a click event to the buttons used for canceling and
saving our data.
The function, SaveChanges, sends the values entered from the page to the controller, then to
the data layer, and then finally to the database. In order to capture the values entered we
use the jQuery method, val().
The CancelUpdate method is connected to the cancel button and does just that.
Now that we have JS code to update with, build your solution, view the Friends area in
your browser and try saving some records.


Step 7.5 JS Delete

In this step we will follow the same pattern as the previous JS operations and use JS to
delete data.
Create a JS file in the Scripts folder in the Web.UI project and name it “delete.js”. Add
this code to the file:


function SetDeleteEntityID(entityID) {
//deleteEntityID used for updating and deleting records and was declared in update.js
deleteEntityID = entityID;
DeleteFriend();
}


function DeleteFriend() {


if (confirm(“Delete record…?”)) {
if (confirm(“Are you sure…?”)) {
} else {
return;
}
} else {
return;
}


if (deleteEntityID == ”) {
alert(‘Can't delete because of missing ID’);
return;
}


var status, message = CommonHasTag + ‘UpdatespanResultMessage’;


var model = {};
model.MyFavoriteFriendsID = deleteEntityID;
var JsonDataStringified = JSON.stringify(model);
$.post(‘../Main/Delete’, { JsonData: JsonDataStringified }, function (results) {
if (results == ”) {
$(message).text(‘Record deleted!’);
$(message).addClass(CommonCSSLabelSuccess);
status = “success”;
}
else {
$(message).show(500);
$(message).text(results);
$(message).addClass(CommonCSSLabelDanger);
}
});


if (status = “success”) {
setTimeout(function () {
$(message).hide(500);
$(CommonHasTag + ‘row’ + deleteEntityID).hide(500);
CommonHideModal(CommonHasTag + ‘UpdatedivCRUD’);
CommonRefreshObject(divPartialData, ‘../Main/FetchAll’);
}, 1000);
}
}




Let’s explain that code.
The SetDeleteEntityID function is used to first capture the ID of the item being deleted, and
then calls the DeleteFriend method. Look in the file PartialData.cshtml and you’ll see that the
delete ID, MyFavoriteFriendsID, is set to the onclick event for the delete button. A delete ID is
important, because without it, we could possibly delete all records in our database, which
is not ideal.
The DeleteFriend function has two alert messages asking users if they are certain they want to
delete the item. Then the function checks to make sure that there is an ID to delete with. If
there is no ID, the code will not continue. The last part of the delete function set’s the
delete ID to the JSON object and passes it to the controller. The corresponding message
will appear depending on whether the delete was successful or not.
Now that we have JS code to delete with, let’s see it in action.
Go to the Friends area, and in the Main folder, right click All.cshtml and view in browser.
Click the red X in the grid to delete a record.


Do a search for a friend and click on a row in the results grid:


The update modal will appear. Click on the red delete button to delete that record:


With that JavaScript code we can easily delete records from the database.


Step 7.6 JS Conclusion

JavaScript is a powerful client side language and can be used for more than just CRUD
operations. Using JS code, there are many other features we can add to our project to
make it better. For example, we can add JS code to validate data. Notice that when adding
and updating a record, we can enter a 6-digit year when 4 digits is sufficient. We can also
add validation for the email address to make sure that it is in the proper format. Beyond
the basic ways we have used JS in this book, it can be used for more advanced needs, like
building single page applications (SPA), connecting to web services, and much more. Play
around with JS and see if you can add more functionality to your site.
Now that we have JS code for CRUD operations, and have learn simple usage for JS, let’s
move on and talk about CSS.


Step 8.0 CSS Basics

By now we know that different programming languages are used for different purposes
and Cascading Style Sheet, CSS, is used to make a website look pretty. In this step we will
do less coding and focus more on understanding how it works. The term cascading already
implies that there will be many layers of styles. With CSS the there is a hierarchy to how
the code works. Let’s look at our project and try to understand this.
The first thing to consider with CSS is how it is referenced and in our project is used in the
Web.UI project in _Layout.cshtml with the code: @Styles.Render(“~/Content/css”)
When the page loads, it will go to that location, and connect all the CSS classes to
corresponding code on the HTML page. However, before that line of code “fires”, notice
the code in the file BundleConfig.cs compacts all the CSS files and puts it in the virtual
directory named Content/css.
When we go to the Friends area, and the view for All.cshtml, the first CSS class is called
“container”: <div class=“container”>
If we open bootstrap.min.css and search for the container class we will see what it does.
In this example I have changed the values of the container and you can see the affect it has
on our view:

.container{padding-right:615px;padding-left:85px;margin-right:auto;margin-left:auto}





Notice anyplace in HTML that uses the CSS class keyword, should refer back to a CSS file
or code. Every object in our website can be define using CSS. We can define absolute or
relative positioning to almost every item on our page. Using CSS, we have total control of
how our pages will look. It is important to keep in mind that CSS should be built to
respond to different platforms, like mobile devices.
Feel free to play around with CSS and see what kind of a website you can build from
scratch.
It is beyond the scope of this book to fully explain how CSS works and there are many
online resources to help you become more experienced with it. Take the time to study
them.
See Appendix E Resources for more resources on CSS.
And remember you can always use other CSS frameworks besides bootstrap, like
Foundation: http://foundation.zurb.com/sites/download.html/.
Or check out 10 Best Free CSS3 Frameworks of Year 2015:
http://www.cssnewbie.com/best-free-css3-frameworks-2015/#.VnWdXBUrIYs

Step 9.0 Final Thoughts

So there you have it! At this point, we have learned much about web development. We
used Visual Studio to build a MVC website and created a user interface to allow users to
create, update, delete and view data. Using SQL Server Management Studio, we managed
our data by creating a database and executed TSQL scripts to manipulate data. With C#
code we pulled data from the database and passed it to the views by filling objects in our
models project. We then wired up client side code using JavaScript, which fired based on
actions taken, like a button click event. And we finally wrapped up by understanding how
CSS classes worked and used it to make our website look better.
If you are brand new to web development and just completed this book, I want to
congratulate you on a job well done! What you just accomplished was truly amazing
because you are entering a new frontier where humans and machines interact. The need
for programmers in the future will be so great that we won’t have enough people to build
and manage all of our digital needs. I have worked for many companies, and have seen
how it takes an army of developers to build one product. Just know that if you stay on this
journey, it will be fun, and you will be contributing to a huge network of I.T. specialists
contributing to making our lives more efficient and connected.
What we have covered in this book can be considered very basic. There are lots of other
techniques and lots of other ways to code to get information and to program. And as a
developer you will always be learning and growing and doing things better and more
efficient. Just know that the topics and techniques discussed in this books are the basics
and can be considered as elementary techniques for programming and web development.
There is so much more to web development, and in this book we have gone through a lot
but I would still consider everything we learned as basic programming. The numerous
possibilities of what we can build using visual studio is astounding, not to mention the
plethora of technologies that go into a finished product. I think that’s why web
development is so exciting, and after 10 years, I am still learning and intrigued with the
latest tools and gadgets. Hopefully this book has given you a good understanding and a
foundation to build on.
I would recommend you keep learning and get to the point where you can build cutting
edge applications and be marketable. Please feel free to check out Appendix D Getting a
Job.
Please feel free to leave me a message on my website and let me know how this book has
affected you. And if you found any spelling errors in this book, I truly apologize and
would appreciate you letting me know by leaving a comment on my website:
http://www.cjtran.com

Thank you for taking the time to join me on this journey and I wish you the best in your
future web development endeavors!


Appendix A - Programming Languages

In order to build a website, you will need to decide what programming languages to use.
Yes, that’s right languages, as in many. Since you are new to all of this, I’m going to pick
the languages for you because they are the core languages for web development today. If
you decide later you want to change to a different programming language, the following
languages will still be useful in your future job. The languages we will be working with
are HTML, JavaScript, CSS, C# and T-SQL. We will discuss them in detail later but for
now, don’t worry, and just trust me when I say, you can’t go wrong with those
programming languages.

Let’s talk about what a programming language is and why we need it.

When you want to communicate something to someone, you will most likely verbally
speak to that person. You can also record a video, write a letter, send a text, post it, hash
tag it, tweet it, like it, poke it, wink it, and so on. The most important thing to consider is
what language will you use to communicate to that person. Maybe that person only
understands Hindi or Mandarin, and you only know English. So in order to communicate
to the person, you can use Google Translate, type in the English message and Google will
translate that into Hindi or Mandarin for you. Then you can take that translated message
and communicate to that person. That is kind of how we speak to computers, except
computers speak in ones and zeros. Simply put, a programming language is used to speak
to a computer.

It is outside the scope of this book to explain in detail how programming languages turn
into something that a computer converts into a website. For now, just understand that
when we use Visual Studio to create a web page, there are many other technologies behind
the scenes that transform your code into a great looking and functioning website.

There are lots and I mean lots of programming languages out there, just as there are many
different “people” languages in the world. Each programming language tells a computer to
do different things depending on what you want it to do and each language has its own
advantages and disadvantages. For example, if you want to make a website look pretty,
you can use Cascading Style Sheet, also known as CSS. If you want to work with a
database, like Microsoft SQL Server (Sequel Server), you can use T-SQL, also known as
Transact Structured Query Language, and if you want to work with an object oriented
programming language (OOP), you can use C# (pronounced just like the musical note,
“see sharp”). Don’t worry about all those terms and languages for now. As we go along,
you will get more familiar with them. For now, just know that in order to communicate
with a computer and build your website, you will have to use many different programming
languages.

And remember, you can use different tools to build different applications. You can also
use different operating systems like Mac OS or Linux, and program with other languages,
like PHP or Python. For now, I want to show you how to do things in a Microsoft
Windows environment with Visual Studio 2015, and as you grow your wings, you can
pick your own style. You have to start somewhere and I believe this book is a great place.

To summarize, in order to build a website, you will need a development tool, like Visual
Studio, and pick the appropriate programming languages.

Appendix B - Creating Your Own Domain

You can purchase a domain name from many web hosting providers, and in our case we
will use Google Domains. To purchase a domain, go to:
https://domains.google.com/registrar and sign in with a Google account. If you don’t have
one, please feel free to create one.
Once logged in, click on “My domains”:


Click the Search link and type in the domain you want and click the Search domains
button.



If someone else already has that domain, you’ll need to pick a different one. In this case,
I’ve already purchased www.cjtran.com and there is a frown next to that domain:



Once you have picked a domain, click on the shopping cart icon to the right. Then click
process to checkout:



Enter the required information on the screen:




On the next screen, click Start now:




You’ll receive confirmation and can click Done:



You can close this screen if it appears:





Now that we have a domain name let’s point it to our hosting URL, which is the URL
from our Azure account. If you don’t have an Azure account, complete the step for
Publishing Your Website Online.
Remember your URL and domain names will be specific to your account.

In Google Domains, click on the Configure DSN icon:



Make your sections look like this, except for where your account differs from mine as seen
in red.
1. Scroll to the “Synthetic records” section.
2. Click the dropdown “Dynamic DNS” and select “Subdomain forward”.
3. Enter @ in the first blank box and enter www.PersonalYourDomainName.com in
the destination box. (NOTICE, replace “PersonalYourDomainName” with your
actual domain name.)
4. Click Add to add the record.



Your Synthetic records section should now look like this:



Now go the Custom resource records section and add three records. All three steps are the
same except for the values you will enter. Your Custom resource records section should
look similar to this:



Remember the information in the DATA column above is from your Azure account and
can be found by going to your Azure site, https://portal.azure.com. Click on Web Apps in
the left menu, then select your web app in the middle and then click on the More
Commands icon to the right.



Click on Buy Domain and then click on Bring External Domains.


NOTICE: Make sure your Azure domain is pointing to your new domain.
https://azure.microsoft.com/en-us/documentation/articles/web-sites-custom-domain-name/

The items in red below is what you will need to enter in to Google Domains.




If you are having trouble setting this up, go to the bottom of Google Domains page to
contact Google for support. Let them know you have a hosting URL and want to point
your personal domain to it.




Once you have configured your DNS in Google Domains it may take up to 48 hours for it
to propagate through the internet.


Appendix C - Installing the dot NET Framework

You can learn more about the .NET Framework by using these links:
https://en.wikipedia.org/wiki/.NET_Framework and https://msdn.microsoft.com/en-
us/vstudio/aa496123.aspx
In order to install the .NET Framework 3.5 Service Pack 1, you can search online for
“Microsoft .NET Framework 3.5 Service Pack 1” or use this link:
http://www.microsoft.com/en-us/download/details.aspx?id=22


Click the Download button:


Once downloaded, click on the file to open and install it. If you see this window, click the
first option to Download and install this feature:


If will download the required files in order to install the .NET Framework:


Once installed, click Close and restart your computer.



Appendix D - Getting a Job

This appendix is focused on those living in the U.S.A., so I apologize to all others, but you
still should have the same principles used in your area.
If you don’t have a degree in Information Technology or many years of experience in web
development, it will be difficult to get a good paying job as a web developer. Most
companies want to see a good looking resume and that you have experience working with
the technologies they are using. If you are new to web development or are trying to enter
the I.T. world, you can still get out there and find an entry level paying job.
The three quickest ways to get started is to create an I.T. resume, post your services on
www.craigslist.com, and get Microsoft certified.
The first way to get started is to create a resume listing the current technologies and
keywords to attract employers. One way to know what to put on your resume is to look at
what the market is asking for. If you do a search on Monster.com, CareerBuilder.com,
Indeed.com, or the many other job sites out there, you will find that the job description
tells you what employers are looking for. If you don’t understand what is on the job
description, do research, learn it, and then you can put it on your resume. Checkout Step
10.5 Appendix F Sample Resume, for an example of what your I.T. resume should look
like.
I just did a search online today for C# web developer and here is an example from one
company:
Jr./Mid Level .Net Software Engineer (web based applications, ASP.Net/MVC,
ADO.Net…)
About the Job: Our established national/international property oriented Software
Company Client is looking for a junior to mid level software engineer. This is a high
growth, high responsibility, opportunity in a stable established firm. (web based
Position offers excellent salary and benefits. May consider entry level, University
Grad, candidates with prior C#/.Net development experience. However, unable to
pay relocation or offer visa sponsorship at this time…
Responsibilities: Perform as a self-motivated software engineer, implementing
significant portions of system design. Design, develop and implement applications
in accordance with functional requirements, defined procedures, and industry best
practices. Create eminently testable units of code. Create and execute unit tests and
contribute to integration test planning.
Requirements: Bachelor’s degree in Computer Science, Engineering, or the related.
Master’s degree preferred. Candidates must have at least 4 years’ experience
developing .NET web-based applications. Hands-on experience with Microsoft
ADO.NET Entity Framework 4/5/6 and Microsoft ASP.NET MVC 4/5. Significant
experiencing programming with C#, LINQ, JavaScript, jQuery, HTML5 and CSS3.
Java experience is a plus. Experience developing browser/mobile hybrid
applications a plus. Experience in REST/JSON web services development.
Knowledge of relational database design concepts. Familiarity with MS SQL Server
and Oracle. Familiarity with using TFS for requirements management, source code
control, development, project tracking, testing, release management, and bug
tracking. Experience with Agile development a plus. Given the nature of the
position you must exhibit: Strong software development skills and familiarity with
current industry best practices. Flexible working as a contributing member of the
team and able to perform development tasks with minimal assistance.

Although that job is asking for 4 years of experience, in my experience, that is not usually
the case. Companies just want to know that you are competent and can work with the
technologies they are using. Never look at a job description and pick out the things you
can’t do or don’t know. Focus on what you do know and how you can improve your skills
or knowledge to match what the job requires. Considered the things companies are asking
you to do. Is the job description something you can see yourself doing on a daily basis?
The key is to get that phone interview or a face-to-face interview. The more interviews
you go through, the more experience you will have and will understand what companies
are looking for. And don’t be so hard on yourself if things are not working out too well for
you. Remember you are new to all of this, and it will take time to get up to that high
paying salary. For now, concentrate on getting experience with the interview and job
seeking process.
You can also contact I.T. recruiters and send them your resume, like www.teksystems.com
and www.roberthalf.com. There are many I.T. recruiters and finding them will vary
depending on where you live. Do an online search to find the closest recruiter in your
location. Call as many as you can and put your name and resume out there. The more you
can market yourself the higher the chance you will get an opportunity. The ultimate goal is
to get a job, but you can get much experience during the interview process as you apply
and accept every opportunity.
The second way to help you get an I.T. job is to post your service on www.craigslist.com
or some classified advertisements website in your area, and let people know you can build
them websites. Small companies, startup companies, and many other companies are
always looking for help with their website and they usually don’t want to spend a lot of
money hiring a very experience developer. If you can do the job at half the price and can
prove that to them, you will most likely get the job. Post your service daily, and as often as
possible. Create multiple accounts for yourself and post as many as you can stand. The
more you can put your service and name out there the more likely someone will contact
you. Post your service in all locations, and not just your home location. Since web
development can be done anywhere in the world, it just may be the case that someone
living in another state can use your service. Just remember to work out payment schedule
so you don’t get scammed and get your money’s worth.
Here is an example of a posting you can use:

If you are starting a small business and are looking for a C# .NET web developer to
build you a custom website for your business, please consider my services. I have X
years of experience in web development and have built websites that are mobile
friendly and cutting edge. Please feel free to contact me for more details and we can
discuss how I can help your business grow.
I have worked for this university, or that small company.
● Proficient in C# .NET on framework 2.0-4.5
● JavaScript (jQuery), HTML5, CSS
● Team Foundation Server, Visual Studio Online. Github/Git Bash
● ASP.NET MVC, WPF, Web Services
● LINQ to Entity Framework (code/model/DB first, edmx, POCO), LINQ to
SQL, LINQ to Oracle
● T-SQL, triggers, stored procedures, views on Microsoft SQL Server
● Visual Studio 2005-2015, Microsoft SQL Server 2000-2014
● Knowledge of third party products such as Bootstrap framework
● Trained in Scrum/Agile methodologies

Thank you.
Your Name


The third way to help get a job in I.T. is to get Microsoft certified:
https://www.microsoft.com/en-us/learning/certification-overview.aspx. Having a
Microsoft certification can go far for you, especially when starting out. There is not much
more I can say about this except if you want to do it, pick a path, like MTA, get the book,
study it, and take the exam.
Keep in mind that I.T. is performed for all sorts of industries, like for education, medical,
government, insurance, and so on. Think about what industry you would like to go
towards. Also keep in mind the working pace of companies. Usually education industries
are more relax and slower paced, while other industries will be more high paced and
demanding. Think about the kind of job that will meet your life needs. Maybe you are
young and single and don’t mind working 80 hours a week to make lots of money. Or
maybe you are older and need a job that respects a work-life balance. And it may just be
the case that you are keeping your current full-time job and are doing web development on
the side, which is a good way to get experience until you are ready to make the leap to
doing it full-time. Whatever your situation, consider where you want to be in 5 or 10
years, and work towards it.
The last thing to remember is never be afraid. Yes, it may be true that you are new to web
development today, and you don’t know it all. I have been doing this for over 10 years,
and I don’t know it all. Nobody knows it all. We are always growing and learning. You
know this much today, and a year from now you will know more, and in 10 years you will
know much more. The point is don’t be afraid of what you don’t know, but be confident
about what you do know. Focus on what you do know and don’t be afraid to try.

Appendix E Resources

Web development
https://mva.microsoft.com/
https://www.youtube.com/user/kudvenkat/playlists


Visual Studio
https://code.visualstudio.com/docs
https://www.visualstudio.com/get-started/overview-of-get-started-tasks-vs
https://msdn.microsoft.com/en-us/library/dn762121.aspx
https://msdn.microsoft.com/en-us/vstudio/aa718325.aspx
https://msdn.microsoft.com/library/dd831853.aspx


MVC
https://mva.microsoft.com/en-US/training-courses/introduction-to-asp-net-mvc-8322?
l=nKZwZ8Zy_3504984382
http://www.asp.net/mvc
https://msdn.microsoft.com/en-us/library/dd381412(v=vs.108).aspx
http://www.codeproject.com/Articles/728216/ASP-NET-MVC-New-Features
https://visualstudiomagazine.com/articles/2014/10/28/asp-net-mvc-5-1-new.aspx


SQL Server
https://mva.microsoft.com/product-training/sql-server
https://msdn.microsoft.com/en-us/library/ms167593(v=sql.105).aspx
http://www.techonthenet.com/sql_server/
http://www.quackit.com/sql_server/sql_server_2014/tutorial/create_a_database.cfm
https://www.mssqltips.com/sqlservertutorial/3200/sql-server-query-performance-
guidelines-tutorial/
https://www.youtube.com/playlist?list=PL08903FB7ACA1C2FB
http://www.dotnet-tricks.com/Tutorial/sqlserverlist
http://www.vertabelo.com/blog/notes-from-the-lab/18-best-online-resources-for-learning-
sql-and-database
http://www.tutorialspoint.com/sql/


T-SQL
http://www.tsql.info/
https://msdn.microsoft.com/en-us/library/bb545450.aspx
https://msdn.microsoft.com/en-us/library/ms365303.aspx
https://technet.microsoft.com/en-us/library/dn237258
This is the best one for advance TSQL: http://blog.sqlauthority.com/


C#
https://www.youtube.com/playlist?list=PLAC325451207E3105
https://mva.microsoft.com/en-US/training-courses/c-fundamentals-for-absolute-beginners-
8295?l=bifAqFYy_204984382


CSS
http://www.w3schools.com/css/css_intro.asp
http://www.csstutorial.net/css-intro/introductioncss-part1.php
http://tutorialzine.com/2014/07/20-impressive-css3-techniques-libraries-and-examples/
http://www.skilledup.com/articles/best-free-css-tutorials
http://learn.shayhowe.com/


JavaScript
https://visualstudiomagazine.com/pages/topic-pages/html5-javascript-tutorials.aspx
https://msdn.microsoft.com/en-us/library/hh334522.aspx
https://www.codementor.io/javascript/tutorial/how-to-learn-javascript-properly
http://www.techaltair.com/7-best-javascript-frameworks-of-2015/
https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-
introduction_to_JavaScript
http://www.codeconquest.com/blog/top-50-websites-to-learn-javascript/
http://tutorialzine.com/2015/05/15-awesome-and-free-javascript-books/


Appendix F Sample Resume

Here is a sample resume you can use for a future web development job.

Your Name
City, State | Email


Microsoft Certifications

● MCSD: Web Applications Solutions Developer
● Microsoft Technology Associate (MTA)

Functional Skills

● Proficient in C# .NET on framework 2.0-4.5
● JavaScript (jQuery), HTML5, CSS
● Team Foundation Server, Visual Studio Online. Github/Git Bash
● ASP.NET MVC, WPF, Web Services
● LINQ to Entity Framework (code/model/DB first, edmx, POCO), LINQ
to SQL, LINQ to Oracle
● T-SQL, triggers, stored procedures, views on Microsoft SQL Server
● Visual Studio 2005-2015, Microsoft SQL Server 2000-2014
● Knowledge of third party products such as Bootstrap framework
● Trained in Scrum/Agile methodologies




Technical Experience

● Microsoft Windows Development - 1 years
● Microsoft SQL Server Database Development - 2 years
● Microsoft C# .NET Web Development - 3 years




Work Experience

Company Name, City, State – Your Job Title (Intern Web Developer) –
Month/Year – present
● As an intern, I did this and that…
· Worked with this technology and that technology
· Worked with these people, or that group, like managers, business analysts…
· Developed these things…
· Participated with the team to do this…



Another Company Name, Location – Your Job Title - from date – to date
● Assisted in the design and maintenance of…
● Created this or that…


Education

Some Community College, location – year attended
● Courses taken: Web Development, Programming C#, Database System

Some Learning Center, location – year attended
● Courses taken: Querying Microsoft SQL Server with Transact-SQL

You might also like