Connecting an MVC application to a database Jim Warren, COMPSCI 280 S2 2014 Enterprise Software Development.

Slides:



Advertisements
Similar presentations
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 15 Introduction to Rails.
Advertisements

Introduction to HTML & CSS
Introduction to MVC Adding a View Page NTPCUG Tom Perkins, Ph.D.
Further exploring the View aspect of MVC Jim Warren, COMPSCI 280 S Enterprise Software Development.
11 Getting Started with ASP.NET Beginning ASP.NET 4.0 in C# 2010 Chapters 5 and 6.
Chapter 10 Database Applications Copyright © 2011 by The McGraw-Hill Companies, Inc. All Rights Reserved. McGraw-Hill.
The Web Warrior Guide to Web Design Technologies
Web Development in Microsoft Visual Studio Slide 2 Lecture Overview Introduce Visual Studio 2013 Create a first ASP.NET application.
Getting Started with Microsoft Visual Studio,.NET and C# Jim Warren, COMPSCI 280 S Enterprise Software Development.
1 Chapter 12 Working With Access 2000 on the Internet.
J4www/jea Week 3 Version Slide edits: nas1 Format of lecture: Assignment context: CRUD - “update details” JSP models.
Further exploring database operations in MVC Jim Warren, COMPSCI 280 S Enterprise Software Development.
ASP.NET Programming with C# and SQL Server First Edition
ASP.NET Programming with C# and SQL Server First Edition Chapter 8 Manipulating SQL Server Databases with ASP.NET.
Chapter 14: Advanced Topics: DBMS, SQL, and ASP.NET
Chapter 12 Database Connectivity with ASP.NET JavaScript, Third Edition.
Chapter 7 Managing Data Sources. ASP.NET 2.0, Third Edition2.
1 An Introduction to Visual Basic Objectives Explain the history of programming languages Define the terminology used in object-oriented programming.
1 Chapter 20 — Creating Web Projects Microsoft Visual Basic.NET, Introduction to Programming.
Windows.Net Programming Series Preview. Course Schedule CourseDate Microsoft.Net Fundamentals 01/13/2014 Microsoft Windows/Web Fundamentals 01/20/2014.
Some Basic Database Terminology
Lecture 3 – Data Storage with XML+AJAX and MySQL+socket.io
Introduction to MVC Adding Model Classes NTPCUG Tom Perkins, Ph.D.
1 Working with MS SQL Server. 2 Objectives You will be able to Use Visual Studio for GUI based interactive access to a Microsoft SQL Server database.
Session 5: Working with MySQL iNET Academy Open Source Web Development.
ASP.NET Programming with C# and SQL Server First Edition
Connecting a.NET application to a database Jim Warren, COMPSCI 280 S Enterprise Software Development.
Building a UI with Zen Pat McGibbon –Sales Engineer.
NOTE: To change the image on this slide, select the picture and delete it. Then click the Pictures icon in the placeholder to insert your own image. WEB.
Microsoft Visual Basic 2005: Reloaded Second Edition
BIT 286: Web Applications Lecture 04 : Thursday, January 15, 2015 ASP.Net MVC - Models.
ASP.NET  ASP.NET is a web development platform, which provides a programming model, a comprehensive software infrastructure and various services required.
PHP Programming with MySQL Slide 8-1 CHAPTER 8 Working with Databases and MySQL.
10-1 aslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhf.
Chapter 15: Using LINQ to Access Data in C# Programs.
E-Commerce: Introduction to Web Development 1 Dr. Lawrence West, Management Dept., University of Central Florida Topics What is a Web.
Web Programming: Client/Server Applications Server sends the web pages to the client. –built into Visual Studio for development purposes Client displays.
Web Server Administration Chapter 7 Installing and Testing a Programming Environment.
Getting Started with Microsoft Visual Studio,.NET and C# Jim Warren, COMPSCI 280 S Enterprise Software Development.
11 Web Services. 22 Objectives You will be able to Say what a web service is. Write and deploy a simple web service. Test a simple web service. Write.
ASP.NET MVC applications in C# Jim Warren, COMPSCI 280 S Enterprise Software Development.
Introduction to ASP.NET MVC Information for this presentation was taken from Pluralsight Building Applications with ASP.NET MVC 4.
1 Data Bound Controls II Chapter Objectives You will be able to Use a Data Source control to get data from a SQL database and make it available.
Tutorial 7 Creating Forms. Objectives Session 7.1 – Create an HTML form – Insert fields for text – Add labels for form elements – Create radio buttons.
Introduction to Entity Framework Part 2 CRUD Scaffolding Tom Perkins NTPCUG.
New team member / new project for the team Helps analyze relationships and structure Understanding code Locates code in unfamiliar code bases Understand.
Further exploring database operations from C#/.NET Jim Warren, COMPSCI 280 S Enterprise Software Development.
Searching Business Data with MOSS 2007 Enterprise Search Presenter: Corey Roth Enterprise Consultant Stonebridge Blog:
CSCI 6962: Server-side Design and Programming Database Manipulation in ASP.
BIT 285: ( Web) Application Programming Lecture 15: Tuesday, February 24, 2015 Microsoft Azure Instructor: Craig Duckett.
BIT 286: Web Applications Lecture 10 : Thursday, February 5, 2015 ASP.Net Form Submission.
Rails & Ajax Module 5. Introduction to Rails Overview of Rails Rails is Ruby based “A development framework for Web-based applications” Rails uses the.
Creating a simple database This shows you how to set up a database using PHPMyAdmin (installed with WAMP)
Database Connectivity with ASP.NET. 2 Introduction Web pages commonly used to: –Gather information stored on a Web server database Most server-side scripting.
Rich Internet Applications 2. Core JavaScript. The importance of JavaScript Many choices open to the developer for server-side Can choose server technology.
11 Getting Started with ASP.NET Beginning ASP.NET in C# and VB Chapters 1 and 2.
Chapter 9 Working with Databases. Copyright © 2011 Pearson Addison-Wesley Introduction In this chapter you will learn: – Basic database concepts – How.
Entity Framework Database Connection with ASP Notes from started/getting-started-with-ef-using-mvc/creating-an-
BIT 286: Web Applications Lecture 04 : Thursday, January 15, 2015 ASP.Net MVC -
BIT 286: Web Applications ASP.Net MVC. Objectives Applied MVC overview Controllers Intro to Routing Views ‘Convention over configuration’ Layout files.
COM621: Advanced Interactive Web Development Lecture 10 PHP and MySQL.
1 Adding a Model. We have created an MVC web app project Added a controller class. Added a view class. Next we will add some classes for managing movies.
Jim Fawcett CSE686 – Internet Programming Spring 2014
ASP.NET Programming with C# and SQL Server First Edition
Jim Fawcett CSE686 – Internet Programming Spring 2012
Introduction and Principles
Microsoft Office Illustrated
Web Development in Microsoft Visual Studio 2013
Database Applications
Presentation transcript:

Connecting an MVC application to a database Jim Warren, COMPSCI 280 S Enterprise Software Development

Today’s learning objectives  To be able to program the key components of a C#/.NET MVC application for  Establishing a database connection  Defining a data model for its tables  Querying the database  Presenting the user a view of the results  To gain familiarity with use of the MVC pattern and its application to a Web application in practice COMPSCI 2802

The Model-View-Controller approach  Last lecture we introduced the MVC pattern and instantiated a default Internet Application template for MVC in C#/.NET  Today we want to learn more about the MVC components and other supporting files of the application so we can integrate the application with our own database  The Model will define the database connection and map C# classes to the database tables  The View will be tailored to present information from a table  The Controller will execute database queries and return data as parameter to the View COMPSCI 2803 See

Getting MySQL and.NET to play together  Principles are the same regardless of the database solution  Get the infrastructure (DBMS and its tools)  Set up a database and get its server running  Establish interoperability of the database and the.NET environment .NET is proprietary to Microsoft, so they’d prefer you ran Microsoft SQL Server (‘Express’ version is included Visual Studio) rather than a competitor such as the free MySQL  Add to your program a ‘connection’  This specifies the running DBMS service, which database (set of tables, views etc.) you want and your ‘login’ as an authorised user on that database COMPSCI 2804

Specifics  Get MySQL running  I did this by installing XAMPP to get MYSQL, Apache, XAMPP Control Panel and PHPMyAdmin  Then just start Apache* and MySQL in XAMPP Control Panel  Used PHPMyAdmin to build an employee database with an employee table, and also to add a user “jim”  Establish interoperability of the technologies  Installed MySQL Connector Net  Did Project/Add Reference/Browse in VS to add the MySql.Web.dll and MySql.Data.dll from ConnectNet's Assemblies\v4.5 subdirectory * Apache only needed for PHPMyAdmin -.NET will use Internet Information Server (IIS) Express to serve the applications Web pages COMPSCI 2805

Add a connection  Go into Web.config (from Solution Explorer)  It’s an XML file with project metadata  There’s already a connection defined  It’s used for the user accounts that are built into this project by default  We’ll put in another ‘add’ COMPSCI 2806 The connection name will come up in the Model Part of that DLL we got from MySQL Connector Net The MySQL user we defined (and its password! – note you can encrypt part of configuration for security: us/library/ms254494(v=vs.110).aspx

Our Model: Employee.cs Handout 01COMPSCI using System.Data.Entity; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace MvcLetsConnect.Models { public class EmployeesContext : DbContext { public EmployeesContext() : base("MySqlConnection") { } public DbSet Employees { get; set; } } [Table("employee")] public class Employee { [Key] public int IDnum { get; set; } public string Surname { get; set; } public string GivenNames { get; set; } public DateTime DateOfBirth { get; set; } } First ‘using’ directive is added for referencing the DbContext object; next two are for the ‘key’ and ‘table’ decorators Use that connection we added to the Web.config file Our context’s DbSet ‘Employees’ will be a collection of objects of type Employee The table in MySQL is named ‘employee’ Define properties of this class with names matched to table fields in MySQL ([Key] identifies IDnum as the primary key as set in MySQL) Entity Framework can create the table entity definitions graphically/automatically for SQL server, but still in beta for MySQL

Our Controller  The HomeController.cs file includes the handler for the index (home) page  Creating an instance of the Employees context initiates the database connection  Putting it in a ‘using’ statement is tidy – invokes the connection’s dispose method, which closes the connection when we’re done serving up the page  We can then invoke methods on the Employees collection such as to.Count() them or assign the whole collection as an enumerable list to be pointed to by an implicitly typed (‘var’) element that we pass to the View COMPSCI 2808 public ActionResult Index() { using (EmployeesContext db = new EmployeesContext()) { int j = db.Employees.Count(); ViewBag.j = String.Format("We have {0} records.",j); var data = db.Employees.ToList(); return View(data); } C# moment: the.Format method of the String class is handy for laying out output

Our View  Using the Index.cshtml file we display the data for the user on the home page COMPSCI ViewBag.Title = "People"; WebGrid grid = new WebGrid(Model); new [] { grid.Column("Surname","Last Name"), grid.Column("GivenNames","Given Names"), grid.Column("DateOfBirth","Date of Birth") }) keyword in Razor says that the data passed to the View will be interpreted as an enumerable list of Employee objects as defined in the Model section of the project Using C#-like syntax in a Razor code block we instantiate an instance of the WebGrid helper on the Model data Razor functions put the text of element ‘j’ of the ViewBag and the instance of a WebGrid into the body of the HTML. Each WebGrid Column is instantiated on an exact property name of the Employee class from the model

The result Handout 02COMPSCI 28010

The result: a closer look Handout 02COMPSCI In Chrome, if you right-click and select ‘Inspect Element’ it’ll open a window showing the HTML (bottom left) and the CSS styles that have been applied (bottom right)

A closer look (contd.)  The WebGrid and ViewBag aren’t there  Just as the C# code has been converted to CIL for the CLR, the View’s Razor syntax has been converted to HTML for the browser to consume  HTML moment: The tag defines the start of a table, with a to start each row and a (‘table data’) to start each cell  Note that Chrome’s Inspect Element navigation has opened the elements directly leading to the cell we inspected but, for instance, has the table header definition (‘thead’) closed Handout 02COMPSCI 28012

A closer look (contd. again)  If we inspect the ‘Given Names’ column header, we see that the WebGrid helper did even more for us  It built a hyperlink (HTML ‘a’ – for ‘anchor’ – tag) which sends back to the Controller a request for the page in a different sort order (and the Controller automatically knows how to handle this, too!)  Note how the Employee class property name (‘GivenNames’) is used in the URL  If we had had more rows, the WebGrid would’ve also built us links for paging the data Handout 02COMPSCI 28013

Making your mark with style  We can add a style parameter to the constructor for a grid.Column  In the Site.css file (under Content in the Solution Explorer) we can create a corresponding style definition to apply to any element of class surname  And the VS intelli-sense greatly assists writing the CSS code!  We can also change any HTML tag’s styling for the whole site by editing in Site.css  E.g. to make all the rows of any table amber (not depicted in next slide) Handout 02COMPSCI new [] { grid.Column("Surname","Last Name",style:"surname"),.surname { font-style: italic; width: 150px; } tr { background-color: #ffe030; }

Styling result Handout 02COMPSCI The class attribute of each body cell in the Last Name column has been given the value we specified Chrome has picked up to apply the style to the content (note how the Inspect Element tooltip [left] shows the cell as ‘td.surname’) n.b. You’ll probably need to hit Refresh on your browser to get the style change to show up

Another query syntax: LINQ  Language Integrated Query (LINQ)  Can modify our HomeController.cs to read:  Very similar to SQL, but actually part of.NET (i.e. integrated with the C# language)  Differs in leading with ‘from’ and ending with ‘select’ (a better order for the intelli-sense!)  Note that the class of the objects returned by the query (each row, the members pointed to by emp ) has to align to in the View definition Handout 02COMPSCI using (EmployeesContext db = new EmployeesContext()) { var emp = from e in db.Employees where e.DateOfBirth.Year < 1975 select e; return View(emp.ToList()); }

Where we’re up to  We’ve now been introduced to the MVC approach in C#/.NET  And we’ve seen how to connect it to a MySQL database  Now…  Work the first labsheet (if you haven’t already)  Look at Assignment 2 (if you haven’t already)  Make a start – use your break time wisely and don’t be afraid to read ahead into weeks 7 and 8  In weeks 7 and 8 we’ll extend what we can do with MVC in C#/.NET and get a firmer understanding of what we’ve used so far Handout 02COMPSCI 28017