ASP.net Training - Canvas

27
ASP.net Training September 2014, Stephen Perks 1

Transcript of ASP.net Training - Canvas

ASP.net Training

September 2014, Stephen Perks

1

Agenda

1. Client / Server

2. Patterns

3. Architectures

4. Server : VB.net and C#

5. Server : ORM & LINQ

6. Client : HTML, CSS & Responsive

7. Client : Javascript & JQuery

8. Standards

9. Projects

10. Security

2

Client / Server

Clients and Servers

System.Web namespace for client-server communication

Request object (HttpRequest, XmlHttpRequest) ‘Get’, ‘Post’

Response object (HttpResponse, XmlHttpRequest)

Synchronous & Asynchronous processing

‘Separations of Concerns’ – Presentation, Business Logic, Persistence

SOA – Service Oriented Architecture

Tiered Systems

3

Client / Server

Tiered Systems:

• Separate out the concerns

• Increase flexibility

4

Design Patterns

Q. What is a software design pattern?

A. Generic reusable solution to a common programming challenge

5

Design Patterns

Lazy Load private string userName = null;

public string UserName

{

get

{

if (userName == null)

{

userName = getUserName(); //...get value from repository

}

return userName;

}

}

Optimistic Concurrency Allow concurrency conflicts to occur and let the OS manage them by interleaving updates on ‘last-in-wins’ basis. Consider detecting change using a timestamp / row-version and alert the user, asking them how they would like to proceed.

Pessimistic Concurrency Assume conflicts are likely to occur so create a resource lock on the object to be updated before attempting he update.

6

Design Patterns Factory To centralise the production of configured objects on demand

Repository To create a logical layer between business logic and data access.

The main benefit it to prevent tight coupling between business logic and a particular implementation of a database.

The Repository layer allows the database implementation to be amended without affecting business logic.

MVC To divide an application in to three elements, and define rules for their interactions:

The MODEL defines centralised data structures, business rules, and maintains state.

The VIEW provides a visual interface for an end-user.

The CONTROLLER responds to requests from the VIEW and interacts with the MODEL.

PRG (Post-Redirect-Get) To prevent form submissions being duplicated.

After posting form data using HTTP POST, issue an HTTP GET. This ensures that if the user requests a screen refresh (e.g. F5 key) then the GET will be repeated, not the POST e.g. Reponse.Redirect("somepage.aspx") after a POST.

Singleton To ensure a class has only one object instance, and provide a central point of access.

7

ASP Architectures

State management

• What is ‘state’? … it is the term for stored information, within a particular component, at a given moment in time

• HTTP is ‘stateless’ protocol

• There are many ways to store state in ASP.net

– Cache, Application, Session, Viewstate, Cookies, Querystring, Config, Membership, Objects, Database.

ASP.net Products

• 1998+ Classic ASP

• 2002+ Web forms

• 2003+ Web Pages / Web Matrix / Webmatrix)

• 2007+ MVC (v5 released 2014)

• 2013+ Web API

…collectively known as ‘One ASP.net’

8

Architectures Webforms

URL linked to File

Requests are routed to pages.

The ‘code-behind’ allows some separation-of-concerns.

Uses the drag-and-drop-and-configure paradigm.

Functionality via Server Controls

Intended as framework for allowing native client VB6 developers to cross-train to Web application development in a RAD (rapid

application development) environment.

Problems arise with the complex page life-cycle and the large page-size caused by the _VIEWState string.

It can also be difficult to enhance the client experience with Javascript libraries due to complex element naming.

9

Architectures MVC

URL linked to a single function

No complex page life-cycle

No heavy view state

Application has three components:

the Model (domain data & constraints)

the View (user interface)

the Controller (business logic)

Requests routed to Controllers and Methods

Suitable for developers who want full control over their application.

State is managed via the ‘model’ which is a strongly-typed object exchanged automatically between the View and the Controller.

Views are linked to methods within a Controller, so URLs are much cleaner, more editable, and SEO friendly.

Controllers are suited to automated testing (TDD).

Views don’t mangle element names, so integration with Javascript libraries is simplified.

10

Server : VB.net &C# The ASP.net Server architecture employs three steps to generate runtime code:

1. The business logic is specified in a high-level language such as VB.net, C#, others

2. The high-level code is translated into a common Microsoft Intermediate Language (MIL) code

3. The intermediate language code is compiled for the native platform/processor into machine code

So all high-level languages end up with the same MIL. So the choice of high-level language is not simply a technical one; the factors to consider include:

– Availability and cost of human resources (developers)

– Availability and quality of training materials and examples

11

Server : VB.net &C#

In May 2014, according to a trusted language popularity index, VB.net is 11th (1%) and C# is 6th (4%); FYI ‘C’ at 16% is the most popular.

The marketplace for C# developers has been increasing, and in decline for VB.net developers. The range of training materials and examples in C# now far outnumbers those in VB.net.

Schools and Colleagues routinely teach the C# language for projects not related to ASP.net

The pragmatic approach for organisations is to move to C# for human resourcing reasons; and they have been doing so for some years.

The pragmatic approach for developers, is to be competent in both VB.net and C#.

12

Server : C#

C# is a case-sensitive language, so userName and UserName are different variables

C# is modelled on Java syntax (by the person who designed Java)

C# is based on strong-typing / OOP (VB.net is an OOP implementation of VB6)

C# uses {} braces to delimit functions and [] square parenthesis

C# uses the ; semi-colon to terminate lines, so code can be fragmented over several lines without _ underscore continuation

C# syntax looks like Javascript syntax, which makes it easier when coding Server and Client components

C# uses = as an assignment operator, == as a value comparator, === as a type and value comparator … a common source of bugs!

C# uses ‘namespaces’ to separate classes from each other

13

Server : OO, ORM & LINQ OOP (Object-Oriented Programming)

What is OO?

A programming paradigm where entities are defined by …

Classes

Attributes

Behaviours

… and can be instantiated into discrete objects.

When you see a reference to ‘Strong Typing’ or ‘Strongly Typed’, it just means the object has been created from known Class.

It may be surprising to learn that OO technology is relatively mature…

OO programming was invented in 1963 as the language ‘Simlua’ for a Norway oil refinery simulation tool

14

Server : OO, ORM & LINQ

Why has OO become the standard?

As a solution to the increasing complexity of software (e.g. Microsoft operating systems)

Encapsulation (data is protected by methods – cannot be directly access or set)

Testability

Reusable components

Easily models real-world entities (Nouns=entities, Verbs=methods)

Inheritance (Superclass=generalisation, Subclass=specialisation)

Allows Multithreading & Parallel-Processing

15

Server : OO, ORM & LINQ

ORM - Object Relational Mapper ASP.net applications work with classes and objects, but data is usually persisted in tables and rows.

The role of the ORM is to mange the translations so we don’t have to.

Entity Framework (EF) This is Microsoft’s core ORM product; the most popular for other platforms is ‘nHibernate’.

EF uses ADO (Active Data Objects) to interface between a Database table and a class representation of the table.

LINQ (Language Integrated Query) Linq is a special type of syntax for manipulating collections of data

‘Collection’ could mean characters in a string array, or a set of strongly-typed objects

Linq is designed to allow objects to be manipulated using query-like syntax.

Note that Linq syntax is inverted compared to SQL in order to provide Visual Studio intellisense.

Linq is particularly useful for interrogating and retrieving data from data-object collections provided by Entity Framework

Practice using LinqPad.net

16

LINQ Extract a User object from the Database…

Public Class rast_Repository

Dim db As rastEntities = New rastEntities()

Public Function getUserByID(ByVal pUserID As Integer) As rast_SystemUser

Dim users As rast_SystemUser = Nothing ‘…declare the strongly-typed object

Try

'Attempt to retrieve the User via their unique ID...

users = (From u In db.rast_SystemUser Where u.UserID = pUserID Select u).Single()

If (user Is Nothing) Then

user = New rast_SystemUser

user.Username = “Error"

End If

Catch ex As Exception

'Log the problem...

End Try

Return user

End Function

End Class

17

LINQ Extract a collection of User objects from the Database… Public Class rast_Repository

Dim db As rastEntities = New rastEntities()

Public Function getUsers() As List(Of rast_SystemUser)

Dim users As List(Of rast_SystemUser) = Nothing

Try

db = New rastEntities()

'Attempt to retrieve Users...

users = (From u In db.rast_SystemUser _

Order By u.Username _

Select u).ToList()

Catch ex As Exception

'Log the problem...

End Try

Return users

End Function

End Class

18

Client : HTML, CSS & Responsive Browsers and Rendering Engines Evolved to become virtual machines / operating systems.

HTML4 (1997+) The most commonly used version; our standard platform for IE8

HTML5 (2008+) Supported by all modern browsers (IE9+)

Sophistication Effectively browsers are now mini operating systems / virtual-machines

19

Browser Engine Available

Internet Explorer (IE) Trident 1998+

Opera Presto, Webkit 2003-2013, 2013+

Chrome Webkit 2001

Safari Webkit 2003+

Firefox Gecko 1997+

Mobile Webkit Various

Client : HTML, CSS & Responsive

CSS = Cascading Style Sheet

CSS2 (2005+) and CSS3 (2011+)

CSS can be… inline (one-off styling)

internal (simple)

external (flexible)

Selectors elements p, a, h1

attributes #UserID

classes .error, .button

Responsive design ‘viewport’ and @media queries

Testing Browserstack.com

Adobe

Locally

20

Client : Javascript & JQuery

Goal is to produce a Rich User Interface (RUI) and deliver the ‘desktop experience’ over the web

Javascript Since 1995, providing client-based interpretive, object-based scripting language to manipulate DOM elements and interact …between user and client machine.

Based on C, and syntactically similar to Java and C#

Core language for Win-8 Apps

Practice using JSBin.com

Browsers and JavaScript Engines Each browser implements their own Javascript engine

Google’s Chrome engine much faster than IE until IE v9

Some syntax and behavioural differences.

Javascript libraries Jquery.js

Knockout.js

Modernizr.js

… and many others

21

Client : Javascript & JQuery

DOM Document Object Model

Each HTML element has an associated object

JQuery Tool to easily manipulate the DOM

Provides a browser-agnostic (auto-adjusts) Javascript environment.

Rich library of ‘plugins’ which extend JQuery functionality to provide specific behaviours, e.g. client-side table sorting.

JSON objects Java Script Object Notation is the de-facto standard for lightweight data-interchange; less verbose than XML.

{ Patients [ {“id” : “1”, “name” : “John” },

{“id” : “2”, “name” : “David” },

{“id” : “3”, “name” : “Sallly” } ] };

Ajax Use XMLHTTP object to perform asynchronous ‘callback’ operations from the Client to the Server

e.g. dynamically retrieve data and update the DOM (ASP.net Update panel)

22

Standards & Best Practice

Build for today’s Internet The full postback model is being replaced by the asynchronous model

End-users expect (and deserve) a high-quality interface and excellent usability experience

Convention over configuration Specify how things can be done through easy-to-follow examples

Try to apply coding standards

Follow Project standards

Best-practice is always evolving Evolution and revolution

Simple & flexible

Assume the design will change

Small page-size … consider ‘minification’

Combine CSS into cacheable external .css

Combine Script in cacheable external .js

Put CSS reference first and Script reference last

Consider serving initial-load CSS and Script separately

Yahoo web standards - https://developer.yahoo.com/performance/rules.html

Google web standards - https://developers.google.com/speed/docs/best-practices/rules_intro

23

Projects

Waterfall Traditional way of developing software

The project’s functionality is, as far as possible, pre-specified and agreed before any software is built and tested

Suitable for large projects, or contract-based projects, or where requirements can be fully specified in advance and remain static

Agile The project’s functionality is specified and refined by frequent iteration of working software

Suitable for small-to-medium projects, or where the requirements are necessarily emergent

Key Documents Standards

Mockups

Requirements Register using ‘MoSCoW’ mnemonic (Must-have, Should-have, Could-have, Won’t-have)

Use Cases (workflow to include)

Wireframe (workflow navigation)

Issues and Change Log

Test Plan

User Guide

Technical Support Guide

24

Security Things to consider…

Authentication and Authorisation LDAP / Active Directory (Windows authentication)

Membership (forms authentication)

Social login (OAuth/OWIN, OpenID)

System ‘roles’

SQL Injection – Textboxes and Querystring attacks e.g. < > script, or login hack using Username = hello’ OR 1=1--

Cross-site Scripting XSS – manipulation of events by injecting client-side script; e.g. steal session cookie

Databases exposed via SOA (Service Oriented Architecture)

Use Strongly-typed objects

Deploy with Debug=false

Input should be constrained (e.g. by range or type)

Input should be HTML encoded (default in MVC)

Use the ASP Request validation “__RequestVerificationToken” hidden field (default in Webforms)

Parameterised queries (default in EF)

25

Next Steps

How do I learn…

C#, MVC, Javascript, JQuery, Ajax, CSS ?

Informatics Review existing Informatics projects

\\uhb\userdata\Information\Information\Common\ReportingServices\ASP.net\Training\Steve's examples

Microsoft http://www.asp.net/

http://www.microsoftvirtualacademy.com/

Take their free courses!

Plural Sight Watch their videos

Safari Books Online Read their books

Stack Overflow http://stackoverflow.com/

26

Questions

Contact [email protected]

27