COMPSCI 280 S2 2014 Enterprise Software Development Getting Started with Microsoft Visual Studio, .NET and C# Jim Warren, jim@cs.auckland.ac.nz Welcome (to this part of 280)! Your lecturer: Jim Warren These 3 weeks will provide you skills to create .NET MVC (model-view-controller) applications (a way of making websites) and to connect them to an underlying database 2 jim@cs.auckland.ac.nz x86422 Office: Tamaki 723-318 Office hours: by arrangement (try email first, and we’ll start an FAQ for assignment 2) There’s a lab sheet for each week to walk through programming methods The tutor will also reinforce the topics from lecture COMPSCI 280 Handout 01 Assignment 2 Create an MVC application Assignment spec on course website 3 Handles viewing and updating of a database Does database connection, query and update from C# Creates HTML form interaction in the MVC framework Includes validation of user input Due noon Friday (before class!) on week 8 (26th September) Worth 5% of course mark Do lab sheet 1 and then get into the assignment before the break! COMPSCI 280 Handout 01 Today’s learning objectives 4 To be introduced to the .NET framework, including Visual Studio and C# To be able to describe characteristics of the Common Language Runtime To be able to describe the general characteristics of the MVC paradigm and its rationale COMPSCI 280 Handout 01 Visual Studio (VS) For Assignment 2, we will use Visual Studio to do our application programming What is Visual Studio? Why an IDE? 5 Visual Studio is an example of an "Integrated Development Environment" (IDE) Think of an IDE as an application that combines code editor, compiler, debugging and other tools that make the design, maintenance, and documentation of large projects easier Remember how our Java projects already consisted of multiple files for different classes? This is characteristic for large projects In MVC applications we’ll see that we have many types of files (for ‘M’, ‘V’, and ‘C’, and various aspects of the website template, system configuration and helper functions) VS lets us manage these features and content in a convenient way COMPSCI 280 Handout 01 Visual Studio and C# Helpful background reading Visual Studio from the Microsoft Developer Network (MSDN) http://msdn.microsoft.com/en-us/library/dd831853.aspx (and particularly the Application Development in Visual Studio link). C# introduction VS supports multiple languages (C#, C++,Visual Basic, J#) in the one IDE All with nearly identical functionality and performance because the use a common core VS produces many types of applications 6 http://msdn.microsoft.com/en-us/library/aa645597(v=vs.71).aspx ‘Console’ (processing with text interaction), Windows, Web, mobile It can also integrate with Microsoft Office applications (Word, Excel, etc.) COMPSCI 280 Handout 01 .NET Languages All Visual Studio .NET languages are object-oriented No matter the language, all programs have a similar structure Files are grouped into projects All programs compiled into Common Intermediate Language (CIL) 7 with syntax similar to Java File structure is similar for all languages With syntax similar to C++, but also borrowing a lot of ideas from Java Visual J# is also a new language Note that if you've done VB 6 in the past - the language has changed considerably! C# (C-sharp) is relatively a new language True inheritance and polymorphism are supported Also known as Microsoft Intermediate Language (MSIL) COMPSCI 280 Handout 01 The .NET Framework The .NET Framework define the rules for language interoperability and how an application is compiled into executable code. It is also responsible for managing the execution of an application created in any VS .NET language. The .NET Framework has two main components: the common language runtime (CLR) and the .NET Framework class library. CLR Manages memory, thread execution, code execution, code safety verification, compilation, and other system services The .NET Framework class library 8 Memory allocation, starting up and stopping processes Provides developers with a unified, object-oriented, hierarchical and extensible set of class libraries (‘application programmer interfaces’, APIs) COMPSCI 280 Handout 01 Execution Management The managed execution process includes the following steps: Choosing a compiler Compiling, code -> CIL/MSIL Compiling translates the source code into CIL and generates the required metadata (this package is an ‘assembly’ (e.g. a DLL is an assembly) Compiling, CIL -> native code The format is similar to assembly language but is hardware independent A just-in-time (JIT) compiler translates the assembly into native code (or runs it in a virtual machine) Conceptually, the process is similar to the Java Virtual Machine Running code The CLR provides the infrastructure that enables managed execution to take place as well as a variety of services that can be used during execution. Compiling Source code 9 Running Engine Language Specific Compiler EXE/DLL (CIL and metadata) COMPSCI 280 JIT Compiler Native Code Execution Handout 01 Garbage Collection The CLR performs memory management It manages the allocation and release of memory for an application Automatic memory management can eliminate common problems, A contiguous area of memory allocated to a process is called the managed heap Reference types are allocated from the managed heap The CLR reclaims memory using the Garbage Collector (GC) The GC examines variables to reclaim unused memory 10 such as forgetting to free an object and causing a memory leak, (common problems in C and C++ that lack garbage collection!) or attempting to access memory for an object that has already been freed. It looks for memory without a corresponding variable (root) COMPSCI 280 Handout 01 Namespace Physical assemblies are organized into logical components called namespaces Namespaces are organized into a hierarchy Microsoft has divided VS .NET into two primary namespaces: Common Namespaces: 11 The System namespace contains components developed by the .NET team The Microsoft namespace contains components developed by Microsoft but outside of the .NET development team The ‘System’ namespace contains fundamental classes System.Data namespace contains classes supplying data access capabilities As compared to e.g. Microsoft.Media.AdaptiveStreaming Namespace (we’ll mostly use parts of the System namespace) You’ll create namespaces for your own content (e.g. the data ‘model’ in your MVC application) COMPSCI 280 Handout 01 Creating a Console Application with VS Open Visual Studio (note I’m using VS 2012 – a few features get added most years, but mostly it stays the same) To create a new project called HelloWorldApp Note: Console.WriteLine("Hello World"); Console.ReadLine(); The Main method is the entry point of your program, where the program control starts and ends Insert Console.ReadLine() to the Main method which causes the program to pause until ENTER is pressed To run your application 12 Choose File->New Project MessageBox.Show("Hello, Select the project type: Visual C# world!"); Select the project template: Console Application Enter a name, Select a save Location and enter solution Name Select Create directory for solution Click OK – a program skeleton with a Main method that appears in the editor Insert the following code: You could also create a Windows Forms Applications and might use Press F5 to run the application, or Click the ‘Start’ button (with the green triangle [‘play’] icon) COMPSCI 280 Handout 03 The Model-View-Controller approach MVC is an architectural pattern Well, it’s ‘architectural’ when you make a project with directories for the 3 areas of concern; conceptually, it’s a design pattern Separates responsibilities in the application Model – the data (including the connection and mapping to the DBMS) and its integrity constraints (e.g. legal values of variables in terms of the domain logic) View – the rendering. What it looks like to the user and the detail of how they interact with the application Controller – Handles and responds to user interaction. Uses the model and selects the next view to offer the user. See http://www.asp.net/mvc/tutorials/older-versions/overview/asp-net-mvc-overview 13 COMPSCI 280 Handout 01 An MVC Project in VS Open VS File/New Project… select Visual C# and the ASP .NET MVC 4 Web Application type* Give it a name and location, press OK Select the default ‘Internet Application’ template with the Razor view engine Press OK and listen to the hard drive grind Solution Explorer (righthand side of screen in IDE) produces folders for the Controllers, Models and Views (alphabetical order) In this one I’ve added an additional C# class file (.cs) for entities in an employer database The default template includes account management (login, new user) MVC elements * I went with v4; 5 is out – there’s always something newer 14 COMPSCI 280 Handout 01 MVC application from the template Runs at ‘localhost’ served up by the built-in IIS Express local Web server 15 COMPSCI 280 Handout 01 The Controller The controller has a method of type ActionResult for each webpage in the solution The ViewBag object is dynamic; shortcut for tossing data to the View C# moment: note the “:” operator to indicate deriving a child class from a base class 16 using using using using using System; System.Collections.Generic; System.Linq; System.Web; System.Web.Mvc; namespace DefaultMVC.Controllers { public class HomeController : Controller { public ActionResult Index() { ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application."; } return View(); public ActionResult About() { ViewBag.Message = "Your app description page."; } return View(); COMPSCI 280 Handout 01 The Model Defines a database context (invoking the parent [base] class constructor to establish the database connection ... using System.Data.Entity; using System.Globalization; using System.Web.Security; namespace DefaultMVC.Models { public class UsersContext : DbContext { public UsersContext() : base("DefaultConnection") { } } public DbSet<UserProfile> UserProfiles { get; set; } Creates model definition for a table in the database (autogenerated primary key and a username). The context’s DbSet is a collection of user profile objects [Table("UserProfile")] public class UserProfile { [Key] [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)] public int UserId { get; set; } public string UserName { get; set; } } 17 COMPSCI 280 Handout 01 The View One .cshtml (C# HTML) file for each page of the solution Here we have the HTML for what the user sees on the index / home page But it’s not just HTML @{ ViewBag.Title = "Home Page"; } @section featured { <section class="featured"> <div class="content-wrapper"> <hgroup class="title"> <h1>@ViewBag.Title.</h1> <h2>@ViewBag.Message</h2> </hgroup> <p> To learn more about ASP.NET MVC visit <a href="http://asp.net/mvc" title="ASP.NET MVC Website">http://asp.net/mvc</a>. ... 18 The @ indicates Razor Syntax markup that is converted at run-time into HTML Can be a code block (essential C# syntax inside curly braces) Or can be an expression (e.g. @ViewBag.Message) Can be cryptic (e.g. @section featured is interpreted by the @RenderSection expression in the autogenerated _Layout.cshtml file COMPSCI 280 Handout 01