• No results found

BASIC WEB DEVELOPMENT WEB DEVELOPER CAREER STARTS HERE. Jacob J. Heck HTML CSS IIS C# ASP.NET MVC MSSQL

N/A
N/A
Protected

Academic year: 2022

Share "BASIC WEB DEVELOPMENT WEB DEVELOPER CAREER STARTS HERE. Jacob J. Heck HTML CSS IIS C# ASP.NET MVC MSSQL"

Copied!
91
0
0

Loading.... (view fulltext now)

Full text

(1)

BASIC WEB DEVELOPMENT

HTML – CSS – IIS – C# – ASP.NET MVC – MSSQL

Discover how the internet works and start creating your own custom web applications with Microsoft’s Visual Studio, Internet Information Server, and SQL Server.

Jacob J. Heck

Senior Software Engineer and Technical Architect

(2)

About the Author ... 1

Prerequisites ... 2

How the Internet Works ... 2

The Client ... 2

Your Web Browser ... 2

The Server ... 4

IIS ... 4

Internal IP Address... 11

Static Internal IP Address ... 12

Public IP Address ... 14

The ISP ... 15

Public IP Address Assignment ... 15

Static IP Addresses Assignment ... 15

DNS Servers... 15

Domain Name Registrars ... 15

ICANN... 15

Getting the Tools ... 16

Your IDE - Microsoft Visual Studio Community 2015 ... 16

Creating A New Web Project ... 19

Debugging ... 22

Application Level Events ... 23

MVC Routing ... 25

Creating a Home Page ... 27

Creating Multiple ActionResults ... 34

Shared Layouts ... 38

NuGet Packages ... 46

bootstrap ... 53

jQuery ... 54

Adding references to Javascript and CSS files ... 54

MVC Razor Syntax ... 65

(3)

GET vs POST ... 79

Model Validation ... 81

Databases ... 89

What is a Database ... 89

Creating a Database ... 89

Deploying a Database ... 89

Accessing a Database ... 89

ADO.NET Entity Framework ... 89

What is ADO.NET ... 89

Creating Data Model ... 89

Saving Data ... 89

Reading Data ... 89

ABOUT THE AUTHOR

I am Jacob Heck, a dynamic and motivated Senior Software Engineer with a proven track record of success in designing, implementing, integrating, testing and supporting impactful applications developed for desktop, mobile, web, and tablet devices on multiple platforms.

I’ve been programming since the age of twelve and my first job was working as a Tutor for the Advanced Programming course at College of the Sequoias. I’ve worked at several companies after; moving to NYC to be an Application Developer where I rapidly expanded my knowledge on web applications and scalable tech environments. While in NYC I attended several Microsoft Developer Camps for Azure virtual

machines and web apps.

I currently work as a Senior Programmer Analyst where I create a variety of windows services, desktop applications, web APIs, and mobile handheld applications.

I look forward to walking through these lessons with you and I hope to make this learning experience as painless as possible. I also hope to instill this valuable information in your mind to help you start or further you career in web development. If you have any questions please contact me.

Jacob J. Heck

[email protected]

http://linkedin.com/in/jacob.heck

(4)

PREREQUISITES

1. A PC with Windows 7 or higher (all screen captures provided are taken in Windows 10) 2. Access to the Internet

HOW THE INTERNET WORKS THE CLIENT

YOUR WEB BROWSER

Whenever you go to http://facebook.com your PC is the client and Facebook.com is the server. Your PC tries to communicate over an internet protocol – HTTP. HTTP stands for Hyper Text Transfer Protocol.

The request on your PC is sent over your web browser to Facebook.com and it looks like this:

GET http://facebook.com/ HTTP/1.1 Host: facebook.com

In which Facebook responds with a “response header” and “response body”

The response header looks like this:

HTTP/1.1 200

Where the http status code 200 = “OK” If we were to go to a webpage that didn’t exist the status code would be 404 (“Not Found”).

The response body is HTML (Hyper Text Markup Language), you can view it by right clicking on the web page and selected “View Source”

(5)

The HTML will look like the following:

(6)

THE SERVER

IIS

You don’t need a fancy server to run a website off your machine. All windows machines can have websites running on them, they just need IIS installed. IIS stands for Internet Information Services. IIS can be installed by going to “add or remove programs” then clicking “turn windows features on or off”

(7)

And then by selecting “Internet Information Services” in the features list and clicking OK

(8)

To see your default website that’s now running on your, find IIS manager and open it

(9)

You can now see your default website in IIS installed on your machine by expanding “Sites” under your computer. To browse the default website, click browse.

(10)

This is what the default IIS website looks like

You can see the web address is http://localhost

(11)

The html file the webpage is displaying is automatically created by IIS. You can view/edit this html file here:

Your IIS default website doesn’t have to look in this folder for your html files for your default website, but this is where it is by default.

(12)

You can change the path it uses by clicking “Basic Settings”

And then changing the Physical path, we won’t change anything and just leave it how it is.

(13)

INTERNAL IP ADDRESS

At your home you probably have several PCs connected to your router. Each machine that is connected to your router is assigned a unique internal (your router only) IP (internet protocol) address. You can see this internal IP address by opening command prompt and typing in “ipconfig” then pressing enter.

Your IP address will be the IPv4 Address. IPv4 is the fourth version in the development of the internet protocol (IP). When you disconnect and reconnect to your home network, this IP address may change because it is dynamically assigned to your computer by your router.

Your router is a DHCP server, DHCP stands for Dynamic Host Configuration Protocol. DHCP is a protocol that enables a server to automatically assign an IP address to a computer from a defined range of numbers configured for a given network.

Applications use ports to allow remote PCs to communicate with your PC. For example, IIS does all of its communication through port 80 (IIS can be setup to use other ports but we’ll talk about that later). So, if we were on the same network and you typed in my internal IP address and IIS port into your browser (e.g. http://192.168.1.114:80), you would be able to see my default website.

All browsers use port 80 by default, so we can remove the trailing “:80” and the address could just be http://192.168.1.114

(14)

STATIC INTERNAL IP ADDRESS

What if my computer disconnected from my router and my router assigned me a different internal IP?

Web browsing connectivity to this internal IP address would no longer work. Therefore, I would need a static internal IP that does not change. Internal static IPs can be configured on your routers admin page.

Every router is different but they all have the ability to save internal static IP addresses. To modify my routers static IPs, I need to go to my routers admin page. The routers admin page is usually the Default Gateway IP address located under my IPv4 address in command prompt after running ipconfig.

(15)

Now I just navigate to my default gateway http://192.168.1.1 and find the reserved IP addresses option

(16)

How does my router remember to assign my internal static IP addresses to my PC everytime it gets disconnected and then reconnected? By my PC’s MAC address. Every PC has a different MAC address embedded into its network hardware. MAC stands for Media Access Control.

PUBLIC IP ADDRESS

Your public IP address is different from your internal IP address. If you go to www.whatismyip.com you can see your public IP address. Every device on your network will have a different internal IP address.

But, every device on your network will have the same public IP address. This is because your Public IP address is assigned to your router by your internet service provider (e.g. Comcast).

Now, what if you were trying to connect to my PC’s default website on your home network, not mine, so internal IPs wouldn’t work? Then, you would have to connect to my public IP address. But, how would my public IP address know to route to my PC’s internal IP address and not someone else’s on my network? We would have to set up port forwarding on my router.

I just navigate to my default gateway http://192.168.1.1 and find the port forwarding option. Once I find it I can set up my router to route to my internal IP address 192.168.1.144 for port 80.

(17)

Now if you were to try to view my website from my public IP address, you would be routed to my PC successfully.

THE ISP

PUBLIC IP ADDRESS ASSIGNMENT

Your ISP (internet service provider) assigns every one of their customer’s routers a public IP address. If you were to disconnect your router and turn it off for a while, then reconnect, you would be assigned a new public IP address.

Every ISP has a range of IP addresses they assign to their customer’s routers. The same IP address cannot be assigned to two different routers at the same time. The IP addresses available for your ISP to assign is regulated by the company ICANN, that way two ISPs cannot assign the same public IP address.

STATIC IP ADDRESSES ASSIGNMENT

If my router disconnected and my ISP assigned me a different public IP, connection to my PC with my old public IP address would no longer work. Therefore, I would need a public static IP that does not change.

Static IP’s can be purchased from ISPs for a monthly fee.

How does my ISP remember to assign my static IP addresses to my router in case it gets disconnected and then reconnected? By the routers MAC address. Every router has a different MAC address embedded into its hardware.

DNS SERVERS

Your internet service provider helps you get to the websites you want with their DNS servers. DNS stands for Domain Name System. DNS servers have long lists of domain names (e.g. google.com) that have a public IP address behind them (e.g. 74.125.224.72 – try it out, http://74.125.224.72). So instead of you having to remember IP addresses, you can just remember google.com. DNS Servers are updated constantly to have consistent data with Domain Name Registrars and ICANN.

DOMAIN NAME REGISTRARS

Domain names are unique identification strings that represent an IP address. Domains can be purchased from Domain Name Registrars (e.g. Godaddy.com). Purchasing domains is like a lease, you have to pay

$10 a year to keep the domain. Domain Name Registrars are regulated by ICANN, that way two exact domain names cannot be sold to two different customers.

ICANN

ICANN stands for Internet Corporation for Assigned Names and Numbers. ICANN is a nonprofit organization that is responsible for coordinating the maintenance and methodologies of several

databases, with unique identifiers, related to the namespaces of the Internet - and thereby, ensuring the

(18)

GETTING THE TOOLS

YOUR IDE - MICROSOFT VISUAL STUDIO COMMUNITY 2015

IDE stands for integrated development environment, which is a software application that provides comprehensive facilities to computer programmers for software/website development. An IDE normally consists of a source code editor (where you write your code), build automation tools (where you compile your code and push updates to your website) and a debugger (where you can see your code run line by line). Most modern IDEs have intelligent code completion (programmers auto-complete that will help you make less typos and write code faster).

Now, let’s get started, download the Visual Studio Community installer from Microsoft’s website.

https://www.visualstudio.com/en-us/downloads/download-visual-studio-vs.aspx

(19)

When installing, select “custom” install.

(20)

Expand “Windows and Web Development”.

Select “Microsoft SQL Server Data Tools”.

Click “Next” and then click “Install” – this may take a while.

Once the install is complete, click “Launch” – this may take a while.

(21)

CREATING A NEW WEB PROJECT Go to the top, click file -> new -> project

(22)

Select under templates -> Visual C# -> Web Type in “CampusNews” as the project name Uncheck “Add to source control”

Check “Create a directory for solution”

Change location of where it’s saved to your desktop Click “Ok”

(23)

Select “Empty” under templates Check “MVC” under core references

MVC stands for Model View Controller and it is the design pattern we will be using for programming the website.

Click “Ok”

(24)

DEBUGGING

Once the project is created, click the debug icon at the top of Visual Studio (the browser may be different on your machine, it’s just the browser used to see the website being debugged)

You’ll see the following error message in your browser

This is because we don’t have any pages created yet.

Go back to visual studio and click the “stop debugging” button at the top

(25)

APPLICATION LEVEL EVENTS Double click the file “Global.asax”

You’ll see the file open up in Visual Studio

The Global.asax file, also known as the ASP.NET application file, is an optional file that contains code for responding to application-level events raised by ASP.NET or by HttpModules. The Global.asax file resides in the root directory of an ASP.NET-based application.

The Global.asax allows you to write code that runs in response to "system level" events, such as the application starting, a session ending, an application error occurring, without having to try and implement that code into each and every page of your site.

You can create it by choosing Add > New Item > Global Application Class in Visual Studio (We don’t have to since it’s already created). Once you've added the file, you can add code under any of the events that are listed:

 Application_Start

 Application_End

 Session_Start

 Session_End

 Application_BeginRequest

 Application_AuthenticateRequest

 Application_Error

When you save changes to an active Global.asax file, the ASP.NET page framework detects that the file has been changed. It completes all current requests for the application, sends the Application_End event to any listeners, and restarts the application domain. In effect, this reboots the application, closing all browser sessions and flushing all state information. When the next incoming request from a browser arrives, the ASP.NET page framework reparses and recompiles the Global.asax file and raises the Application_Start event.

(26)

Notice that the Application_Start event has been created for us already.

We can go ahead and Delete AreaRegisteration.RegisterAllAreas() because we are not using any MVC areas at the moment.

(27)

MVC ROUTING

Double click “RegisterRoutes”

Click “F12” to navigate where the web application is registering its routes

You’ll see that it opens the file “RouteConfig.cs” that has the RegisterRoutes function

RouteConfig.cs is located under the App_Start folder in the solution explorer

In this file, all of the routing for the website is setup. You can see the following path is ignored

(28)

This path is ignored to prevent requests for the auto-generated Web resource files such as WebResource.axd or ScriptResource.axd from being passed to a controller.

The other part of the code is routing all http requests to {controller}/{action}{id}

With the default value of the controller = “home”, action =”index”, and id = UrlParameter.Optional

(29)

CREATING A HOME PAGE

To create a home page, we need to create a “Home” controller with an action result of “Index”

Right click the controller folder in the solution explorer -> add -> Controller

(30)

Select MVC controller empty Then click add

Change the controller name to “HomeController”

Then click Add

(31)

An action result for “Index” is created for you automatically

Under “Controllers” folder in the solution explorer you will see “HomeController.cs” has been created And under Views folder you will see a “Home” folder has been created for you

(32)

Right click the “Home” folder and click add -> view

(33)

Change the view name to “Index”

Uncheck “use a layout page”

Click Add

Your Index view has been created as “index.cshtml” under the home folder and the html is generated in the index.cshtml

(34)

Inside of the Index.cshtml file, add the following “Hello World!” in between the <div> tags

Then type ctrl + s to save your changes.

Now start debugging your project.

(35)

You now see in the web browser that the Home -> Index action result is being displayed

Since in the RouteConfig.cs file the defaults are “Home” controller “Index” action, you can remove the following “/Home/Index” from the URL and click enter to see it load by default

Stop debugging in Visual Studio

(36)

CREATING MULTIPLE ACTIONRESULTS

Create a new Action Result in the Home controller called “About”

(37)

Add a new View called “About” in the Views\Home folder

(38)

Change the view name to “About”

Uncheck “use a layout page”

Click Add

Inside of the Index.cshtml file, add the following “<h1>About Us</h1>” in between the <div> tags

(39)

Save your changes.

Start debugging your project.

See that your webpage has been created

Stop debugging

(40)

SHARED LAYOUTS

Notice that the following code is redundant in both the Index and About view:

And

(41)

Create a new folder in the views folder

Name the folder “Shared”

Create a new View in the Shared folder called “_Layout”

(42)

Delete Layout=null;

(43)

And rename the title to “Campus News”

And then add @RenderBody() in between the <div>

Save your changes

@RenderBody() will be where the view’s HTML will be rendered.

(44)

Under the views folder, add a new view

Name the view “_ViewStart”

(45)

Delete everything except the Layout=null

Replace null with "~/Views/Shared/_Layout.cshtml"

Save your changes

The MVC Framework is programmed to look for a _ViewStart.cshtml file in which will execute at the start of each view's rendering. Any code contained within the code block in this file will execute before any code in the view. This helps us from having to declare the shared layout on every view that is created.

Delete the excess code from the Index view so that it looks like this:

Save your changes

Delete the excess code from the About view so that it looks like this:

Save your changes Start debugging

Right click and view source

(46)

Notice that all of the html for the view is using the HTML content of the _Layout view, placing the About view HTML where RenderBody() should be

(47)

Stop debugging

(48)

NUGET PACKAGES

NuGet is the package manager for the Microsoft development platform including .NET. The NuGet client tools provide the ability to produce and consume packages. The NuGet Gallery is the central package repository used by all package authors and consumers.

NuGet is a Visual Studio extension that allows you to search for, install, uninstall and update external references in your projects and solutions.

In conclusion, you can add all types of external references that can help speed up your coding and at the same time, make sure to receive quality updates of the external references.

We’ll start off by adding our first NuGet package, Twitter Bootstrap. We’ll install more NuGet Packages later, but right now we should get the design of the webpage to look more appealing. I’ll explain Twitter Bootstrap after we install the NuGet Package.

(49)

Right click your project and click “Mange Nuget Packages…”

(50)

The Nuget Package Manager window will open. Click the filter and select “Installed”

These NuGet packages were added by default because they are the Core references for our basic Web Project.

(51)

Search for “twitter bootstrap” with filter of “All”

Click “Install”

(52)

Notice that the review changes window says that it is installing jQuery, Bootstrap and Twitter.Bootstrap.

jQuery is in here because it is a prerequisite package needed for Twitter Bootstrap.

Click OK

A readme.txt file will open, go ahead and close out of it. It’s just letting us know that all future updates for Twitter Bootstrap will be the bootstrap package instead of the twitter.bootstrap package.

If we go to the NuGet Package Manager and select “Installed” under the filters, you can see all of the NuGet packages installed for your project (make sure to clear out the search field that was previously

“Twitter Bootstrap”)

(53)
(54)

Some of the NuGet packages in here were pre-existing when we created the new project. The new NuGet packages that have been added are:

 bootstrap

 jQuery

 Twitter.Bootstrap

Notice that there is an upgrade available for bootstrap. Go ahead and select version 3.35 and click upgrade

The update preview will inform us that it will also upgrade jQuery. Click OK

(55)

BOOTSTRAP

The bootstrap NuGet package is for installing the external library bootstrap:

http://getbootstrap.com/

Bootstrap is the most popular HTML, CSS, and JS framework for developing responsive, mobile first projects on the web. It’s a framework that experienced developers spent thousands of hours creating that you can use to create your webpage instead of manually writing all the CSS yourself (reinventing the wheel is bad).

In the solution explorer you will see that the folder “Scripts” has been created with several Javascript files:

You will also see under the folder “Content” some CSS files have been created

And last but not least, some fonts have been added

(56)

JQUERY

The jQuery NuGet package is for installed the external library jQuery:

https://jquery.com/

jQuery is a fast, small, and feature-rich JavaScript library. It makes things like HTML document traversal and manipulation, event handling, animation, and Ajax much simpler with an easy-to-use API that works across a multitude of browsers. With a combination of versatility and extensibility, jQuery has changed the way that millions of people write JavaScript. It’s a framework that experienced developers spent thousands of hours creating that you can use to create you webpage instead of manually writing all of the Javascript yourself (reinventing the wheel is bad). jQuery functions are short and sweet where if you had to manually write the Javascript yourself you would write a at least eight lines per one line of jQuery (and have to figure out how to handle all the different types of browsers).

ADDING REFERENCES TO JAVASCRIPT AND CSS FILES

To start taking advantage of bootstrap and jQuery, you need to reference them in your project.

Open the _Layout view.

Click and drag the bootstrap.css file below the <title> tag

(57)

Click and drag the bootstrap.js file there too

And the same for the jQuery-1.9.1.js file

Note: the bootstrap.js relies on the jquery-1.9.1.js file, so jquery-1.9.1 must be referenced first.

And while we’re add it, let’s go ahead and cut and paste add our <script> tags to the bottom of the document, right before “</body>”

(58)

Putting that script at the bottom of the body guarantees the DOM is ready to be manipulated, if you put it in the head, you have to wrap it so that it waits for the DOMReady(or similar) event.

The Document Object Model (DOM) is an application programming interface (API) for valid HTML and well-formed XML documents. It defines the logical structure of documents and the way a document is accessed and manipulated.

Now start debugging your project, you will see the webpage looks exactly the same because although we referenced these files, we’re not using them yet

Stop debugging

(59)

To start using bootstrap, we can use a template on bootstraps website http://getbootstrap.com/getting-started/#examples

(60)

Scroll until you find “Fixed Navbar” example

(http://getbootstrap.com/examples/navbar-fixed-top/) The click the example

Right click the page and click view source

(61)

Go ahead and copy the code inside the entire <body> to </body> html

Paste the code, replace the html inside <body> to </body> in the _Layout file (except for the <script>)

(62)

Delete the html code for the scripts at the bottom

And replace the <div class=”jumbotron”>

With @RenderBody()

There was an extra custom CSS file the bootsrap example was referencing “navbar-fixed-top.css”:

(63)
(64)

So we need to create this file under the “Content” folder. Right click the folder and select add -> style sheet

Type in “navbar-fixed-top.css” and click OK

(65)

Go back to the viewed source, hold down “ctrl” and click the “navbar-fixed-top.css” to view the contents of the file

Copy this CSS and add it to the navbar-fixed-top.css file in the project

Delete “min-height: 2000px”

Save changes

Go to _Layout and add reference to navbar-fixed-top.css

(66)

Start debugging

And now we’re using a bootstrap template as the design of the web project.

Stop debugging

(67)

MVC RAZOR SYNTAX

Although we have a layout, none of the links will work until we route them correctly.

Hyperlinks in HTML look like this:

But in MVC we write them a little differently. In the _Layout view, find the following link:

<a href=”#”>Home</a>

And replace it with the following:

<a href=”@Url.Action(“Index”,”Home”)”>Home</a>

This way we are telling the View to create a hyper link that routes to the Index ActionResult for the Home controller.

Save changes, start debugging

Inspect element for the Home link in the navigation bar

You can see the following HTML has been generated from the MVC Razor code we wrote above:

Stop debugging Update the About link

Delete the contact link

(68)

Delete the drop down

Delete the “Static Top” and “Fixed Top” links

The following link we left and did not delete will not work properly, but we’ll update it to something later:

Update the navbar-brand link to:

Save changes, start debugging

You can click the Home and About link to see them routing correctly now Stop debugging

FORMATTING CODE

Delete all of the HTML comments.

HTML comments are green in the editor and start with <!-- and end with -->

(69)

Delete any empty lines

Ctrl+a and select all of the code

Then hold ctrl, then hold K then press F This formats your code to align and look neat

(70)

Right click one of the tabs in the top of the editor, for example “_Layout” and click “Close all documents”

(71)

DESIGNING VIEWS

You now have a lot of the _Layout view covered, let’s go back and update the HTML for the Index and About view.

Open the viewed source for the bootstrap template (http://getbootstrap.com/examples/navbar-fixed- top/), and copy the following HTML:

Paste this HTML into the Index view (replacing “Hello World!”)

Change the text inside of the <h1> tag to “Campus News”

Delete all the <p> tags and replace them with:

<p>Welcome to the Campus News page. The best place to find all of your campus news!</p>

(72)

And we’ll add the example of rows and columns from the following template (http://getbootstrap.com/examples/justified-nav/):

Open the page, right click and view source Copy the “Example row of columns” HTML

(73)

Paste the copied HTML into the Index view, below the jumbotron </div>

Update the <h2> and <p> tags to look like news posts

At the very top of the Index view add the following @{ ViewBag.Title = “Home”; }

(74)

Save changes Open the About view

Add the following <small> inside the <h1>

<small>we bring the news</small>

Wrap the <h1> with a <div class=”page-header”>

I found the example for page-header here:

http://getbootstrap.com/components/#page-header

Add the following <p> to describe the about page

<p>We are a small team that publishes the campus news online for our fellow students. Nothing makes us happier than letting everyone know what is and what is not important.</p>

At the very top of the Index view add the following @{ ViewBag.Title = “About”; }

Save changes

Open _Layout and add the following @ViewBag.Title to the <title>

(75)

Start debugging, view your updates to the Index and About page

Notice the title of the page changes based on each page because we added the ViewBag.Title

Stop debugging

(76)

MODEL BINDING

Model binding in MVC provides a simple way to map posted form values to a .NET Framework type and pass the type to an action result as a parameter. It’s a clean and organized way to receive and process inputted data on the webpage.

Let’s start off by creating a new controller called “Account”

Create a new folder under the folder Models called “Account”

Under the Account folder, create a new class file

(77)

Name the file “RegisterModel”

Declare two new strings properties public string Email {get;set;}

public string Password {get;set;}

Add “Public” in front of “class RegisterModel”

Save changes

Go to the Account controller and add the following using statement:

using CampusNews.Models.Account;

(78)

Create a new action result called Register

Inside of the action result, create a new instance of the RegisterModel like this:

var model = new RegisterModel();

Then pass the model to the view like this:

return View(model);

Create a new view called Index under Views\Account\

Leave the generated text as is:

(79)

Create a new view called Register under Views\Account\

Select “create” as the template and “ReigsterModel” as the Model class

In the Register view, Delete the very last div

Save changes and start debugging

(80)

Right click and view source

Compare and see all of the HTML the MVC Razor code generated for you.

@using (Html.BeginForm())

@Html.AntiForgeryToken()

We need this to prevent CSRF attacks. CSRF stands for Cross Site Request Forgery.

Cross Site Request forgery is a type of a hack where the hacker exploits the trust of a website on the user. In other words, the site trusts the user (because they have authenticated themselves) and accepts data that turns out to be malicious.

A CSRF attack depends on the fact that the site trusts the user’s input. From here on the hacker attempts to get authenticated users to click on links that submit data without the user actually realizing. For example, say you are logged on to your bank that has the ability to transfer money from one account to another. The hacker somehow reverse engineers this form and sets up a duplicate form that submits transfer requests to their own account.

@Html.AntiForgeryToken() ensures that a form being posted to the server was actually generated by the same server. Thus fake forms that do not have the AntiForgeryToken from the correct server, gets rejected.

We will add the other half of AntiForgeryToken to our controller in a bit.

On with the HTML generated for model.Email

@Html.LabelFor(model => model.Email)

@Html.EditorFor(model => model.Email)

@Html.ValidationMessageFor(model => model.Email)

And last but not least, the HTML generated for model.Password

(81)

Stop debugging

We are successfully displaying the Register view, but we aren’t processing any of the values when the user submits the form.

Go to the Account controller GET VS POST

Whenever you load a webpage, the default method of loading it is “GET”. The other type would be you submitting a form, which would be “POST”

So to process the submitted values of the Register view, we need to add another action result to our Account controller that accepts the POST values of the RegisterModel.

We also need to add the other half of AntiForgeryToken:

Add a debug marker to the beginning of this action result by placing your cursor at the first curly bracket and typing F9

Save changes

Update the _Layout view and change the <a href="../navbar/">Default</a> link to route to the Account\Register view and change the “default” test to “Register”

(82)

Start debugging, go to the register page

Type in some values for email and password fields, then click the create button

Visual Studio will then successfully hit the breakpoint we added. If you hover over “model” in the parameter, you can see the values coming in

Click F5 to allow the breakpoint to continue Stop debugging

Model binding has allowed us to use the code from the model to easily generate html in the view and accept POST values in the controller.

(83)

MODEL VALIDATION

Validation should be added to your models to assure you have clean data before trying to go on to a next step (e.g. make sure email is valid before letting a user register).

Open RegisterModel and add the following using statement:

using System.ComponentModel.DataAnnotations;

Make RegisterModel’s base class IValidatableObject

Create a new function that returns an IEnumerable <ValidationResult> called Validate

Inside of the Validate function, add a condition that checks if the string Email is null or empty

Start debugging and navigate to the register page

(84)

On the register page, leave the email blank and type in “test” for password, the submit the form You hit the breakpoint and should see that the email has a null value.

Click F5

Notice on the view, you can see it has our validation error

Type in “test” for the email and submit again Click F5 to get past the breakpoint

Notice the view no longer has a validation error Stop debugging

(85)

Inside of the RegisterModel, create a public void Save() {}

This will be the code we call if the data in our view provided is correct, we need to add it to the controller to be called now.

On the Account controller for the [HttpPost] register, add to call the Save if ModelState.IsValid

Remove all existing debug points (by toggling F9) and then add one to model.Save();

(86)

Navigate to the register page, leave the email blank and password = “test” and submit the form You will see the validation message “Email is empty”

Change the email field to “test” and password field to “test” and submit the form again You will see that the breakpoint to save has been hit

Click F5

Stop debugging

Now let’s add some validation to check if Email is a correct email address.

There’s no reason to reinvent the wheel, so we’ll use some code from MSDN’s website https://msdn.microsoft.com/en-us/library/01escwtf%28v=vs.110%29.aspx

(87)

Create a new folder in the project called “Helpers”

Then create a new class called “RegexUtilities.cs”

Copy the code from MSDN

(88)

And paste into RegexUtilities.cs

(89)

Then add wrapping namespace around all of the code namespace CampusNews.Helpers{}

Add custom code to beginning of RegexUtilities public static bool IsEmailValid(string email) {

var regexUtilties = new RegexUtilities();

return regexUtilties.IsValidEmail(email);

}

Save changes

(90)

Add the following using statement:

using CampusNews.Helpers;

Inside of validate, add the following validation for the email

Add the following validation to check if Password is null or empty

And then add the following validation to check if Password is at least six characters in length

Save changes Start debugging

Try out all your new validation Stop debugging

(91)

DATABASES

WHAT IS A DATABASE CREATING A DATABASE DEPLOYING A DATABASE ACCESSING A DATABASE

ADO.NET ENTITY FRAMEWORK WHAT IS ADO.NET

CREATING DATA MODEL SAVING DATA

READING DATA

References

Related documents

To create shortcuts for a file or folder, in the right pane of Windows Explorer, right click on the desired file or folder and select Create Shortcut. The shortcut is created in

Q 106: After the engine start, the Pack Flow Control Valves automatically open, however on the ground, reopening of the valves is delayed for _____ after the first engine start. A:

(repeat for each folder) Double click on the “HTTP Response Headers” icon. Click “Set Common Headers” in the right-hand pane. IIS Manager &gt; Application Pools &gt; Add

Rational Application Developer provides a wizard to easily create new custom Dojo widgets.. Right-click on the WebContent/dojo folder and select New &gt;

Navigate to office A IPPBX Web menu Basic-&gt;Trunks-&gt;VoIP Trunks page, click on “ New VoIP Trunk ” to create a peer trunk.. This trunk will be used for the other IPPBX to

As can be seen from the results obtained in this work, the use of DLLME procedure leads to further improve- ments in sensitivity and detection limits compared with SDME method,

After successful completion of this course students will be able to: • Identify the main concepts in the web development environment • Create web pages using HTML and CSS.. •

The properties window allows you to center items on the page, determine the fonts, colors, and size of text, type in links, and configure other features.. The body window is the