Introduction to Routing

Overview

Routing consists of creating an address for a webpage and opening such a webpage when a visitor clicks the link. The actual webpage is either generated from scratch or is incomplete because it depends on the link the user would click.

Practical LearningPractical Learning: Introducing Routing

  1. Start Microsoft Visual Studio
  2. On the main menu, click File -> New Project...
  3. In the New Project dialog box, make sure ASP.NET Web Application (.NET Framework) is selected in the middle list.
    Change the Name of the project to TrafficTicketsSystem2
  4. Click OK
  5. In the New ASP.NET Web Application, click the MVC icon and click OK
  6. In the Solution Explorer, right-click TrafficTicketsSystem1 -> Add -> New Folder
  7. Type Images and press Enter
  8. Save the following pictures to the Images folders:

    Traffic Tickets System

    Traffic Tickets System

    Traffic Tickets System

    Traffic Tickets System

  9. In the Solution Explorer, right-click Content -> Add -> Style Sheet
  10. Type TrafficTicketsSystem
  11. Click OK
  12. Create some styles as follows:
    body {
        background-color: #FCFBED;
    }
    
    footer                  { background-color: #2e0202;              }
    .bold                   { font-weight:      600;                  }
    .yellow                 { color:            yellow;               }
    .maroon                 { color:            maroon;               }
    .small-text             { width:            120px;                }
    .large-text             { width:            250px;                }
    .flat-text              { border:           1px solid #FCFBED;
                              background-color: #FCFBED;              }
    .push-down              { padding-top:      6.75em;               }
    .containment            { margin:           auto;
                              width:            400px;                }
    .large-content          { margin:           auto;
                              width:            600px;                }
    .box-title              { margin-left:      20px;
                              border-bottom:    1px dashed white;     }
    .bottom-title           { margin-left:      40px;
                              margin-top:       10px;
                              color:            #d9d758;
                              border-bottom:    1px dashed lightblue; }
    .bottom-title + ul      { list-style-type:  none;                 }
    .bottom-title + ul > li { margin-top:       5px;
                              margin-bottom:    5px;                  }
    .management             { background-color: rgb(145, 65, 15);     }
    .management > ul        { list-style-type:  none;                 }
    .management > ul > li   { margin-top:       5px;
                              margin-bottom:    5px;
                              margin-left:     -20px;                 }
    .manage-lead            { color:            antiquewhite;         }
    .manage-lead:link       { color:            orange;               }
    .manage-lead:focus      { color:            white;                }
    .manage-lead:hover      { color:            yellow;               }
    .bottom-lead            { color:            antiquewhite;         }
    .bottom-lead:link       { color:            orange;               }
    .bottom-lead:focus      { color:            white;                }
    .bottom-lead:hover      { color:            yellow;               }
    .bordered               { border:           1px solid #000;       }
    .navbar-fixed-top       { top:              6em;                  }
    .while-box              { margin:           3px;
                              background-color: white;
                              border-left:      1px solid #f1e9e9;
                              border-top:       1px solid #f1e9e9;
                              border-right:     2px solid silver;
                              border-bottom:    2px solid silver;     }
    .navbar-top-fixed       { position:         fixed;
                              right:            0;
                              left:             0;
                              z-index:          1030;                 }
    .navbar-top-fixed       { top:              0;
                              border-width:     0 0 1px;              }
    .navbar-inverse         { background-color: #000;                 }
    .navbar-brand           { font-size:        14px;                 }
    
    .col-md-20, .col-md-30, .col-md-60
                            { position:         relative;
                              min-height:       1px;
                              padding-right:    15px;
                              padding-left:     15px;                 }
    
    @media (min-width: 768px) {
        .navbar-top-fixed .navbar-collapse {
            padding-right: 0;
            padding-left: 0;
        }
    }
    .navbar-top-fixed .navbar-collapse {
        max-height: 340px;
    }
    @media (max-device-width: 480px) and (orientation: landscape) {
        .navbar-top-fixed .navbar-collapse {
            max-height: 200px;
        }
    }
    @media (min-width: 768px) {
        .navbar-top-fixed {
            border-radius: 0;
        }
    }
    
    @media (min-width: 992px) {
        .col-md-20, .col-md-30, .col-md-60 {
            float: left;
        }
    
        .col-md-20 { width: 20%; }
        .col-md-30 { width: 32%; }
        .col-md-60 { width: 60%; }
    }
    
    .common-font { font-family: Georgia, Garamond, 'Times New Roman', serif; }
  13. In the Solution Explorer, expand App_Start and double-click BundleConfig.cs
  14. Change the document as follows:
    using System.Web;
    using System.Web.Optimization;
    
    namespace TrafficTicketsSystem2
    {
        public class BundleConfig
        {
            // For more information on bundling, visit https://go.microsoft.com/fwlink/?LinkId=301862
            public static void RegisterBundles(BundleCollection bundles)
            {
                bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                            "~/Scripts/jquery-{version}.js"));
    
                bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
                            "~/Scripts/jquery.validate*"));
    
                // Use the development version of Modernizr to develop with and learn from. Then, when you're
                // ready for production, use the build tool at https://modernizr.com to pick only the tests you need.
                bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
                            "~/Scripts/modernizr-*"));
    
                bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
                          "~/Scripts/bootstrap.js",
                          "~/Scripts/respond.js"));
    
                bundles.Add(new StyleBundle("~/Content/css").Include(
                          "~/Content/bootstrap.css",
                          "~/Content/site.css",
                          "~/Content/TrafficTicketSystem.css"));
            }
        }
    }
  15. In the Solution Explorer, expand Views and expand Home
  16. Under Views and Home, double-click Index.cshtml
  17. Under Home, double-click Index.cshtml and change it as follows:
    @{
        ViewBag.Title = "Welcoome to TTS";
    }
    
    <div class="row">
        <div class="col-md-20">
            <div class="management">
                <br />
                <div class="box-title yellow">MANAGEMENT</div>
                <ul>
                    <li>@Html.ActionLink("Public Relations", "Index", "Home", htmlAttributes: new { @class = "manage-lead" })</li>
                    <li>@Html.ActionLink("Districts/Precincts", "Index", "Home", htmlAttributes: new { @class = "manage-lead" })</li>
                    <li>@Html.ActionLink("Crime Statistics", "Index", "Home", htmlAttributes: new { @class = "manage-lead" })</li>
                    <li>@Html.ActionLink("Neighborhood Watch", "Index", "Home", htmlAttributes: new { @class = "manage-lead" })</li>
                    <li>@Html.ActionLink("Social Calendar", "Index", "Home", htmlAttributes: new { @class = "manage-lead" })</li>
                    <li>@Html.ActionLink("Careers", "Index", "Home", htmlAttributes: new { @class = "manage-lead" })</li>
                    <li>@Html.ActionLink("Volunteers", "Index", "Home", htmlAttributes: new { @class = "manage-lead" })</li>
                    <li>@Html.ActionLink("Internal Affairs", "Index", "Home", htmlAttributes: new { @class = "manage-lead" })</li>
                    <li>@Html.ActionLink("Stress Management", "Index", "Home", htmlAttributes: new { @class = "manage-lead" })</li>
                    <li>@Html.ActionLink("Patrol Services", "Index", "Home", htmlAttributes: new { @class = "manage-lead" })</li>
                    <li>@Html.ActionLink("Field Services", "Index", "Home", htmlAttributes: new { @class = "manage-lead" })</li>
                    <li>@Html.ActionLink("Investigations", "Index", "Home", htmlAttributes: new { @class = "manage-lead" })</li>
                    <li>@Html.ActionLink("Communities", "Index", "Home", htmlAttributes: new { @class = "manage-lead" })</li>
                    <li>@Html.ActionLink("Forms & Fees", "Index", "Home", htmlAttributes: new { @class = "manage-lead" })</li>
                    <li>@Html.ActionLink("Press Releases", "Index", "Home", htmlAttributes: new { @class = "manage-lead" })</li>
                </ul>
                <hr />
            </div>
    
        </div>
        <div class="col-md-60">
            <div class="text-center">
                <img src="~/Images/tts3.png" class="bordered" />
            </div>
            <div>
                <p class="lead">The Solomon County Police Department is a division of the Solomon County government. This department is proud to insure the safety, security, and wellbeing of both our citizens and our visitors.</p>
    
                <div class="row">
                    <div class="col-md-30 while-box">
                        <h2>Government</h2>
                        <p>Citizens and visitors can get more information about the available services and duties.</p>
                    </div>
                    <div class="col-md-30 while-box">
                        <h2>Community</h2>
    
                        <p>Here you can find more information about public parks (recreatiional parks, etc).</p>
                    </div>
                    <div class="col-md-30 while-box">
                        <h2>Relations</h2>
                        <p>Here is information about our activities, how we operate, and our future projects.</p>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-md-20">
            <div class="management">
                <br />
                <div class="box-title yellow">USEFUL INFO</div>
                <ul>
                    <li>@Html.ActionLink("Questions/Help", "Index", "Home", htmlAttributes: new { @class = "manage-lead" })</li>
                    <li>@Html.ActionLink("News and Events", "Index", "Home", htmlAttributes: new { @class = "manage-lead" })</li>
                    <li>@Html.ActionLink("Safety Tips", "Index", "Home", htmlAttributes: new { @class = "manage-lead" })</li>
                    <li>@Html.ActionLink("Knowledge Base", "Index", "Home", htmlAttributes: new { @class = "manage-lead" })</li>
                    <li>@Html.ActionLink("Interships", "Index", "Home", htmlAttributes: new { @class = "manage-lead" })</li>
                </ul>
                <br />
            </div>
            <div>
                <br />
                <img src="~/Images/tts4.png" />
                <br />
            </div>
        </div>
    </div>
    
    <br />
  18. In the Solution Explorer, under Views, expand Shared and double-click _Layout.cshtml
  19. Type the following code:
    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Traffic Tickets System :: @ViewBag.Title</title>
        @Styles.Render("~/Content/css")
        @Scripts.Render("~/bundles/modernizr")
    </head>
    <body>
        <div class="navbar-top-fixed">
            <div class="row">
                <div class="col-md-3" style="background-color: rgb(133, 17, 0); height: 6.15em"></div>
                <div class="col-md-6" style="background-image: url(/Images/tts1.png); height: 6.15em"></div>
                <div class="col-md-3" style="background-image: url(/Images/tts2.png); height: 6.15em"></div>
            </div>
        </div>
    
        <div class="navbar navbar-inverse navbar-fixed-top">
            <div class="container">
                <div class="navbar-header">
                    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                    </button>
                    @Html.ActionLink("TRAFFIC TICKETS SYSTEM", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
                </div>
                <div class="navbar-collapse collapse">
                    <ul class="nav navbar-nav">
                        <li>@Html.ActionLink("CAMERAS", "Index", "Cameras")</li>
                        <li>@Html.ActionLink("DRIVERS", "Index", "Drivers")</li>
                        <li>@Html.ActionLink("VEHICLES", "Index", "Vehicles")</li>
                        <li>@Html.ActionLink("VIOLATIONS TYPES", "Index", "ViolationsTypes")</li>
                        <li>@Html.ActionLink("TRAFFIC VIOLATIONS", "Index", "TrafficViolations")</li>
                        <li>@Html.ActionLink("ABOUT US", "About", "Home")</li>
                        <li>@Html.ActionLink("CONTACT TTS", "Contact", "Home")</li>
                    </ul>
                </div>
            </div>
        </div>
        <div class="container body-content push-down">
            @RenderBody()
    
            <footer>
                <div class="row">
                    <div class="col-md-3">
                        <div class="bottom-title">LOCAL GOVERNMENTS</div>
                        <ul>
                            <li>@Html.ActionLink("Chesterworth County", "Index", "Home", htmlAttributes: new { @class = "bottom-lead" })</li>
                            <li>@Html.ActionLink("Ramses County", "Index", "Home", htmlAttributes: new { @class = "bottom-lead" })</li>
                            <li>@Html.ActionLink("Peyton County", "Index", "Home", htmlAttributes: new { @class = "bottom-lead" })</li>
                            <li>@Html.ActionLink("Clarendon County", "Index", "Home", htmlAttributes: new { @class = "bottom-lead" })</li>
                        </ul>
                    </div>
                    <div class="col-md-3">
                        <div class="bottom-title">CITY HALL</div>
                        <ul>
                            <li>@Html.ActionLink("Office of the Mayor", "Index", "Home", htmlAttributes: new { @class = "bottom-lead" })</li>
                            <li>@Html.ActionLink("Human Resources", "Index", "Home", htmlAttributes: new { @class = "bottom-lead" })</li>
                            <li>@Html.ActionLink("County Executive", "Index", "Home", htmlAttributes: new { @class = "bottom-lead" })</li>
                            <li>@Html.ActionLink("State Governor", "Index", "Home", htmlAttributes: new { @class = "bottom-lead" })</li>
                        </ul>
                    </div>
                    <div class="col-md-3">
                        <div class="bottom-title">PUBLIC SERVICES</div>
                        <ul>
                            <li>@Html.ActionLink("Laymans Library", "Index", "Home", htmlAttributes: new { @class = "bottom-lead" })</li>
                            <li>@Html.ActionLink("Entertainment", "Index", "Home", htmlAttributes: new { @class = "bottom-lead" })</li>
                            <li>@Html.ActionLink("Weekend Programs", "Index", "Home", htmlAttributes: new { @class = "bottom-lead" })</li>
                            <li>@Html.ActionLink("Kids/Teens Info", "Index", "Home", htmlAttributes: new { @class = "bottom-lead" })</li>
                        </ul>
                    </div>
                    <div class="col-md-3">
                        <div class="bottom-title">MISCELLANEOUS</div>
                        <ul>
                            <li>@Html.ActionLink("Labor/Regulations", "Index", "Home", htmlAttributes: new { @class = "bottom-lead" })</li>
                            <li>@Html.ActionLink("Taxes Information", "Index", "Home", htmlAttributes: new { @class = "bottom-lead" })</li>
                            <li>@Html.ActionLink("Seasonals/Weather", "Index", "Home", htmlAttributes: new { @class = "bottom-lead" })</li>
                            <li>@Html.ActionLink("Education", "Index", "Home", htmlAttributes: new { @class = "bottom-lead" })</li>
                        </ul>
                    </div>
                </div>
                <hr />
                <p class="text-center common-font yellow">&copy; @DateTime.Now.Year - Traffic Tickets System</p>
    
            </footer>
        </div>
    
        @Scripts.Render("~/bundles/jquery")
        @Scripts.Render("~/bundles/bootstrap")
        @RenderSection("scripts", required: false)
    </body>
    </html>
  20. To preview the result, press Ctrl + F5:

    Linked Lists - Traffic Tickets Management

  21. Close the browser and return to your programming environment
  22. In the Solution Explorer, right-click Models -> Add -> Class...
  23. Type Camera
  24. Click Add
  25. Change the document as follows:
    using System;
    using System.ComponentModel.DataAnnotations;
    
    namespace TrafficTicketsSystem2.Models
    {
        [Serializable]
        public class Camera
        {
            [Display(Name = "Camera #")]
            public string CameraNumber { get; set; }
            public string Make         { get; set; }
            public string Model        { get; set; }
            public string Location     { get; set; }
        }
    }

A Route Collection

To support routing, the .NET Framework provides a class named RouteCollection. This class is derived from the Collection<T> class of the System.Collections.ObjectModel namespace:

public class RouteCollection : Collection<RouteBase>

The RouteCollection class is defined in a namespace named System.Web.Routing. As its name indicates, RouteCollection is a collection class used to create and manage a list of items. The class is equipped with all types of properties and methods to add and manage its values.

Besides its members, the RouteCollection class is expanded with many extended methods. For example, to let you specify a routing scheme, the RouteCollection class is equipped with an overloaded method named MapRoute. One of its versions uses the following syntax:

public static Route MapRoute(this RouteCollection routes,
						     string name,
						     string url,
						     object defaults)

The first argument is the name of the route. This name can be anything you want. Here is an example:

using System.Web.Mvc;
using System.Web.Routing;

namespace Exercise1
{
    public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.MapRoute("Detailed Report", . . .);
        }
    }
}

The second argument is a string that uses a special expression made of different sections separated by forward slashes / as in something1/something2/something_n. Each section contains a special word included in curly brackets, as in {something1}/{something2}/{something_n}.

A routing pattern is primarily controlled inside a controller class, or rather by the members of a class. For this reason, the first word of a routing pattern is controller. Here is an example:

using System.Web.Mvc;
using System.Web.Routing;

namespace Exercise1
{
    public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.MapRoute("Detailed Report", "{controller}/...");
        }
    }
}

Introducing Route Patterns

An Identity for a Routing Pattern

A Web Route is specified using a formula that follows some rules. This is the role of the url argument of the RouteCollection.MapRoute() method. The argument is a string that contains a scheme, called a URL pattern, that resembles the path or address of a webpage. The formula it follows is:

{controller}/{action}/{id}

As you can see, this string uses a few placeholders. The most-left placeholder specifies that a path starts with a controller. Here is an example:

using System.Web.Mvc;

namespace ASPNETMVCRouting1.Controllers
{
    public class ViolationsController : Controller
    {
    }
}

The url argument indicates that the controller is followed by the name of an action method. This means that you must create such a controller. By tradtion, that method is named Details. Here is an example:

using System.Web.Mvc;

namespace ASPNETMVCRouting1.Controllers
{
    public class ViolationsController : Controller
    {
        public ActionResult Details()
        {
            return View();
        }
    }
}

The address of a route ends with a value that can be used to select a webpage or a value to display. This can be a value that uniquely idenfies a page or a record. For this reason, when creating a class for a group of records, such as a class for employees, you should create a special property that will hold unique values; that is, for every variable of the class, the value of this property will be different from the value of the same property for another variable of the same class. By convension (and/or to make things easier):

The values of this property don't mean anything significant except their roles of being unique among themselves. In formal databases, database applications are equipped to automatically specify the value of this property. In a text-based collection application such as those we create in these lessons, it is your responsibility to find a way to provide a (usually an incrementing) value for the property.

Practical LearningPractical Learning: Adding Routing Properties

  1. Change the Camera class as follows:
    using System;
    using System.ComponentModel.DataAnnotations;
    
    namespace TrafficTicketsSystem2.Models
    {
        [Serializable]
        public class Camera
        {
            [Display(Name = "Camera Id")]
            public int    CameraId     { get; set; }
            [Display(Name = "Camera #")]
            public string CameraNumber { get; set; }
            public string Make         { get; set; }
            public string Model        { get; set; }
            public string Location     { get; set; }
    
    		  // We need to override the Equals() method so we can compare one object to another for equality
            public override bool Equals(object obj)
            {
                if( obj is Camera )
                {
                    Camera cmr = (Camera)obj;
    
                    if (cmr.CameraId == CameraId)
                        return true;
                }
    
                return false;
            }
            
            public override int GetHashCode()
            {
                return CameraId;
            }
        }
    }
  2. In the Solution Explorer, right-click Models -> Add -> Class...
  3. Type Driver
  4. Click Add
  5. Change the document as follows:
    using System;
    using System.ComponentModel.DataAnnotations;
    
    namespace TrafficTicketsSystem2.Models
    {
        [Serializable]
        public class Driver
        {
            [Display(Name = "Driver Id")]
            public int DriverId { get; set; }
            [Display(Name = "Drv. Lic. #")]
            public string DrvLicNumber { get; set; }
            [Display(Name = "First Name")]
            public string FirstName    { get; set; }
            [Display(Name = "Last Name")]
            public string LastName     { get; set; }
            public string Address      { get; set; }
            public string City         { get; set; }
            public string County       { get; set; }
            public string State        { get; set; }
            [Display(Name = "ZIP Code")]
            public string ZIPCode      { get; set; }
    
            public override bool Equals(object obj)
            {
                Driver dvr = (Driver)obj;
    
                return dvr.DriverId == DriverId ? true : false;
            }
    
            public override int GetHashCode()
            {
                return DriverId;
            }
        }
    }
  6. In the Solution Explorer, right-click Models -> Add -> Class...
  7. Type Vehicle
  8. Click Add
  9. Change the document as follows:
    using System;
    using System.ComponentModel.DataAnnotations;
    
    namespace TrafficTicketsSystem2.Models
    {
        [Serializable]
        public class Vehicle
        {
            [Display(Name = "Vehicle Id")]
            public int VehicleId { get; set; }
            [Display(Name = "Tag #")]
            public string TagNumber { get; set; }
            [Display(Name = "Driver Id")]
            public int DriverId { get; set; }
            public string Make { get; set; }
            public string Model { get; set; }
            [Display(Name = "Vehicle Year")]
            public string VehicleYear { get; set; }
            public string Color { get; set; }
    
            public override bool Equals(object obj)
            {
                if (obj is Vehicle)
                {
                    Vehicle car = (Vehicle)obj;
    
                    if (car.VehicleId == VehicleId)
                        return true;
                }
    
                return false;
            }
    
            public override int GetHashCode()
            {
                return VehicleId;
            }
        }
    }
  10. In the Solution Explorer, right-click Models -> Add -> Class...
  11. Type ViolationType as the name of the class
  12. Click Add
  13. Change the class as follows:
    using System;
    using System.ComponentModel.DataAnnotations;
    
    namespace TrafficTicketsSystem2.Models
    {
        [Serializable]
        public class ViolationType
        {
            [Display(Name = "Violation Type Id")]
            public int    ViolationTypeId { get; set; }
            [Display(Name = "Violation Name")]
            public string ViolationName { get; set; }
            public string Description { get; set; }
    
            public override bool Equals(object obj)
            {
                ViolationType vt = (ViolationType)obj;
    
                return vt.ViolationTypeId == ViolationTypeId ? true : false;
            }
    
            public override int GetHashCode()
            {
                return ViolationTypeId;
            }
        }
    }
  14. In the Solution Explorer, right-click Models -> Add -> Class...
  15. Type TrafficViolation
  16. Click Add
  17. Change the document as follows:
    using System;
    using System.ComponentModel.DataAnnotations;
    
    namespace TrafficTicketSystem2.Models
    {
        [Serializable]
        public class TrafficViolation
        {
            [Display(Name = "Violation Id")]
            public int TrafficViolationId { get; set; }
            [Display(Name = "Traffic Violation #")]
            public int TrafficViolationNumber { get; set; }
            [Display(Name = "Camera #")]
            public int    CameraId     { get; set; }
            [Display(Name = "Vehicle Id")]
            public int VehicleId { get; set; }
            [Display(Name = "Violation Id")]
            public int    ViolationTypeId { get; set; }
            [Display(Name = "Violation Date")]
            public string ViolationDate { get; set; }
            [Display(Name = "Violation Time")]
            public string ViolationTime { get; set; }
            [Display(Name = "Photo Available")]
            public string PhotoAvailable { get; set; }
            [Display(Name = "Video Available")]
            public string VideoAvailable { get; set; }
            [Display(Name = "Payment Due Date")]
            public string PaymentDueDate { get; set; }
            [Display(Name = "Payment Date")]
            public string PaymentDate { get; set; }
            [Display(Name = "Payment Amount")]
            public double PaymentAmount { get; set; }
            [Display(Name = "Payment Status")]
            public string PaymentStatus { get; set; }
    
            public override bool Equals(object obj)
            {
                TrafficViolation tv = (TrafficViolation)obj;
    
                return tv.TrafficViolationId == TrafficViolationId ? true : false;
            }
    
            public override int GetHashCode()
            {
                return TrafficViolationId;
            }
        }
    }
  18. In the Solution Explorer, right-click Controllers -> Add -> Controller...
  19. In the middle frame of the Add Scaffold dialog box, click MVC 5 Controller With Read/Write Actions
  20. Click Add
  21. Type Cameras to get CamerasController
  22. Click Add
  23. Change the class as follows:
    using System.IO;
    using System.Web.Mvc;
    using System.Collections.Generic;
    using TrafficTicketSystem2.Models;
    using System.Runtime.Serialization.Formatters.Binary;
    
    namespace TrafficTicketSystem2.Controllers
    {
        public class CamerasController : Controller
        {
            // GET: Cameras
            public ActionResult Index()
            {
                FileStream fsCameras = null;
                List<Camera> cameras = new List<Camera>();
                BinaryFormatter bfCameras = new BinaryFormatter();
                string strCamerasFile = Server.MapPath("~/App_Data/Cameras.tts");
    
                // If a file for Cameras records was proviously created, open it
                if (System.IO.File.Exists(strCamerasFile))
                {
                    using (fsCameras = new FileStream(strCamerasFile, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        /* After opening the file, get the list of cameras from it
                         * and store in the declared List<> variable. */
                        cameras = (List<Camera>)bfCameras.Deserialize(fsCameras);
                    }
                }
    
                // Return the list of cameras so they can be accessed in the view
                return View(cameras);
            }
    
            // GET: Cameras/Details/5
            public ActionResult Details(int id)
            {
                return View();
            }
    
            // GET: Cameras/Create
            public ActionResult Create()
            {
                return View();
            }
    
            // POST: Cameras/Create
            [HttpPost]
            public ActionResult Create(FormCollection collection)
            {
                try
                {
                    // TODO: Add insert logic here
                    int cmrID = 0;
                    FileStream fsCameras = null;
                    List<Camera> cameras = new List<Camera>();
                    BinaryFormatter bfCameras = new BinaryFormatter();
                    string strCamerasFile = Server.MapPath("~/App_Data/Cameras.tts");
    
                    if (!string.IsNullOrEmpty("CameraNumber"))
                    {
                        if (System.IO.File.Exists(strCamerasFile))
                        {
                            using (fsCameras = new FileStream(strCamerasFile, FileMode.Open, FileAccess.Read, FileShare.Read))
                            {
                                cameras = (List<Camera>)bfCameras.Deserialize(fsCameras);
    
                                foreach(Camera cmr in cameras)
                                {
                                    cmrID = cmr.CameraId;
                                }
                            }
                        }
    
                        cmrID++;
    
                        Camera viewer = new Camera()
                        {
                            CameraId = cmrID,
                            CameraNumber = collection["CameraNumber"],
                            Make = collection["Make"],
                            Model = collection["Model"],
                            Location = collection["Location"]
                        };
    
                        cameras.Add(viewer);
    
                        using (fsCameras = new FileStream(strCamerasFile, FileMode.Create, FileAccess.Write, FileShare.Write))
                        {
                            bfCameras.Serialize(fsCameras, cameras);
                        }
                    }
    
                    return RedirectToAction("Index");
                }
                catch
                {
                    return View();
                }
            }
    
            . . . No Change
        }
    }
  24. In the document, right-click inside one of the Create() methods and click Add View...
  25. Make sure the View Name text box is displaying Create.
    Click Add
  26. Create a form as follows:
    @model TrafficTicketsSystem2.Models.Camera
    
    @{
        ViewBag.Title = "Create Camera";
    }
    
    <h2 class="common-font text-center bold maroon">Create Camera</h2>
    
    <hr />
    
    @using (Html.BeginForm())
    {
        @Html.AntiForgeryToken()
    
        <div class="containment">
            <div class="form-horizontal common-font">
                @Html.ValidationSummary(true, "", new { @class = "text-danger" })
                <div class="form-group">
                    @Html.LabelFor(model => model.CameraNumber, htmlAttributes: new { @class = "control-label col-md-5 maroon" })
                    <div class="col-md-7">
                        @Html.EditorFor(model => model.CameraNumber, new { htmlAttributes = new { @class = "form-control" } })
                        @Html.ValidationMessageFor(model => model.CameraNumber, "", new { @class = "text-danger" })
                    </div>
                </div>
    
                <div class="form-group">
                    @Html.LabelFor(model => model.Make, htmlAttributes: new { @class = "control-label col-md-5 maroon" })
                    <div class="col-md-7">
                        @Html.EditorFor(model => model.Make, new { htmlAttributes = new { @class = "form-control" } })
                        @Html.ValidationMessageFor(model => model.Make, "", new { @class = "text-danger" })
                    </div>
                </div>
    
                <div class="form-group">
                    @Html.LabelFor(model => model.Model, htmlAttributes: new { @class = "control-label col-md-5 maroon" })
                    <div class="col-md-7">
                        @Html.EditorFor(model => model.Model, new { htmlAttributes = new { @class = "form-control" } })
                        @Html.ValidationMessageFor(model => model.Model, "", new { @class = "text-danger" })
                    </div>
                </div>
    
                <div class="form-group">
                    @Html.LabelFor(model => model.Location, htmlAttributes: new { @class = "control-label col-md-5 maroon" })
                    <div class="col-md-7">
                        @Html.EditorFor(model => model.Location, new { htmlAttributes = new { @class = "form-control" } })
                        @Html.ValidationMessageFor(model => model.Location, "", new { @class = "text-danger" })
                    </div>
                </div>
    
                <div class="form-group">
                    <label class="control-label col-md-6">
                        @Html.ActionLink("Traffic Cameras", "Index")
                    </label>
                    <div class="col-md-6">
                        <input type="submit" value="Save Camera Information" class="btn btn-warning" />
                    </div>
                </div>
            </div>
        </div>
    }
  27. Click the CamerasController.cs tab

A Link for a Route

As you may know already from your studying ASP.NET MVC modelling, in a webpage, in the code of a view, you can access the record(s) by creating an @model expression that calls either the class from the Models folder or getting the records from its related IEnumerable<> collection.

To lead the users to a view that can show a record, you can create a link from a webpage that displays a list of records, which the view of the Index method of a controller. To start, when the user accesses the records, each record displays on its own row. Remember that each record should (must) have a value that uniquely identifies it. you can create a link so that, when the user positions the mouse on it, the unique value would be selected. You can then create a link on that value. To let you do this, the HtmlHelper class is extended with various versions of the ActionLink() method. One of the versions uses the following syntax:

public static MvcHtmlString ActionLink(this HtmlHelper htmlHelper,
                                       string linkText,
                                       string actionName,
                                       object routeValues);

The first argument, linkText, is the text of the link. The second argument, actionName, is the name of the action method from a controller class. The new argument, routeValues, is of type object and represents the route. The argument is passed as an anonymous object: new {}. In the curly brackets, assign the unique record value to the argument passed to the action method.

Practical LearningPractical Learning: Creating a Link through a Route

  1. In the CamerasController class, right-click Index() and click Add View...
  2. In the Add View dialog box, make sure the View Name text box is displaying Index. Click Add
  3. Create the webpage as follows:
    @model IEnumerable<TrafficTicketsSystem2.Models.Camera>
    
    @{
        ViewBag.Title = "Cameras - Traffic Monitors";
    }
    
    <h2 class="bold maroon common-font text-center">Cameras - Traffic Monitors</h2>
    
    <table class="table table-striped common-font">
        <tr>
            <th class="text-center maroon">@Html.DisplayNameFor(model => model.CameraId)</th>
            <th class="text-center maroon">@Html.DisplayNameFor(model => model.CameraNumber)</th>
            <th class="maroon">@Html.DisplayNameFor(model => model.Make)</th>
            <th class="maroon">@Html.DisplayNameFor(model => model.Model)</th>
            <th class="maroon">@Html.DisplayNameFor(model => model.Location)</th>
            <th class="maroon">@Html.ActionLink("Create New Camera", "Create")</th>
        </tr>
    
        @foreach (var item in Model)
        {
            <tr>
                <td class="text-center">@Html.DisplayFor(modelItem => item.CameraId)</td>
                <td class="text-center">@Html.DisplayFor(modelItem => item.CameraNumber)</td>
                <td>@Html.DisplayFor(modelItem => item.Make)</td>
                <td>@Html.DisplayFor(modelItem => item.Model)</td>
                <td>@Html.DisplayFor(modelItem => item.Location)</td>
                <td>
                    @Html.ActionLink("Edit", "Edit", new { id = item.CameraId }) |
                    @Html.ActionLink("Details", "Details", new { id = item.CameraId }) |
                    @Html.ActionLink("Delete", "Delete", new { id = item.CameraId })
                </td>
            </tr>
        }
    </table>
  4. To execute the project, on the main menu, click Debug -> Start Without Debugging
  5. Click Create New Camera:

    Label

  6. Create a few records as follows:

    Camera # Make Model Location
    DGH-38460 Ashton Digital MPH-6000 Eastern Ave and Ashburry Drv
    ELQ-79284 Seaside International BL5 Monroe Str and Westview Rd
    MSR-59575 Ashton Digital MPH-6000 Concordia Blvd and Sunset Way
    DHT-29417 Woodson and Sons NG200 Temple Ave and Barclay Rd
    AHR-41518 Seaside International 442i Chesterwood Rd and Old Dutler Str
    HTR-93847 Ashton Digital 366d Monrovia Str at Moon Springs

    Label

  7. Close the browser and return to your programming environment
  8. Click the CamerasController.cs tab

Detailing a Routing Pattern

To use the unique value of a record, which is the value of the property that was created to hold unique values, in your controller class, you should create a method, usually named Details. Pass an integral parameter to it. As you will use an action method to access the unique value of a record, the second section of the second argument to the RouteCollection.MapRoute() uses action as its name. Here is an example:

using System.Web.Mvc;
using System.Web.Routing;

namespace Exercise1
{
    public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.MapRoute("Detailed Report", "{controller}/{action}/", . . .);
        }
    }
}

To make matters easier, the parameter is usually named id. To indicate that this parameter will hold the value for a route, the third part of the url argument of the RouteCollection.MapRoute() method uses the id name. Here is an example:

using System.Web.Mvc;
using System.Web.Routing;

namespace Exercise1
{
    public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.MapRoute("Detailed Report", "{controller}/{action}/{id}", . . .);
        }
    }
}

You must anticipate that, at times, the value of this parameter will not be provided, for any reason. Therefore, the method must be able to handle null values. For this reason, the argument must be passed as a possible null. If you are passing it as a primitive type such as an integer, add a question mark to it. Here is an example:

using System.Web.Mvc;

namespace ASPNETMVCRouting1.Controllers
{
    public class ViolationsController : Controller
    {
        // GET: Violations/Details/1
        public ActionResult Details(int? id)
        {
            return View();
        }
    }
}

Practical LearningPractical Learning: Detailing a Routing Pattern

  1. In the CamerasController class, change the Details() method as follows:
    using System.IO;
    using System.Net;
    using System.Web.Mvc;
    using System.Collections.Generic;
    using TrafficTicketsSystem2.Models;
    using System.Runtime.Serialization.Formatters.Binary;
    
    namespace TrafficTicketsSystem2.Controllers
    {
        public class CamerasController : Controller
        {
            . . . No Change
    
            // GET: Cameras/Details/5
            public ActionResult Details(int? id)
            {
                Camera viewer = null;
                FileStream fsCameras = null;
                List<Camera> cameras = new List<Camera>();
                BinaryFormatter bfCameras = new BinaryFormatter();
                string strCamerasFile = Server.MapPath("~/App_Data/Cameras.tts");
    
                if (id == 0)
                {
                    return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
                }
    
                if (System.IO.File.Exists(strCamerasFile))
                {
                    using (fsCameras = new FileStream(strCamerasFile, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        cameras = (List<Camera>)bfCameras.Deserialize(fsCameras);
                    }
    
                    viewer = cameras.Find(cmr => cmr.CameraId == id);
                }
    
                if (viewer == null)
                {
                    return HttpNotFound();
                }
    
                return View(viewer);
            }
            
            . . . No Change
        }
    }
  2. In the class, right-click inside the Details() method-> Add View...
  3. In the Add View dialog box, make sure the View Name text box is displaying Details. Click Add
  4. Create the webpage as follows:
    @model TrafficTicketsSystem2.Models.Camera
    
    @{
        ViewBag.Title = "Camera Details";
    }
    
    <h2 class="common-font bold maroon text-center">Camera Details</h2>
    
    <hr />
    
    <div class="containment">
        <dl class="dl-horizontal common-font">
            <dt class="maroon">@Html.DisplayNameFor(model => model.CameraId)</dt>
            <dd>@Html.DisplayFor(model => model.CameraId)</dd>
    
            <dt class="maroon">@Html.DisplayNameFor(model => model.CameraNumber)</dt>
            <dd>@Html.DisplayFor(model => model.CameraNumber)</dd>
    
            <dt class="maroon">@Html.DisplayNameFor(model => model.Make)</dt>
            <dd>@Html.DisplayFor(model => model.Make)</dd>
    
            <dt class="maroon">@Html.DisplayNameFor(model => model.Model)</dt>
            <dd>@Html.DisplayFor(model => model.Model)</dd>
    
            <dt class="maroon">@Html.DisplayNameFor(model => model.Location)</dt>
            <dd>@Html.DisplayFor(model => model.Location)</dd>
        </dl>
    </div>
    
    <p class="text-center">
        @Html.ActionLink("Edit", "Edit", new { id = Model.CameraId }) |
        @Html.ActionLink("Cameras - Traffic Monitors", "Index")
    </p>
  5. To execute the project, on the main menu, click Debug -> Start Without Debugging (the webpage will display an error)
  6. In the address bar, click on the right side of the address, type /3

    Route Patterns

  7. Press Enter

    Route Patterns

  8. Close the browser and return to your programming environment
  9. Click the CamerasController.cs tab and complete its class as follows:
    using System.IO;
    using System.Net;
    using System.Web.Mvc;
    using System.Collections.Generic;
    using TrafficTicketsSystem2.Models;
    using System.Runtime.Serialization.Formatters.Binary;
    
    namespace TrafficTicketsSystem2.Controllers
    {
        public class CamerasController : Controller
        {
            // GET: Cameras
            public ActionResult Index()
            {
                FileStream fsCameras = null;
                List<Camera> cameras = new List<Camera>();
                BinaryFormatter bfCameras = new BinaryFormatter();
                string strCamerasFile = Server.MapPath("~/App_Data/Cameras.tts");
    
                // If a file for Cameras records was proviously created, ...
                if (System.IO.File.Exists(strCamerasFile))
                {
                    // ... open it
                    using (fsCameras = new FileStream(strCamerasFile, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        /* After opening the file, get the list of cameras from it
                         * and store in the declared List<> variable. */
                        cameras = (List<Camera>)bfCameras.Deserialize(fsCameras);
                    }
                }
    
                // Return the list of cameras so they can be accessed in the view
                return View(cameras);
            }
    
            // GET: Cameras/Details/5
            public ActionResult Details(int? id)
            {
                Camera viewer = null;
                FileStream fsCameras = null;
                List<Camera> cameras = new List<Camera>();
                BinaryFormatter bfCameras = new BinaryFormatter();
                string strCamerasFile = Server.MapPath("~/App_Data/Cameras.tts");
    
                if (id == 0)
                {
                    return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
                }
    
                if (System.IO.File.Exists(strCamerasFile))
                {
                    using (fsCameras = new FileStream(strCamerasFile, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        cameras = (List<Camera>)bfCameras.Deserialize(fsCameras);
                    }
    
                    viewer = cameras.Find(cmr => cmr.CameraId == id);
                }
    
                if (viewer == null)
                {
                    return HttpNotFound();
                }
    
                return View(viewer);
            }
    
            // GET: Cameras/Create
            public ActionResult Create()
            {
                return View();
            }
    
            // POST: Cameras/Create
            [HttpPost]
            public ActionResult Create(FormCollection collection)
            {
                try
                {
                    // TODO: Add insert logic here
                    int cmrId = 0;
                    FileStream fsCameras = null;
                    List<Camera> cameras = new List<Camera>();
                    BinaryFormatter bfCameras = new BinaryFormatter();
                    string strCamerasFile = Server.MapPath("~/App_Data/Cameras.tts");
    
                    if (!string.IsNullOrEmpty("CameraNumber"))
                    {
                        if (System.IO.File.Exists(strCamerasFile))
                        {
                            using (fsCameras = new FileStream(strCamerasFile, FileMode.Open, FileAccess.Read, FileShare.Read))
                            {
                                cameras = (List<Camera>)bfCameras.Deserialize(fsCameras);
    
                                foreach (Camera cmr in cameras)
                                {
                                    cmrId = cmr.CameraId;
                                }
                            }
                        }
    
                        cmrId++;
    
                        Camera viewer = new Camera()
                        {
                            CameraId = cmrId,
                            CameraNumber = collection["CameraNumber"],
                            Make = collection["Make"],
                            Model = collection["Model"],
                            Location = collection["Location"]
                        };
    
                        cameras.Add(viewer);
    
                        using (fsCameras = new FileStream(strCamerasFile, FileMode.Create, FileAccess.Write, FileShare.Write))
                        {
                            bfCameras.Serialize(fsCameras, cameras);
                        }
                    }
    
                    return RedirectToAction("Index");
                }
                catch
                {
                    return View();
                }
            }
    
            // GET: Cameras/Edit/5
            public ActionResult Edit(int? id)
            {
                Camera viewer = null;
                FileStream fsCameras = null;
                List<Camera> cameras = new List<Camera>();
                BinaryFormatter bfCameras = new BinaryFormatter();
                string strCamerasFile = Server.MapPath("~/App_Data/Cameras.tts");
    
                if (id == 0)
                {
                    return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
                }
    
                if (System.IO.File.Exists(strCamerasFile))
                {
                    using (fsCameras = new FileStream(strCamerasFile, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        cameras = (List<Camera>)bfCameras.Deserialize(fsCameras);
                    }
    
                    viewer = cameras.Find(cmr => cmr.CameraId == id);
                }
    
                if (viewer == null)
                {
                    return HttpNotFound();
                }
    
                return View(viewer);
            }
    
            // POST: Cameras/Edit/5
            [HttpPost]
            public ActionResult Edit(int id, FormCollection collection)
            {
                try
                {
                    // TODO: Add update logic here
                    FileStream fsCameras = null;
                    List<Camera> cameras = new List<Camera>();
                    BinaryFormatter bfCameras = new BinaryFormatter();
                    string strCamerasFile = Server.MapPath("~/App_Data/Cameras.tts");
    
                    if (!string.IsNullOrEmpty("CameraNumber"))
                    {
                        if (System.IO.File.Exists(strCamerasFile))
                        {
                            using (fsCameras = new FileStream(strCamerasFile, FileMode.Open, FileAccess.Read, FileShare.Read))
                            {
                                cameras = (List<Camera>)bfCameras.Deserialize(fsCameras);
                            }
    
                            Camera camera = cameras.Find(cmr => cmr.CameraId == id);
    
                            camera.Make = collection["Make"];
                            camera.Model = collection["Model"];
                            camera.Location = collection["Location"];
    
                            using (fsCameras = new FileStream(strCamerasFile, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite))
                            {
                                bfCameras.Serialize(fsCameras, cameras);
                            }
                        }
                    }
    
                    return RedirectToAction("Index");
                }
                catch
                {
                    return View();
                }
            }
    
            // GET: Cameras/Delete/5
            public ActionResult Delete(int id)
            {
                Camera viewer = null;
                FileStream fsCameras = null;
                List<Camera> cameras = new List<Camera>();
                BinaryFormatter bfCameras = new BinaryFormatter();
                string strCamerasFile = Server.MapPath("~/App_Data/Cameras.tts");
    
                if (id == 0)
                {
                    return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
                }
    
                if (System.IO.File.Exists(strCamerasFile))
                {
                    using (fsCameras = new FileStream(strCamerasFile, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        cameras = (List<Camera>)bfCameras.Deserialize(fsCameras);
                    }
    
                    viewer = cameras.Find(cmr => cmr.CameraId == id);
                }
    
                if (viewer == null)
                {
                    return HttpNotFound();
                }
    
                return View(viewer);
            }
    
            // POST: Cameras/Delete/5
            [HttpPost]
            public ActionResult Delete(int id, FormCollection collection)
            {
                try
                {
                    // TODO: Add delete logic here
                    FileStream fsCameras = null;
                    List<Camera> cameras = new List<Camera>();
                    BinaryFormatter bfCameras = new BinaryFormatter();
                    string strCamerasFile = Server.MapPath("~/App_Data/Cameras.tts");
    
                    if (!string.IsNullOrEmpty("CameraNumber"))
                    {
                        if (System.IO.File.Exists(strCamerasFile))
                        {
                            using (fsCameras = new FileStream(strCamerasFile, FileMode.Open, FileAccess.Read, FileShare.Read))
                            {
                                cameras = (List<Camera>)bfCameras.Deserialize(fsCameras);
                            }
    
                            Camera camera = cameras.Find(cmr => cmr.CameraId == id);
    
                            cameras.Remove(camera);
    
                            using (fsCameras = new FileStream(strCamerasFile, FileMode.Create, FileAccess.Write, FileShare.Write))
                            {
                                bfCameras.Serialize(fsCameras, cameras);
                            }
                        }
                    }
    
                    return RedirectToAction("Index");
                }
                catch
                {
                    return View();
                }
            }
        }
    }
  10. In the CamerasController class, right-click inside one of the Edit() methods and click Add View...
  11. Make sure the View Name is displaying Edit. Click Add
  12. Create the form as follows:
    @model TrafficTicketsSystem2.Models.Camera
    
    @{
        ViewBag.Title = "Edit/Update Camera Details";
    }
    
    <h2 class="maroon common-font text-center bold">Edit/Change Camera Setup</h2>
    
    <hr />
    
    @using (Html.BeginForm())
    {
        @Html.AntiForgeryToken()
    
        <div class="containment">
            <div class="form-horizontal common-font">
                @Html.ValidationSummary(true, "", new { @class = "text-danger" })
                @Html.HiddenFor(model => model.CameraId)
    
                <div class="form-group">
                    @Html.LabelFor(model => model.CameraNumber, htmlAttributes: new { @class = "control-label col-md-5 maroon" })
                    <div class="col-md-7">
                        @Html.EditorFor(model => model.CameraNumber, new { htmlAttributes = new { @class = "form-control" } })
                        @Html.ValidationMessageFor(model => model.CameraNumber, "", new { @class = "text-danger" })
                    </div>
                </div>
    
                <div class="form-group">
                    @Html.LabelFor(model => model.Make, htmlAttributes: new { @class = "control-label col-md-5 maroon" })
                    <div class="col-md-7">
                        @Html.EditorFor(model => model.Make, new { htmlAttributes = new { @class = "form-control" } })
                        @Html.ValidationMessageFor(model => model.Make, "", new { @class = "text-danger" })
                    </div>
                </div>
    
                <div class="form-group">
                    @Html.LabelFor(model => model.Model, htmlAttributes: new { @class = "control-label col-md-5 maroon" })
                    <div class="col-md-7">
                        @Html.EditorFor(model => model.Model, new { htmlAttributes = new { @class = "form-control" } })
                        @Html.ValidationMessageFor(model => model.Model, "", new { @class = "text-danger" })
                    </div>
                </div>
    
                <div class="form-group">
                    @Html.LabelFor(model => model.Location, htmlAttributes: new { @class = "control-label col-md-5 maroon" })
                    <div class="col-md-7">
                        @Html.EditorFor(model => model.Location, new { htmlAttributes = new { @class = "form-control" } })
                        @Html.ValidationMessageFor(model => model.Location, "", new { @class = "text-danger" })
                    </div>
                </div>
    
                <div class="form-group">
                    <label class="col-md-6 control-label">
                        @Html.ActionLink("Traffic Cameras", "Index", null, htmlAttributes: new { @class = "btn btn-warning" })
                    </label>
                    <div class="col-md-6">
                        <input type="submit" value="Update Camera Setup" class="btn btn-warning" />
                    </div>
                </div>
            </div>
        </div>
    }
    
    <hr />
  13. In the Solution Explorer, under Views, right-click Cameras -> Add -> View...
  14. Type Delete as the View Name
  15. Click Add
  16. Create the small form as follows:
    @model TrafficTicketsSystem2.Models.Camera
    
    @{
        ViewBag.Title = "Delete Camera";
    }
    
    <h2 class="maroon common-font text-center bold">Delete/Remove Camera Setup</h2>
    
    <div class="containment">
        <hr />
        <dl class="dl-horizontal common-font">
            <dt class="maroon">@Html.DisplayNameFor(model => model.CameraId)</dt>
            <dd>@Html.DisplayFor(model => model.CameraId)</dd>
    
            <dt class="maroon">@Html.DisplayNameFor(model => model.CameraNumber)</dt>
            <dd>@Html.DisplayFor(model => model.CameraNumber)</dd>
    
            <dt class="maroon">@Html.DisplayNameFor(model => model.Make)</dt>
            <dd>@Html.DisplayFor(model => model.Make)</dd>
    
            <dt class="maroon">@Html.DisplayNameFor(model => model.Model)</dt>
            <dd>@Html.DisplayFor(model => model.Model)</dd>
    
            <dt class="maroon">@Html.DisplayNameFor(model => model.Location)</dt>
            <dd>@Html.DisplayFor(model => model.Location)</dd>
        </dl>
    
        <h3 class="common-font text-center bold maroon">Are you sure you want to delete this camera?</h3>
    
        @using (Html.BeginForm())
        {
            @Html.AntiForgeryToken()
    
            <div class="form-actions no-color">
                <input type="submit" value="Delete Camera Record" class="btn btn-warning" /> ::
                @Html.ActionLink("Cameras - Traffic Monitors", "Index")
            </div>
        }
    </div>
    
    <hr />
  17. In the Solution Explorer, right-click Controller -> Add -> Controller...
  18. In the middle frame of the Add Scaffold dialog box, make sure MVC 5 Controller With Read/Write Action.
    Click Add
  19. Type ViolationsTypes to get ViolationsTypesController
  20. Click Add
  21. Complete the class as follows:
    using System.IO;
    using System.Net;
    using System.Web.Mvc;
    using System.Collections.Generic;
    using TrafficTicketsSystem2.Models;
    using System.Runtime.Serialization.Formatters.Binary;
    
    namespace TrafficTicketsSystem2.Controllers
    {
        public class ViolationsTypesController : Controller
        {
            // GET: ViolationsTypes
            public ActionResult Index()
            {
                FileStream fsViolationsTypes = null;
                BinaryFormatter bfViolationsTypes = new BinaryFormatter();
                List<ViolationType> categories = new List<ViolationType>();
                string strViolationsTypesFile = Server.MapPath("~/App_Data/ViolationsTypes.tts");
    
                if (System.IO.File.Exists(strViolationsTypesFile))
                {
                    using (fsViolationsTypes = new FileStream(strViolationsTypesFile, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        categories = (List<ViolationType>)bfViolationsTypes.Deserialize(fsViolationsTypes);
                    }
                }
    
                return View(categories);
            }
    
            // GET: ViolationsTypes/Details/5
            public ActionResult Details(int? id)
            {
                ViolationType category = null;
                FileStream fsViolationsTypes = null;
                BinaryFormatter bfViolationsTypes = new BinaryFormatter();
                List<ViolationType> categories = new List<ViolationType>();
                string strViolationsTypesFile = Server.MapPath("~/App_Data/ViolationsTypes.tts");
    
                if (id == 0)
                {
                    return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
                }
    
                if (System.IO.File.Exists(strViolationsTypesFile))
                {
                    using (fsViolationsTypes = new FileStream(strViolationsTypesFile, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        categories = (List<ViolationType>)bfViolationsTypes.Deserialize(fsViolationsTypes);
                    }
    
                    category = categories.Find(cat => cat.ViolationTypeId == id);
                }
    
                if (category == null)
                {
                    return HttpNotFound();
                }
    
                return View(category);
            }
    
            // GET: ViolationsTypes/Create
            public ActionResult Create()
            {
                return View();
            }
    
            // POST: ViolationsTypes/Create
            [HttpPost]
            public ActionResult Create(FormCollection collection)
            {
                try
                {
                    // TODO: Add insert logic here
                    int vTypeId = 0;
                    FileStream fsViolationsTypes = null;
                    BinaryFormatter bfViolationsTypes = new BinaryFormatter();
                    List<ViolationType> categories = new List<ViolationType>();
                    string strViolationsTypesFile = Server.MapPath("~/App_Data/ViolationsTypes.tts");
    
                    if (!string.IsNullOrEmpty("DrvLicNumber"))
                    {
                        if (System.IO.File.Exists(strViolationsTypesFile))
                        {
                            using (fsViolationsTypes = new FileStream(strViolationsTypesFile, FileMode.Open, FileAccess.Read, FileShare.Read))
                            {
                                categories = (List<ViolationType>)bfViolationsTypes.Deserialize(fsViolationsTypes);
                            }
    
                            foreach (ViolationType vt in categories)
                            {
                                vTypeId = vt.ViolationTypeId;
                            }
                        }
    
                        vTypeId++;
    
                        ViolationType category = new ViolationType()
                        {
                            ViolationTypeId = vTypeId,
                            ViolationName = collection["ViolationName"],
                            Description = collection["Description"],
                        };
    
                        categories.Add(category);
    
                        using (fsViolationsTypes = new FileStream(strViolationsTypesFile, FileMode.Create, FileAccess.Write, FileShare.Write))
                        {
                            bfViolationsTypes.Serialize(fsViolationsTypes, categories);
                        }
                    }
    
                    return RedirectToAction("Index");
                }
                catch
                {
                    return View();
                }
            }
    
            // GET: ViolationsTypes/Edit/5
            public ActionResult Edit(int id)
            {
                ViolationType category = null;
                FileStream fsViolationsTypes = null;
                BinaryFormatter bfViolationsTypes = new BinaryFormatter();
                List<ViolationType> categories = new List<ViolationType>();
                string strViolationsTypesFile = Server.MapPath("~/App_Data/ViolationsTypes.tts");
    
                if (id == 0)
                {
                    return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
                }
    
                if (System.IO.File.Exists(strViolationsTypesFile))
                {
                    using (fsViolationsTypes = new FileStream(strViolationsTypesFile, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        categories = (List<ViolationType>)bfViolationsTypes.Deserialize(fsViolationsTypes);
                    }
    
                    category = categories.Find(cat => cat.ViolationTypeId == id);
                }
    
                if (category == null)
                {
                    return HttpNotFound();
                }
    
                return View(category);
            }
    
            // POST: ViolationsTypes/Edit/5
            [HttpPost]
            public ActionResult Edit(int id, FormCollection collection)
            {
                try
                {
                    // TODO: Add update logic here
                    FileStream fsViolationsTypes = null;
                    BinaryFormatter bfDrivers = new BinaryFormatter();
                    List<ViolationType> violationsTypes = new List<ViolationType>();
                    string strViolationsTypesFile = Server.MapPath("~/App_Data/ViolationsTypes.tts");
    
                    if (!string.IsNullOrEmpty("ViolationName"))
                    {
                        if (System.IO.File.Exists(strViolationsTypesFile))
                        {
                            using (fsViolationsTypes = new FileStream(strViolationsTypesFile, FileMode.Open, FileAccess.Read, FileShare.Read))
                            {
                                violationsTypes = (List<ViolationType>)bfDrivers.Deserialize(fsViolationsTypes);
                            }
                        }
    
                        ViolationType vType = violationsTypes.Find(type => type.ViolationTypeId == id);
    
                        vType.ViolationName = collection["ViolationName"];
                        vType.Description = collection["Description"];
    
                        using (fsViolationsTypes = new FileStream(strViolationsTypesFile, FileMode.Create, FileAccess.Write, FileShare.Write))
                        {
                            bfDrivers.Serialize(fsViolationsTypes, violationsTypes);
                        }
                    }
    
                    return RedirectToAction("Index");
                }
                catch
                {
                    return View();
                }
            }
    
            // GET: ViolationsTypes/Delete/5
            public ActionResult Delete(int id)
            {
                ViolationType category = null;
                FileStream fsViolationsTypes = null;
                BinaryFormatter bfViolationsTypes = new BinaryFormatter();
                List<ViolationType> categories = new List<ViolationType>();
                string strViolationsTypesFile = Server.MapPath("~/App_Data/ViolationsTypes.tts");
    
                if (id == 0)
                {
                    return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
                }
    
                if (System.IO.File.Exists(strViolationsTypesFile))
                {
                    using (fsViolationsTypes = new FileStream(strViolationsTypesFile, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        categories = (List<ViolationType>)bfViolationsTypes.Deserialize(fsViolationsTypes);
                    }
    
                    category = categories.Find(cat => cat.ViolationTypeId == id);
                }
    
                if (category == null)
                {
                    return HttpNotFound();
                }
    
                return View(category);
            }
    
            // POST: ViolationsTypes/Delete/5
            [HttpPost]
            public ActionResult Delete(int id, FormCollection collection)
            {
                try
                {
                    // TODO: Add delete logic here
                    FileStream fsViolationsTypes = null;
                    BinaryFormatter bfViolationsTypes = new BinaryFormatter();
                    List<ViolationType> violationsTypes = new List<ViolationType>();
                    string strViolationsTypesFile = Server.MapPath("~/App_Data/ViolationsTypes.tts");
    
                    if (!string.IsNullOrEmpty("ViolationName"))
                    {
                        if (System.IO.File.Exists(strViolationsTypesFile))
                        {
                            using (fsViolationsTypes = new FileStream(strViolationsTypesFile, FileMode.Open, FileAccess.Read, FileShare.Read))
                            {
                                violationsTypes = (List<ViolationType>)bfViolationsTypes.Deserialize(fsViolationsTypes);
                            }
                        }
    
                        ViolationType violationType = violationsTypes.Find(type => type.ViolationTypeId == id);
    
                        bool success = violationsTypes.Remove(violationType);
    
                        if (success)
                        {
                            using (fsViolationsTypes = new FileStream(strViolationsTypesFile, FileMode.Create, FileAccess.Write, FileShare.Write))
                            {
                                bfViolationsTypes.Serialize(fsViolationsTypes, violationsTypes);
                            }
                        }
                    }
    
                    return RedirectToAction("Index");
                }
                catch
                {
                    return View();
                }
            }
        }
    }
  22. In the class, right-click inside the Index() method and click Add View...
  23. Make sure the View Name text box is displaying Index. Click Add
  24. Create the webpage as follows:
    @model IEnumerable<TrafficTicketsSystem2.Models.ViolationType>
    
    @{
        ViewBag.Title = "Violations Types";
    }
    
    <h2 class="bold maroon common-font text-center">Violations Types</h2>
    
    <table class="table table-striped common-font">
        <tr>
            <th class="text-center maroon">@Html.DisplayNameFor(model => model.ViolationTypeId)</th>
            <th class="text-center maroon">@Html.DisplayNameFor(model => model.ViolationName)</th>
            <th class="maroon">@Html.DisplayNameFor(model => model.Description)</th>
            <th>@Html.ActionLink("New Violation Type", "Create")</th>
        </tr>
    
        @foreach (var item in Model)
        {
            <tr>
                <td class="text-center">@Html.DisplayFor(modelItem => item.ViolationTypeId)</td>
                <td>@Html.DisplayFor(modelItem => item.ViolationName)</td>
                <td>@Html.DisplayFor(modelItem => item.Description)</td>
                <td>
                    @Html.ActionLink("Edit", "Edit", new { id = item.ViolationTypeId }) |
                    @Html.ActionLink("Details", "Details", new { id = item.ViolationTypeId }) |
                    @Html.ActionLink("Delete", "Delete", new { id = item.ViolationTypeId })
                </td>
            </tr>
        }
    </table>
    
    <hr />
  25. In to Solution Explorer, under Views, right-click ViolationsTypes -> Add -> View...
  26. Type Details
  27. Click Add
  28. Create the webpage as follows:
    @model TrafficTicketsSystem2.Models.ViolationType
    
    @{
        ViewBag.Title = "Violation Type Details";
    }
    
    <h2 class="common-font bold maroon text-center">Details on Violation Type</h2>
    
    <hr />
    
    <div class="containment">
        <dl class="dl-horizontal common-font">
            <dt>@Html.DisplayNameFor(model => model.ViolationTypeId)</dt>
            <dd>@Html.DisplayFor(model => model.ViolationTypeId)</dd>
    
            <dt>@Html.DisplayNameFor(model => model.ViolationName)</dt>
            <dd>@Html.DisplayFor(model => model.ViolationName)</dd>
    
            <dt>@Html.DisplayNameFor(model => model.Description)</dt>
            <dd>@Html.DisplayFor(model => model.Description)</dd>
        </dl>
    </div>
    
    <p class="text-center">
        @Html.ActionLink("Edit", "Edit", new { id = Model.ViolationTypeId }) |
        @Html.ActionLink("Violations Types", "Index")</p>
    
    <hr />
  29. In to Solution Explorer, under Views, right-click ViolationsTypes -> Add -> View...
  30. Type Create as the name of the view
  31. Click Add
  32. Create the form as follows:
    @model TrafficTicketsSystem2.Models.ViolationType
    
    @{
        ViewBag.Title = "Create Violation Type";
    }
    
    <h2 class="common-font text-center bold maroon">Create Violation Type</h2>
    
    <hr />
    
    @using (Html.BeginForm())
    {
        @Html.AntiForgeryToken()
    
        <div class="large-content">
            <div class="form-horizontal common-font">
                @Html.ValidationSummary(true, "", new { @class = "text-danger" })
                <div class="form-group">
                    @Html.LabelFor(model => model.ViolationName, htmlAttributes: new { @class = "control-label col-md-5 maroon" })
                    <div class="col-md-7">
                        @Html.EditorFor(model => model.ViolationName, new { htmlAttributes = new { @class = "form-control" } })
                        @Html.ValidationMessageFor(model => model.ViolationName, "", new { @class = "text-danger" })
                    </div>
                </div>
    
                <div class="form-group">
                    @Html.LabelFor(model => model.Description, htmlAttributes: new { @class = "control-label col-md-5 maroon" })
                    <div class="col-md-7">
                        @Html.TextArea("Description", null,
                                       htmlAttributes: new { @class = "form-control", rows = "10", cols = "20" })
                        @Html.ValidationMessageFor(model => model.Description, "", new { @class = "text-danger" })
                    </div>
                </div>
    
                <div class="form-group">
                    <div class="control-label col-md-6">
                        @Html.ActionLink("Violations Types", "Index")
                    </div>
                    <div class="col-md-6">
                        <input type="submit" value="Save this Violation Type" class="btn btn-warning" />
                    </div>
                </div>
            </div>
        </div>
    }
  33. In to Solution Explorer, under Views, right-click ViolationsTypes -> Add -> View...
  34. Type Edit
  35. Click Add
  36. Create the form as follows:
    @model TrafficTicketsSystem2.Models.ViolationType
    
    @{
        ViewBag.Title = "Edit Violation Type";
    }
    
    <h2 class="maroon common-font text-center bold">Edit/Update Violation Type</h2>
    
    <hr />
    
    @using (Html.BeginForm())
    {
        @Html.AntiForgeryToken()
    
        <div class="containment">
            <div class="form-horizontal common-font">
                @Html.ValidationSummary(true, "", new { @class = "text-danger" })
                @Html.HiddenFor(model => model.ViolationTypeId)
    
                <div class="form-group">
                    @Html.LabelFor(model => model.ViolationName, htmlAttributes: new { @class = "control-label col-md-5" })
                    <div class="col-md-7">
                        @Html.EditorFor(model => model.ViolationName, new { htmlAttributes = new { @class = "form-control" } })
                        @Html.ValidationMessageFor(model => model.ViolationName, "", new { @class = "text-danger" })
                    </div>
                </div>
    
                <div class="form-group">
                    @Html.LabelFor(model => model.Description, htmlAttributes: new { @class = "control-label col-md-5" })
                    <div class="col-md-7">
                        @Html.TextArea("Description", @ViewBag.Description as string, htmlAttributes: new { @class = "form-control", rows = "10", cols = "50" })
                        @Html.ValidationMessageFor(model => model.Description, "", new { @class = "text-danger" })
                    </div>
                </div>
    
                <div class="form-group">
                    <label class="col-md-6 control-label">
                        @Html.ActionLink("Violations Types", "Index" })
                    </label>
                    <div class="col-md-6">
                        <input type="submit" value="Save Violation Type Update" class="btn btn-warning" />
                    </div>
                </div>
            </div>
        </div>
    }
    
    <hr />
  37. In to Solution Explorer, under Views, right-click ViolationsTypes -> Add -> View...
  38. Type Delete
  39. Click Add
  40. Create the form as follows:
    @model TrafficTicketsSystem2.Models.ViolationType
    
    @{
        ViewBag.Title = "Delete Violation Type";
    }
    
    <h2 class="maroon common-font text-center bold">Delete Violation Type</h2>
    
    <div class="containment">
        <hr />
        <dl class="dl-horizontal common-font">
            <dt>@Html.DisplayNameFor(model => model.ViolationTypeId)</dt>
            <dd>@Html.DisplayFor(model => model.ViolationTypeId)</dd>
    
            <dt>@Html.DisplayNameFor(model => model.ViolationName)</dt>
            <dd>@Html.DisplayFor(model => model.ViolationName)</dd>
    
            <dt>@Html.DisplayNameFor(model => model.Description)</dt>
            <dd>@Html.DisplayFor(model => model.Description)</dd>
        </dl>
    
        <h3 class="common-font text-center bold blue">Are you sure you want to delete this violation type?</h3>
    
        @using (Html.BeginForm())
        {
            @Html.AntiForgeryToken()
    
            <div class="form-actions no-color">
                <input type="submit" value="Delete this Violation Type" class="btn btn-warning" /> ::
                @Html.ActionLink("Violations Types", "Index")
            </div>
        }
    </div>
  41. In the Solution Explorer, right-click Controller -> Add -> New Scaffolded Item...
  42. In the left frame of the Add Scaffold dialog box, under Common, click MVC and, in the middle list, click MVC 5 Controller With Read/Write Action
  43. Click Add
  44. Type Drivers to get DriversController
  45. Click Add
  46. Complete the class as follows:
    using System.IO;
    using System.Net;
    using System.Web.Mvc;
    using System.Collections.Generic;
    using TrafficTicketsSystem2.Models;
    using System.Runtime.Serialization.Formatters.Binary;
    
    namespace TrafficTicketsSystem2.Controllers
    {
        public class DriversController : Controller
        {
            // GET: Drivers
            public ActionResult Index()
            {
                FileStream fsDrivers = null;
                List<Driver> drivers = new List<Driver>();
                BinaryFormatter bfDrivers = new BinaryFormatter();
                string strDriversFile = Server.MapPath("~/App_Data/Drivers.tts");
    
                if (System.IO.File.Exists(strDriversFile))
                {
                    using (fsDrivers = new FileStream(strDriversFile, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        drivers = (List<Driver>)bfDrivers.Deserialize(fsDrivers);
                    }
                }
    
                return View(drivers);
            }
    
            // GET: Drivers/Details/5
            public ActionResult Details(int? id)
            {
                Driver driver = null;
                FileStream fsDrivers = null;
                List<Driver> drivers = new List<Driver>();
                BinaryFormatter bfDrivers = new BinaryFormatter();
                string strDriversFile = Server.MapPath("~/App_Data/Drivers.tts");
    
                if (id == null)
                {
                    return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
                }
    
                if (System.IO.File.Exists(strDriversFile))
                {
                    using (fsDrivers = new FileStream(strDriversFile, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        drivers = (List<Driver>)bfDrivers.Deserialize(fsDrivers);
                    }
    
                    driver = drivers.Find(dvr => dvr.DriverId == id);
                }
    
                if (driver == null)
                {
                    return HttpNotFound();
                }
    
                return View(driver);
            }
    
            // GET: Drivers/Create
            public ActionResult Create()
            {
                return View();
            }
    
            // POST: Drivers/Create
            [HttpPost]
            public ActionResult Create(FormCollection collection)
            {
                try
                {
                    // TODO: Add insert logic here
                    int driverId = 0;
                    FileStream fsDrivers = null;
                    List<Driver> drivers = new List<Driver>();
                    BinaryFormatter bfDrivers = new BinaryFormatter();
                    string strDriversFile = Server.MapPath("~/App_Data/Drivers.tts");
    
                    if ((!string.IsNullOrEmpty("DrvLicNumber")) && (!string.IsNullOrEmpty("State")))
                    {
                        if (System.IO.File.Exists(strDriversFile))
                        {
                            using (fsDrivers = new FileStream(strDriversFile, FileMode.Open, FileAccess.Read, FileShare.Read))
                            {
                                drivers = (List<Driver>)bfDrivers.Deserialize(fsDrivers);
                            }
    
                            foreach(Driver drv in drivers)
                            {
                                driverId = drv.DriverId;
                            }
                        }
    
                        driverId++;
    
                        Driver person = new Driver()
                        {
                            DriverId = driverId,
                            DrvLicNumber = collection["DrvLicNumber"],
                            FirstName = collection["FirstName"],
                            LastName = collection["LastName"],
                            Address = collection["Address"],
                            City = collection["City"],
                            County = collection["County"],
                            State = collection["State"],
                            ZIPCode = collection["ZIPCode"],
                        };
    
                        drivers.Add(person);
    
                        using (fsDrivers = new FileStream(strDriversFile, FileMode.Create, FileAccess.Write, FileShare.Write))
                        {
                            bfDrivers.Serialize(fsDrivers, drivers);
                        }
                    }
    
                    return RedirectToAction("Index");
                }
                catch
                {
                    return View();
                }
            }
    
            // GET: Drivers/Edit/5
            public ActionResult Edit(int? id)
            {
                Driver driver = null;
                FileStream fsDrivers = null;
                List<Driver> drivers = new List<Driver>();
                BinaryFormatter bfDrivers = new BinaryFormatter();
                string strDriversFile = Server.MapPath("~/App_Data/Drivers.tts");
    
                if (id == null)
                {
                    return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
                }
    
                if (System.IO.File.Exists(strDriversFile))
                {
                    using (fsDrivers = new FileStream(strDriversFile, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        drivers = (List<Driver>)bfDrivers.Deserialize(fsDrivers);
                    }
    
                    driver = drivers.Find(dvr => dvr.DriverId == id);
                }
    
                if (driver == null)
                {
                    return HttpNotFound();
                }
    
                return View(driver);
            }
    
            // POST: Drivers/Edit/5
            [HttpPost]
            public ActionResult Edit(int id, FormCollection collection)
            {
                try
                {
                    // TODO: Add update logic here
                    FileStream fsDrivers = null;
                    List<Driver> drivers = new List<Driver>();
                    BinaryFormatter bfDrivers = new BinaryFormatter();
                    string strDriversFile = Server.MapPath("~/App_Data/Drivers.tts");
    
                    if (!string.IsNullOrEmpty("DrvLicNumber"))
                    {
                        if (System.IO.File.Exists(strDriversFile))
                        {
                            using (fsDrivers = new FileStream(strDriversFile, FileMode.Open, FileAccess.Read, FileShare.Read))
                            {
                                drivers = (List<Driver>)bfDrivers.Deserialize(fsDrivers);
                            }
                        }
    
                        Driver driver = drivers.Find(dvr => dvr.DriverId == id);
    
                        driver.FirstName = collection["FirstName"];
                        driver.LastName = collection["LastName"];
                        driver.Address = collection["Address"];
                        driver.City = collection["City"];
                        driver.County = collection["County"];
                        driver.State = collection["State"];
                        driver.ZIPCode = collection["ZIPCode"];
    
                        using (fsDrivers = new FileStream(strDriversFile, FileMode.Create, FileAccess.Write, FileShare.Write))
                        {
                            bfDrivers.Serialize(fsDrivers, drivers);
                        }
                    }
    
                    return RedirectToAction("Index");
                }
                catch
                {
                    return View();
                }
            }
    
            // GET: Drivers/Delete/5
            public ActionResult Delete(int? id)
            {
                Driver driver = null;
                FileStream fsDrivers = null;
                List<Driver> drivers = new List<Driver>();
                BinaryFormatter bfDrivers = new BinaryFormatter();
                string strDriversFile = Server.MapPath("~/App_Data/Drivers.tts");
    
                if (id == null)
                {
                    return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
                }
    
                if (System.IO.File.Exists(strDriversFile))
                {
                    using (fsDrivers = new FileStream(strDriversFile, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        drivers = (List<Driver>)bfDrivers.Deserialize(fsDrivers);
                    }
    
                    driver = drivers.Find(dvr => dvr.DriverId == id);
                }
    
                if (driver == null)
                {
                    return HttpNotFound();
                }
    
                return View(driver);
            }
    
            // POST: Drivers/Delete/5
            [HttpPost]
            public ActionResult Delete(int id, FormCollection collection)
            {
                try
                {
                    // TODO: Add delete logic here
                    FileStream fsDrivers = null;
                    List<Driver> drivers = new List<Driver>();
                    BinaryFormatter bfDrivers = new BinaryFormatter();
                    string strDriversFile = Server.MapPath("~/App_Data/Drivers.tts");
    
                    if (!string.IsNullOrEmpty("DrvLicNumber"))
                    {
                        if (System.IO.File.Exists(strDriversFile))
                        {
                            using (fsDrivers = new FileStream(strDriversFile, FileMode.Open, FileAccess.Read, FileShare.Read))
                            {
                                drivers = (List<Driver>)bfDrivers.Deserialize(fsDrivers);
                            }
                        }
    
                        Driver driver = drivers.Find(dvr => dvr.DriverId == id);
    
                        drivers.Remove(driver);
    
                        using (fsDrivers = new FileStream(strDriversFile, FileMode.Create, FileAccess.Write, FileShare.Write))
                        {
                            bfDrivers.Serialize(fsDrivers, drivers);
                        }
                    }
    
                    return RedirectToAction("Index");
                }
                catch
                {
                    return View();
                }
            }
        }
    }
  47. In the class, right-click inside the Index() method and click Add View...
  48. Make sure the View Name text box is displaying Index. Click Add
  49. Create the webpage as follows:
    @model IEnumerable<TrafficTicketsSystem2.Models.Driver>
    
    @{
        ViewBag.Title = "Drivers";
    }
    
    <h2 class="bold maroon common-font text-center">Drivers - Vehicles Owners</h2>
    
    <table class="table table-striped common-font">
        <tr>
            <th class="text-center maroon">@Html.DisplayNameFor(model => model.DriverId)</th>
            <th class="text-center maroon">@Html.DisplayNameFor(model => model.DrvLicNumber)</th>
            <th class="maroon">@Html.DisplayNameFor(model => model.FirstName)</th>
            <th class="maroon">@Html.DisplayNameFor(model => model.LastName)</th>
            <th class="maroon">@Html.DisplayNameFor(model => model.Address)</th>
            <th class="maroon">@Html.DisplayNameFor(model => model.City)</th>
            <th class="maroon">@Html.DisplayNameFor(model => model.County)</th>
            <th class="maroon">@Html.DisplayNameFor(model => model.State)</th>
            <th class="maroon">@Html.DisplayNameFor(model => model.ZIPCode)</th>
            <th>@Html.ActionLink("Issue New Driver's License", "Create")</th>
        </tr>
    
        @foreach (var item in Model)
        {
            <tr>
                <td class="text-center">@Html.DisplayFor(modelItem => item.DriverId)</td>
                <td class="text-center">@Html.DisplayFor(modelItem => item.DrvLicNumber)</td>
                <td>@Html.DisplayFor(modelItem => item.FirstName)</td>
                <td>@Html.DisplayFor(modelItem => item.LastName)</td>
                <td>@Html.DisplayFor(modelItem => item.Address)</td>
                <td>@Html.DisplayFor(modelItem => item.City)</td>
                <td>@Html.DisplayFor(modelItem => item.County)</td>
                <td>@Html.DisplayFor(modelItem => item.State)</td>
                <td>@Html.DisplayFor(modelItem => item.ZIPCode)</td>
                <td>
                    @Html.ActionLink("Edit", "Edit", new { id = item.DriverId }) |
                    @Html.ActionLink("Details", "Details", new { id = item.DriverId }) |
                    @Html.ActionLink("Delete", "Delete", new { id = item.DriverId })
                </td>
            </tr>
        }
    </table>
  50. In to Solution Explorer, under Views, right-click Drivers -> Add -> View...
  51. Type Details
  52. Click Add
  53. Create the webpage as follows:
    @model TrafficTicketsSystem2.Models.Driver
    
    @{
        ViewBag.Title = "Driver Details";
    }
    
    <h2 class="common-font bold maroon text-center">Driver's License Details</h2>
    
    <hr />
    
    <div class="containment">
        <dl class="dl-horizontal common-font">
            <dt class="maroon">@Html.DisplayNameFor(model => model.DriverId)</dt>
            <dd>@Html.DisplayFor(model => model.DriverId)</dd>
    
            <dt class="maroon">@Html.DisplayNameFor(model => model.DrvLicNumber)</dt>
            <dd>@Html.DisplayFor(model => model.DrvLicNumber)</dd>
    
            <dt class="maroon">@Html.DisplayNameFor(model => model.FirstName)</dt>
            <dd class="maroon">@Html.DisplayFor(model => model.FirstName)</dd>
    
            <dt class="maroon">@Html.DisplayNameFor(model => model.LastName)</dt>
            <dd>@Html.DisplayFor(model => model.LastName)</dd>
    
            <dt class="maroon">@Html.DisplayNameFor(model => model.Address)</dt>
            <dd>@Html.DisplayFor(model => model.Address)</dd>
    
            <dt class="maroon">@Html.DisplayNameFor(model => model.City)</dt>
            <dd>@Html.DisplayFor(model => model.City)</dd>
    
            <dt class="maroon">@Html.DisplayNameFor(model => model.County)</dt>
            <dd class="maroon">@Html.DisplayFor(model => model.County)</dd>
    
            <dt class="maroon">@Html.DisplayNameFor(model => model.State)</dt>
            <dd>@Html.DisplayFor(model => model.State)</dd>
    
            <dt class="maroon">@Html.DisplayNameFor(model => model.ZIPCode)</dt>
            <dd>@Html.DisplayFor(model => model.ZIPCode)</dd>
        </dl>
    </div>
    
    <p class="text-center">
        @Html.ActionLink("Edit", "Edit", new { id = Model.DriverId }) |
        @Html.ActionLink("Drivers - Vehicles Owners", "Index")</p>
    
    <hr />
  54. In to Solution Explorer, under Views, right-click Drivers -> Add -> View...
  55. Type Create as the name of the view
  56. Click Add
  57. Create the form as follows:
    @model TrafficTicketsSystem2.Models.Driver
    
    @{
        ViewBag.Title = "Create Driver";
    }
    
    <h2 class="common-font maroon text-center bold">Driver's License Issuance</h2>
    
    <hr />
    
    @using (Html.BeginForm())
    {
        @Html.AntiForgeryToken()
    
        <div class="containment">
            <div class="form-horizontal common-font">
                @Html.ValidationSummary(true, "", new { @class = "text-danger" })
                <div class="form-group">
                    @Html.LabelFor(model => model.DrvLicNumber, htmlAttributes: new { @class = "control-label maroon col-md-5" })
                    <div class="col-md-7">
                        @Html.EditorFor(model => model.DrvLicNumber, new { htmlAttributes = new { @class = "form-control" } })
                        @Html.ValidationMessageFor(model => model.DrvLicNumber, "", new { @class = "text-danger" })
                    </div>
                </div>
    
                <div class="form-group">
                    @Html.LabelFor(model => model.FirstName, htmlAttributes: new { @class = "control-label maroon col-md-5" })
                    <div class="col-md-7">
                        @Html.EditorFor(model => model.FirstName, new { htmlAttributes = new { @class = "form-control" } })
                        @Html.ValidationMessageFor(model => model.FirstName, "", new { @class = "text-danger" })
                    </div>
                </div>
    
                <div class="form-group">
                    @Html.LabelFor(model => model.LastName, htmlAttributes: new { @class = "control-label maroon col-md-5" })
                    <div class="col-md-7">
                        @Html.EditorFor(model => model.LastName, new { htmlAttributes = new { @class = "form-control" } })
                        @Html.ValidationMessageFor(model => model.LastName, "", new { @class = "text-danger" })
                    </div>
                </div>
    
                <div class="form-group">
                    @Html.LabelFor(model => model.Address, htmlAttributes: new { @class = "control-label maroon col-md-5" })
                    <div class="col-md-7">
                        @Html.EditorFor(model => model.Address, new { htmlAttributes = new { @class = "form-control" } })
                        @Html.ValidationMessageFor(model => model.Address, "", new { @class = "text-danger" })
                    </div>
                </div>
    
                <div class="form-group">
                    @Html.LabelFor(model => model.City, htmlAttributes: new { @class = "control-label maroon col-md-5" })
                    <div class="col-md-7">
                        @Html.EditorFor(model => model.City, new { htmlAttributes = new { @class = "form-control" } })
                        @Html.ValidationMessageFor(model => model.City, "", new { @class = "text-danger" })
                    </div>
                </div>
    
                <div class="form-group">
                    @Html.LabelFor(model => model.County, htmlAttributes: new { @class = "control-label maroon col-md-5" })
                    <div class="col-md-7">
                        @Html.EditorFor(model => model.County, new { htmlAttributes = new { @class = "form-control" } })
                        @Html.ValidationMessageFor(model => model.County, "", new { @class = "text-danger" })
                    </div>
                </div>
    
                <div class="form-group">
                    @Html.LabelFor(model => model.State, htmlAttributes: new { @class = "control-label maroon col-md-5" })
                    <div class="col-md-7">
                        @Html.EditorFor(model => model.State, new { htmlAttributes = new { @class = "form-control" } })
                        @Html.ValidationMessageFor(model => model.State, "", new { @class = "text-danger" })
                    </div>
                </div>
    
                <div class="form-group">
                    @Html.LabelFor(model => model.ZIPCode, htmlAttributes: new { @class = "control-label maroon col-md-5" })
                    <div class="col-md-7">
                        @Html.EditorFor(model => model.ZIPCode, new { htmlAttributes = new { @class = "form-control" } })
                        @Html.ValidationMessageFor(model => model.ZIPCode, "", new { @class = "text-danger" })
                    </div>
                </div>
    
                <div class="form-group">
                    <label class="control-label col-md-6">
                        @Html.ActionLink("Vehicles Owners", "Index")
                    </label>
                    <div class="col-md-6">
                        <input type="submit" value="Create Driver Record" class="btn btn-warning" />
                    </div>
                </div>
            </div>
        </div>
    }
    
    <hr />
  58. In to Solution Explorer, under Views, right-click Drivers -> Add -> View...
  59. Type Edit
  60. Click Add
  61. Create the form as follows:
    @model TrafficTicketsSystem2.Models.Driver
    
    @{
        ViewBag.Title = "Edit Driver";
    }
    
    <h2 class="maroon common-font text-center bold">Edit/Update Driver Details</h2>
    
    <hr />
    
    @using (Html.BeginForm())
    {
        @Html.AntiForgeryToken()
    
        <div class="containment">
            <div class="form-horizontal common-font">
                @Html.ValidationSummary(true, "", new { @class = "text-danger" })
                @Html.HiddenFor(model => model.DriverId)
    
                <div class="form-group">
                    @Html.LabelFor(model => model.DrvLicNumber, htmlAttributes: new { @class = "control-label maroon col-md-5" })
                    <div class="col-md-7">
                        @Html.EditorFor(model => model.DrvLicNumber, new { htmlAttributes = new { @class = "form-control" } })
                        @Html.ValidationMessageFor(model => model.DrvLicNumber, "", new { @class = "text-danger" })
                    </div>
                </div>
    
                <div class="form-group">
                    @Html.LabelFor(model => model.FirstName, htmlAttributes: new { @class = "control-label maroon col-md-5" })
                    <div class="col-md-7">
                        @Html.EditorFor(model => model.FirstName, new { htmlAttributes = new { @class = "form-control" } })
                        @Html.ValidationMessageFor(model => model.FirstName, "", new { @class = "text-danger" })
                    </div>
                </div>
    
                <div class="form-group">
                    @Html.LabelFor(model => model.LastName, htmlAttributes: new { @class = "control-label maroon col-md-5" })
                    <div class="col-md-7">
                        @Html.EditorFor(model => model.LastName, new { htmlAttributes = new { @class = "form-control" } })
                        @Html.ValidationMessageFor(model => model.LastName, "", new { @class = "text-danger" })
                    </div>
                </div>
    
                <div class="form-group">
                    @Html.LabelFor(model => model.Address, htmlAttributes: new { @class = "control-label maroon col-md-5" })
                    <div class="col-md-7">
                        @Html.EditorFor(model => model.Address, new { htmlAttributes = new { @class = "form-control" } })
                        @Html.ValidationMessageFor(model => model.Address, "", new { @class = "text-danger" })
                    </div>
                </div>
    
                <div class="form-group">
                    @Html.LabelFor(model => model.City, htmlAttributes: new { @class = "control-label maroon col-md-5" })
                    <div class="col-md-7">
                        @Html.EditorFor(model => model.City, new { htmlAttributes = new { @class = "form-control" } })
                        @Html.ValidationMessageFor(model => model.City, "", new { @class = "text-danger" })
                    </div>
                </div>
    
                <div class="form-group">
                    @Html.LabelFor(model => model.County, htmlAttributes: new { @class = "control-label col-md-5 maroon" })
                    <div class="col-md-7">
                        @Html.EditorFor(model => model.County, new { htmlAttributes = new { @class = "form-control" } })
                        @Html.ValidationMessageFor(model => model.County, "", new { @class = "text-danger" })
                    </div>
                </div>
    
                <div class="form-group">
                    @Html.LabelFor(model => model.State, htmlAttributes: new { @class = "control-label col-md-5 maroon" })
                    <div class="col-md-7">
                        @Html.EditorFor(model => model.State, new { htmlAttributes = new { @class = "form-control" } })
                        @Html.ValidationMessageFor(model => model.State, "", new { @class = "text-danger" })
                    </div>
                </div>
    
                <div class="form-group">
                    @Html.LabelFor(model => model.ZIPCode, htmlAttributes: new { @class = "control-label col-md-5 maroon" })
                    <div class="col-md-7">
                        @Html.EditorFor(model => model.ZIPCode, new { htmlAttributes = new { @class = "form-control" } })
                        @Html.ValidationMessageFor(model => model.ZIPCode, "", new { @class = "text-danger" })
                    </div>
                </div>
    
                <div class="form-group">
                    <label class="col-md-6 control-label">
                        @Html.ActionLink("Drivers - Vehicles Owners", "Index", null, htmlAttributes: new { @class = "btn btn-warning" })
                    </label>
                    <div class="col-md-6">
                        <input type="submit" value="Update Driver Record" class="btn btn-warning" />
                    </div>
                </div>
            </div>
        </div>
    }
    
    <hr />
  62. In to Solution Explorer, under Views, right-click Drivers -> Add -> View...
  63. Type Delete
  64. Click Add
  65. Create the form as follows:
    @model TrafficTicketsSystem2.Models.Driver
    
    @{
        ViewBag.Title = "Delete Driver";
    }
    
    <h2 class="maroon common-font text-center bold">Delete Driver's Record</h2>
    
    <div class="containment">
        <hr />
        <dl class="dl-horizontal common-font">
            <dt class="maroon">@Html.DisplayNameFor(model => model.DriverId)</dt>
            <dd>@Html.DisplayFor(model => model.DriverId)</dd>
    
            <dt class="maroon">@Html.DisplayNameFor(model => model.DrvLicNumber)</dt>
            <dd>@Html.DisplayFor(model => model.DrvLicNumber)</dd>
    
            <dt class="maroon">@Html.DisplayNameFor(model => model.FirstName)</dt>
            <dd>@Html.DisplayFor(model => model.FirstName)</dd>
    
            <dt class="maroon">@Html.DisplayNameFor(model => model.LastName)</dt>
            <dd>@Html.DisplayFor(model => model.LastName)</dd>
    
            <dt class="maroon">@Html.DisplayNameFor(model => model.Address)</dt>
            <dd>@Html.DisplayFor(model => model.Address)</dd>
    
            <dt class="maroon">@Html.DisplayNameFor(model => model.City)</dt>
            <dd>@Html.DisplayFor(model => model.City)</dd>
    
            <dt class="maroon">@Html.DisplayNameFor(model => model.County)</dt>
            <dd>@Html.DisplayFor(model => model.County)</dd>
    
            <dt class="maroon">@Html.DisplayNameFor(model => model.State)</dt>
            <dd>@Html.DisplayFor(model => model.State)</dd>
    
            <dt class="maroon">@Html.DisplayNameFor(model => model.ZIPCode)</dt>
            <dd>@Html.DisplayFor(model => model.ZIPCode)</dd>
        </dl>
    
        <h3 class="common-font text-center bold blue">Are you sure you want to delete this driver's record?</h3>
    
        @using (Html.BeginForm())
        {
            @Html.AntiForgeryToken()
    
            <div class="form-actions no-color">
                <input type="submit" value="Delete Driver Record" class="btn btn-warning" /> ::
                @Html.ActionLink("Drivers - Vehicles Owners", "Index")
            </div>
        }
    </div>
    
    <hr />
  66. In the Solution Explorer, right-click Controllers -> Add -> Controller...
  67. In middle frame of the Add Scaffold dialog box, make sure MVC 5 Controller With Read/Write Actions. Click Add
  68. Type Vehicles to get VehiclesController
  69. Click Add
  70. Complete the class as follows:
    using System.IO;
    using System.Net;
    using System.Web.Mvc;
    using System.Collections.Generic;
    using TrafficTicketsSystem2.Models;
    using System.Runtime.Serialization.Formatters.Binary;
    
    namespace TrafficTicketsSystem2.Controllers
    {
        public class VehiclesController : Controller
        {
            // GET: Vehicles
            public ActionResult Index()
            {
                FileStream fsVehicles = null;
                List<Vehicle> vehicles = new List<Vehicle>();
                BinaryFormatter bfVehicles = new BinaryFormatter();
    
                string strVehiclesFile = Server.MapPath("~/App_Data/Vehicles.tts");
    
                if (System.IO.File.Exists(strVehiclesFile))
                {
                    using (fsVehicles = new FileStream(strVehiclesFile, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        vehicles = (List<Vehicle>)bfVehicles.Deserialize(fsVehicles);
                    }
                }
    
                return View(vehicles);
            }
    
            // GET: Vehicles/Details/5
            public ActionResult Details(int? id)
            {
                Vehicle car = null;
                FileStream fsVehicles = null;
                List<Vehicle> vehicles = new List<Vehicle>();
                BinaryFormatter bfVehicles = new BinaryFormatter();
                string strVehiclesFile = Server.MapPath("~/App_Data/Vehicles.tts");
    
                if (id == null)
                {
                    return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
                }
    
                if (System.IO.File.Exists(strVehiclesFile))
                {
                    using (fsVehicles = new FileStream(strVehiclesFile, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        vehicles = (List<Vehicle>)bfVehicles.Deserialize(fsVehicles);
                    }
    
                    car = vehicles.Find(engine => engine.VehicleId == id);
                }
    
                if (car == null)
                {
                    return HttpNotFound();
                }
    
                return View(car);
            }
    
            // GET: Vehicles/Create
            public ActionResult Create()
            {
                return View();
            }
    
            // POST: Vehicles/Create
            [HttpPost]
            public ActionResult Create(FormCollection collection)
            {
                try
                {
                    // TODO: Add insert logic here
                    bool driverFound = false;
                    int vehicleId = 0, driverId = 0;
                    List<Driver> drivers = new List<Driver>();
                    List<Vehicle> vehicles = new List<Vehicle>();
                    FileStream fsVehicles = null, fsDrivers = null;
                    BinaryFormatter bfDrivers = new BinaryFormatter();
                    BinaryFormatter bfVehicles = new BinaryFormatter();
                    string strDriversFile = Server.MapPath("~/App_Data/Drivers.tts");
                    string strVehiclesFile = Server.MapPath("~/App_Data/Vehicles.tts");
    
                    // Open the file of the drivers records
                    if (System.IO.File.Exists(strDriversFile))
                    {
                        using (fsDrivers = new FileStream(strDriversFile, FileMode.Open, FileAccess.Read, FileShare.Read))
                        {
                            /* After opening the file, get the list of records from it
                             * and store in the empty LinkedList<> collection we started. */
                            drivers = (List<Driver>)bfDrivers.Deserialize(fsDrivers);
    
                            // Navigate to each record
                            foreach (Driver person in drivers)
                            {
                                /* When you get to a record, find out if its DrvLicNumber value 
                                 * is the DrvLicNumber the user typed on the form. */
                                if (person.DrvLicNumber == collection["DrvLicNumber"])
                                {
                                    /* If you find the record with that DrvLicNumber value, 
                                     * make a note to indicate it. */
                                    driverId = person.DriverId;
                                    driverFound = true;
                                    break;
                                }
                            }
                        }
                    }
    
                    /* If the driverFound is true, it means the driver's license 
                     * number is valid, which means we can save the record. */
                    if (driverFound == true)
                    {
                        // Check whether a file for vehicles exists already.
                        if (System.IO.File.Exists(strVehiclesFile))
                        {
                            // If a file for vehicles exists already, open it ...
                            using (fsVehicles = new FileStream(strVehiclesFile, FileMode.Open, FileAccess.Read, FileShare.Read))
                            {
                                // ... and store the records in our vehicles variable
                                vehicles = (List<Vehicle>)bfVehicles.Deserialize(fsVehicles);
                            }
    
                            foreach (Vehicle engine in vehicles)
                                vehicleId = engine.VehicleId;
                        }
    
                        vehicleId++;
    
                        Vehicle car = new Vehicle()
                        {
                            VehicleId = vehicleId,
                            TagNumber = collection["TagNumber"],
                            DriverId = driverId,
                            Make = collection["Make"],
                            Model = collection["Model"],
                            VehicleYear = collection["VehicleYear"],
                            Color = collection["Color"]
                        };
    
                        vehicles.Add(car);
    
                        using (fsVehicles = new FileStream(strVehiclesFile, FileMode.Create, FileAccess.Write, FileShare.Write))
                        {
                            bfVehicles.Serialize(fsVehicles, vehicles);
                        }
                    }
    
                    return RedirectToAction("Index");
                }
                catch
                {
                    return View();
                }
            }
    
            // GET: Vehicles/Edit/5
            public ActionResult Edit(int? id)
            {
                Vehicle car = null;
                string strDrvLicNumber = string.Empty;
                List<Driver> drivers = new List<Driver>();
                List<Vehicle> vehicles = new List<Vehicle>();
                FileStream fsVehicles = null, fsDrivers = null;
                BinaryFormatter bfDrivers = new BinaryFormatter();
                BinaryFormatter bfVehicles = new BinaryFormatter();
                string strDriversFile = Server.MapPath("~/App_Data/Drivers.tts");
                string strVehiclesFile = Server.MapPath("~/App_Data/Vehicles.tts");
    
                if (id == null)
                {
                    return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
                }
    
                if (System.IO.File.Exists(strVehiclesFile))
                {
                    using (fsVehicles = new FileStream(strVehiclesFile, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        vehicles = (List<Vehicle>)bfVehicles.Deserialize(fsVehicles);
                    }
    
                    car = vehicles.Find(engine => engine.VehicleId == id);
                }
    
                if (System.IO.File.Exists(strDriversFile))
                {
                    using (fsDrivers = new FileStream(strDriversFile, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        drivers = (List<Driver>)bfDrivers.Deserialize(fsDrivers);
                        
                        foreach (Driver person in drivers)
                        {
                            if (person.DriverId == car.DriverId)
                            {
                                ViewBag.DrvLicNumber = person.DrvLicNumber;
                                break;
                            }
                        }
                    }
                }
    
                if (car == null)
                {
                    return HttpNotFound();
                }
    
                return View(car);
            }
    
            // POST: Vehicles/Edit/5
            [HttpPost]
            public ActionResult Edit(int id, FormCollection collection)
            {
                try
                {
                    // TODO: Add update logic here
                    int driverId = 0;
                    List<Driver> drivers = new List<Driver>();
                    List<Vehicle> vehicles = new List<Vehicle>();
                    FileStream fsVehicles = null, fsDrivers = null;
                    BinaryFormatter bfDrivers = new BinaryFormatter();
                    BinaryFormatter bfVehicles = new BinaryFormatter();
                    string strDriversFile = Server.MapPath("~/App_Data/Drivers.tts");
                    string strVehiclesFile = Server.MapPath("~/App_Data/Vehicles.tts");
    
                    if (!string.IsNullOrEmpty("CameraNumber"))
                    {
                        if (System.IO.File.Exists(strVehiclesFile))
                        {
                            using (fsVehicles = new FileStream(strVehiclesFile, FileMode.Open, FileAccess.Read, FileShare.Read))
                            {
                                vehicles = (List<Vehicle>)bfVehicles.Deserialize(fsVehicles);
                            }
                        }
    
                        Vehicle vehicle = vehicles.Find(car => car.VehicleId == id);
    
                        if (System.IO.File.Exists(strDriversFile))
                        {
                            using (fsDrivers = new FileStream(strDriversFile, FileMode.Open, FileAccess.Read, FileShare.Read))
                            {
                                drivers = (List<Driver>)bfDrivers.Deserialize(fsDrivers);
    
                                foreach (Driver person in drivers)
                                {
                                    if (person.DrvLicNumber == collection["DrvLicNumber"])
                                    {
                                        driverId = person.DriverId;
                                        break;
                                    }
                                }
                            }
                        }
    
                        vehicle.TagNumber = collection["TagNumber"];
                        vehicle.DriverId = driverId;
                        vehicle.Make = collection["Make"];
                        vehicle.Model = collection["Model"];
                        vehicle.VehicleYear = collection["VehicleYear"];
                        vehicle.Color = collection["Color"];
    
                        using (fsVehicles = new FileStream(strVehiclesFile, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite))
                        {
                            bfVehicles.Serialize(fsVehicles, vehicles);
                        }
                    }
    
                    return RedirectToAction("Index");
                }
                catch
                {
                    return View();
                }
            }
    
            // GET: Vehicles/Delete/5
            public ActionResult Delete(int? id)
            {
                Vehicle car = null;
                FileStream fsVehicles = null;
                List<Vehicle> vehicles = new List<Vehicle>();
                BinaryFormatter bfVehicles = new BinaryFormatter();
                string strVehiclesFile = Server.MapPath("~/App_Data/Vehicles.tts");
    
                if (id == null)
                {
                    return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
                }
    
                if (System.IO.File.Exists(strVehiclesFile))
                {
                    using (fsVehicles = new FileStream(strVehiclesFile, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
    
                        vehicles = (List<Vehicle>)bfVehicles.Deserialize(fsVehicles);
                    }
    
                    car = vehicles.Find(engine => engine.VehicleId == id);
                }
    
                if (car == null)
                {
                    return HttpNotFound();
                }
    
                return View(car);
            }
    
            // POST: Vehicles/Delete/5
            [HttpPost]
            public ActionResult Delete(int id, FormCollection collection)
            {
                try
                {
                    // TODO: Add delete logic here
                    FileStream fsVehicles = null;
                    List<Vehicle> vehicles = new List<Vehicle>();
                    BinaryFormatter bfVehicles = new BinaryFormatter();
                    string strVehiclesFile = Server.MapPath("~/App_Data/Vehicles.tts");
    
                    if (!string.IsNullOrEmpty("TagNumber"))
                    {
                        if (System.IO.File.Exists(strVehiclesFile))
                        {
                            using (fsVehicles = new FileStream(strVehiclesFile, FileMode.Open, FileAccess.Read, FileShare.Read))
                            {
                                vehicles = (List<Vehicle>)bfVehicles.Deserialize(fsVehicles);
                            }
                        }
    
                        Vehicle vehicle = vehicles.Find(car => car.VehicleId == id);
    
                        vehicles.Remove(vehicle);
    
                        using (fsVehicles = new FileStream(strVehiclesFile, FileMode.Create, FileAccess.Write, FileShare.Write))
                        {
                            bfVehicles.Serialize(fsVehicles, vehicles);
                        }
                    }
    
                    return RedirectToAction("Index");
                }
                catch
                {
                    return View();
                }
            }
        }
    }
  71. In the class, right-click inside the Index() method and click Add View...
  72. Make sure the View Name has Index.
    Click Add
  73. Create the webpage as follows:
    @model IEnumerable<TrafficTicketsSystem2.Models.Vehicle>
    
    @{
        ViewBag.Title = "Cars - Vehicles";
    }
    
    <h2 class="bold maroon common-font text-center">Cars - Vehicles</h2>
    
    <table class="table table-hover common-font">
        <tr>
            <th class="text-center maroon">@Html.DisplayNameFor(model => model.VehicleId)</th>
            <th class="text-center maroon">@Html.DisplayNameFor(model => model.TagNumber)</th>
            <th class="maroon">@Html.DisplayNameFor(model => model.DriverId)</th>
            <th class="maroon">@Html.DisplayNameFor(model => model.Make)</th>
            <th class="maroon">@Html.DisplayNameFor(model => model.Model)</th>
            <th class="maroon">@Html.DisplayNameFor(model => model.VehicleYear)</th>
            <th class="maroon">@Html.DisplayNameFor(model => model.Color)</th>
            <th class="maroon">@Html.ActionLink("Register New Vehicle", "Create")</th>
        </tr>
    
        @foreach (var item in Model)
        {
        <tr>
            <td class="text-center">@Html.DisplayFor(modelItem => item.VehicleId)</td>
            <td class="text-center">@Html.DisplayFor(modelItem => item.TagNumber)</td>
            <td>@Html.DisplayFor(modelItem => item.DriverId)</td>
            <td>@Html.DisplayFor(modelItem => item.Make)</td>
            <td>@Html.DisplayFor(modelItem => item.Model)</td>
            <td>@Html.DisplayFor(modelItem => item.VehicleYear)</td>
            <td>@Html.DisplayFor(modelItem => item.Color)</td>
            <td>
                @Html.ActionLink("Edit", "Edit", new { id = item.VehicleId }) |
                    @Html.ActionLink("Details", "Details", new { id = item.VehicleId }) |
                    @Html.ActionLink("Delete", "Delete", new { id = item.VehicleId })
                </td>
        </tr>
        }
    </table>
    <hr />
  74. In the Solution Explorer, under Views, right-click Vehicles -> Add -> View...
  75. Type Details
  76. Click Add
  77. Change the document as follows:
    @model TrafficTicketsSystem2.Models.Vehicle
    
    @{
        ViewBag.Title = "Vehicle Details";
    }
    
    <h2 class="common-font bold maroon text-center">Vehicle Registration Details</h2>
    
    <hr />
    
    <div class="containment">
        <dl class="dl-horizontal common-font">
            <dt class="maroon">@Html.DisplayNameFor(model => model.VehicleId)</dt>
            <dd>@Html.DisplayFor(model => model.VehicleId)</dd>
    
            <dt class="maroon">@Html.DisplayNameFor(model => model.TagNumber)</dt>
            <dd>@Html.DisplayFor(model => model.TagNumber)</dd>
    
            <dt class="maroon">@Html.DisplayNameFor(model => model.DriverId)</dt>
            <dd>@Html.DisplayFor(model => model.DriverId)</dd>
    
            <dt class="maroon">@Html.DisplayNameFor(model => model.Make)</dt>
            <dd>@Html.DisplayFor(model => model.Make)</dd>
    
            <dt class="maroon">@Html.DisplayNameFor(model => model.Model)</dt>
            <dd>@Html.DisplayFor(model => model.Model)</dd>
    
            <dt class="maroon">@Html.DisplayNameFor(model => model.VehicleYear)</dt>
            <dd>@Html.DisplayFor(model => model.VehicleYear)</dd>
    
            <dt class="maroon">@Html.DisplayNameFor(model => model.Color)</dt>
            <dd>@Html.DisplayFor(model => model.Color)</dd>
        </dl>
    </div>
    
    <p class="text-center">
        @Html.ActionLink("Edit", "Edit", new { id = Model.VehicleId }) |
        @Html.ActionLink("Vehicles", "Index")
    </p>
  78. Click the VehiclesController.cs tab to access it
  79. In the VehiclesController class, right-click anywhere inside one of the Create() methods and click Add View...
  80. Make sure the View Name text box is displaying Create. Click Add
  81. Create the webpage as follows:
    @model TrafficTicketsSystem2.Models.Vehicle
    
    @{
        ViewBag.Title = "Create Vehicle";
    }
    
    <h2 class="common-font text-center bold maroon">Create Vehicle Registration</h2>
    
    <hr />
    
    @using (Html.BeginForm())
    {
        @Html.AntiForgeryToken()
    
        <div class="containment">
            <div class="form-horizontal common-font">
                @Html.ValidationSummary(true, "", new { @class = "text-danger" })
                <div class="form-group">
                    @Html.LabelFor(model => model.TagNumber, htmlAttributes: new { @class = "control-label col-md-5 maroon" })
                    <div class="col-md-7">
                        @Html.EditorFor(model => model.TagNumber, new { htmlAttributes = new { @class = "form-control" } })
                        @Html.ValidationMessageFor(model => model.TagNumber, "", new { @class = "text-danger" })
                    </div>
                </div>
    
                <div class="form-group">
                    <label for="drvLicNbr" class="control-label col-md-5 maroon">Owner's Drv. Lic. #</label>
                    <div class="col-md-7">
                        @Html.TextBox("DrvLicNumber", null, htmlAttributes: new { @class = "form-control", id = "drvLicNbr" })
                        @Html.ValidationMessageFor(model => model.Make, "", new { @class = "text-danger" })
                    </div>
                </div>
    
                <div class="form-group">
                    @Html.LabelFor(model => model.Make, htmlAttributes: new { @class = "control-label col-md-5 maroon" })
                    <div class="col-md-7">
                        @Html.EditorFor(model => model.Make, new { htmlAttributes = new { @class = "form-control" } })
                        @Html.ValidationMessageFor(model => model.Make, "", new { @class = "text-danger" })
                    </div>
                </div>
    
                <div class="form-group">
                    @Html.LabelFor(model => model.Model, htmlAttributes: new { @class = "control-label col-md-5 maroon" })
                    <div class="col-md-7">
                        @Html.EditorFor(model => model.Model, new { htmlAttributes = new { @class = "form-control" } })
                        @Html.ValidationMessageFor(model => model.Model, "", new { @class = "text-danger" })
                    </div>
                </div>
    
                <div class="form-group">
                    @Html.LabelFor(model => model.VehicleYear, htmlAttributes: new { @class = "control-label col-md-5 maroon" })
                    <div class="col-md-7">
                        @Html.EditorFor(model => model.VehicleYear, new { htmlAttributes = new { @class = "form-control" } })
                        @Html.ValidationMessageFor(model => model.VehicleYear, "", new { @class = "text-danger" })
                    </div>
                </div>
    
                <div class="form-group">
                    @Html.LabelFor(model => model.Color, htmlAttributes: new { @class = "control-label col-md-5 maroon" })
                    <div class="col-md-7">
                        @Html.EditorFor(model => model.Color, new { htmlAttributes = new { @class = "form-control" } })
                        @Html.ValidationMessageFor(model => model.Color, "", new { @class = "text-danger" })
                    </div>
                </div>
    
                <div class="form-group">
                    <label class="control-label col-md-6">
                        @Html.ActionLink("Vehicles", "Index")
                    </label>
                    <div class="col-md-6">
                        <input type="submit" value="Save Vehicle Registration" class="btn btn-warning" />
                    </div>
                </div>
            </div>
        </div>
    }
    
    <hr />
  82. Click the VehiclesController.cs tab to access it
  83. In the VehiclesController class, right-click anywhere inside the Edit() method and click Add View...
  84. In the Add View dialog box, make sure the View Name text box is displaying Edit. Click Add
  85. Change the document as follows:
    @model TrafficTicketsSystem2.Models.Vehicle
    
    @{
        ViewBag.Title = "Edit/Update Vehicle";
    }
    
    <h2 class="common-font text-center bold maroon">Edit/Update Vehicle Registration</h2>
    
    <hr />
    
    @using (Html.BeginForm())
    {
        @Html.AntiForgeryToken()
    
        <div class="containment">
            <div class="form-horizontal common-font">
                @Html.ValidationSummary(true, "", new { @class = "text-danger" })
                @Html.HiddenFor(model => model.VehicleId)
    
                <div class="form-group">
                    @Html.LabelFor(model => model.TagNumber, htmlAttributes: new { @class = "control-label col-md-5 maroon" })
                    <div class="col-md-7">
                        @Html.EditorFor(model => model.TagNumber, new { htmlAttributes = new { @class = "form-control" } })
                        @Html.ValidationMessageFor(model => model.TagNumber, "", new { @class = "text-danger" })
                    </div>
                </div>
    
                <div class="form-group">
                    <label for="drvLicNbr" class="control-label col-md-5 maroon">Owner's Drv. Lic. #</label>
                    <div class="col-md-7">
                        @Html.TextBox("DrvLicNumber", null, htmlAttributes: new { @class = "form-control", id = "drvLicNbr" })
                        @Html.ValidationMessageFor(model => model.Make, "", new { @class = "text-danger" })
                    </div>
                </div>
    
                <div class="form-group">
                    @Html.LabelFor(model => model.Make, htmlAttributes: new { @class = "control-label col-md-5 maroon" })
                    <div class="col-md-7">
                        @Html.EditorFor(model => model.Make, new { htmlAttributes = new { @class = "form-control" } })
                        @Html.ValidationMessageFor(model => model.Make, "", new { @class = "text-danger" })
                    </div>
                </div>
    
                <div class="form-group">
                    @Html.LabelFor(model => model.Model, htmlAttributes: new { @class = "control-label col-md-5 maroon" })
                    <div class="col-md-7">
                        @Html.EditorFor(model => model.Model, new { htmlAttributes = new { @class = "form-control" } })
                        @Html.ValidationMessageFor(model => model.Model, "", new { @class = "text-danger" })
                    </div>
                </div>
    
                <div class="form-group">
                    @Html.LabelFor(model => model.VehicleYear, htmlAttributes: new { @class = "control-label col-md-5 maroon" })
                    <div class="col-md-7">
                        @Html.EditorFor(model => model.VehicleYear, new { htmlAttributes = new { @class = "form-control" } })
                        @Html.ValidationMessageFor(model => model.VehicleYear, "", new { @class = "text-danger" })
                    </div>
                </div>
    
                <div class="form-group">
                    @Html.LabelFor(model => model.Color, htmlAttributes: new { @class = "control-label col-md-5 maroon" })
                    <div class="col-md-7">
                        @Html.EditorFor(model => model.Color, new { htmlAttributes = new { @class = "form-control" } })
                        @Html.ValidationMessageFor(model => model.Color, "", new { @class = "text-danger" })
                    </div>
                </div>
    
                <div class="form-group">
                    <label class="control-label col-md-6">
                        @Html.ActionLink("Vehicles", "Index")
                    </label>
                    <div class="col-md-6">
                        <input type="submit" value="Update Vehicle Registration" class="btn btn-warning" />
                    </div>
                </div>
            </div>
        </div>
    }
    
    <hr />
  86. In the Solution Explorer, under Views, right-click Vehicles -> Add -> View...
  87. Type Delete as the name of the view
  88. Click Add
  89. Change the document as follows:
    @model TrafficTicketsSystem2.Models.Vehicle
    
    @{
        ViewBag.Title = "Delete Vehicle";
    }
    
    <h2 class="maroon common-font text-center bold">Delete Vehicle Registration</h2>
    
    <hr />
    
    <div class="containment">
        <dl class="dl-horizontal common-font">
            <dt class="maroon">@Html.DisplayNameFor(model => model.VehicleId)</dt>
            <dd>@Html.DisplayFor(model => model.VehicleId)</dd>
    
            <dt class="maroon">@Html.DisplayNameFor(model => model.TagNumber)</dt>
            <dd>@Html.DisplayFor(model => model.TagNumber)</dd>
    
            <dt class="maroon">@Html.DisplayNameFor(model => model.DriverId)</dt>
            <dd>@Html.DisplayFor(model => model.DriverId)</dd>
    
            <dt class="maroon">@Html.DisplayNameFor(model => model.Make)</dt>
            <dd>@Html.DisplayFor(model => model.Make)</dd>
    
            <dt class="maroon">@Html.DisplayNameFor(model => model.Model)</dt>
            <dd>@Html.DisplayFor(model => model.Model)</dd>
    
            <dt class="maroon">@Html.DisplayNameFor(model => model.VehicleYear)</dt>
            <dd>@Html.DisplayFor(model => model.VehicleYear)</dd>
    
            <dt class="maroon">@Html.DisplayNameFor(model => model.Color)</dt>
            <dd>@Html.DisplayFor(model => model.Color)</dd>
        </dl>
    
        <h3 class="common-font text-center bold maroon">Are you sure you want to delete this vehicle registration?</h3>
    
        @using (Html.BeginForm())
        {
            @Html.AntiForgeryToken()
    
            <div class="form-actions no-color">
                <input type="submit" value="Delete Vehicle Registration" class="btn btn-warning" /> ::
                @Html.ActionLink("Cars - Vehicles", "Index", null, htmlAttributes: new { @class = "btn btn-warning" })
            </div>
        }
    </div>
    
    <hr />
  90. Click the VehiclesController.cs tab to access it
  91. To execute the application, on the main menu, click Debug and click Start Without Debugging
  92. Click the DRIVERS link
  93. Click Issue New Driver's License:

    Text Box

  94. Create a few records as follows:

    Drv. Lic. # First Name Last Name Address City County State ZIP Code
    296 840 681 Simon Havers 1884 Stewart Ln Kittanning Armstrong PA 15638
    273-79-4157 Terrence McConnell 8304 Polland Str Meadowview Washington VA 24361
    A402-630-468 Patrick Atherton 10744 Quincy Blvd Cumberland Allegany MD 21502
    C-684-394-527 Sarah Cuchran 10804 Euton Rd Shawnee Land   VA 24450
    72938468 Victoria Huband 3958 Lubber Court Middletown New Castle DE 19709
    E-928-374-025 Jeannette Eubanks 794 Arrowhead Ave Vienna Dorchester MD 21869
    851608526 Patrick Whalley 10227 Woodrow Rd Shelbyville Bedford TN 38561
    593 804 597 George Higgins 884 Willingmont Drv Krumsville Berks PA 19530
    W639-285-940 David Woodbank 9703 Abington Ave Easton Talbot MD 21601
    S-283-942-646 Emilie Sainsbury 4048 Utah Rd Denville Morris NJ 07961
    860586175 Kelly Murray 8622 Rutger Farms Str Rutger Farms Macon TN 37122

    Label

  95. Click the VEHICLES link:

    Linked Lists - Traffic Tickets Violations

  96. Click Register New Vehicle:

    Linked Lists - Vehicles

  97. Register a few vehicles using the following values:

    Tag # Drv. Lic. # Make Model Year Color
    8DE9275 296 840 681 Ford Focus SF 2000 Gray
    KLT4805 593 804 597 Toyota Corolla LE 2016 Maroon
    5293WPL C-684-394-527 Ford Transit Connect 2018 Navy
    FKEWKR 72938468 Toyota Camry 2010 Silver
    MKR9374 273-79-4157 Lincoln MKT 2018 Black
    KAS9314 W639-285-940 Cadillac Escalade 2008 Cream
    HAK3936 S-283-942-646 Chrysler Crossfire 2006 Red
    PER2849 296 840 681 Buick LeSabre 2012 Silver
    MWH4685 851608526 Honda Accord 1998 Blue
    971384 E-928-374-025 BMW 325i 2015 Navy
    394815 273-79-4157 Jeep Wrangler Sahara 1996 Black

    Linked List - Traffic Tickets System - Vehicles

  98. Click the VIOLATIONS TYPES link:

    Linked Lists - Getting Each Node of a Linked List

  99. On the webpage, click Create New Violation Type:

    Linked Lists - Getting Each Node of a Linked List

  100. Create some records as follows::

    Violation Name Description
    Speed The vehicle drove at a speed significantly above the speed limit. The laws in this state require that every non-emergency and non-utility vehicle drives at or below the posted speed limit (or at or below the default speed regulation where the speed is not clearly posted).
    Stop Sign The vehicle did not stop at the Stop sign. The law in our state indicates every non-emergency vehicle to completely stop at every Stop sign, regardless of the presence or absence of incoming or adjacent vehicles.
    Red Light Steady The vehicle drove through a steady red light. The law in our state requires that when a vehicle approaches a steady red light, it must completely stop and wait for the light to change to green.
    Red Light Flashing The vehicle drove through a red light that was flashing (or blinking). The laws in this state require that if a vehicle comes to a flashing red light, whether it is at an intersection or not, the vehicle must first stop complete, the drive must observe around for pedestrians, animals, and other cars, and then cautiously.
    Red Light Right Turn The vehicle turns to the right without stopping. The laws in our state require that, when a vehicle reaches a traffic light and wants to make a right turn, if the light is red, regardless of any presence or not of another vehicle or pedestrian, the vehicle must first stop completely, and then make the right turn.

    Linked Lists - Getting Each Node of a Linked List

  101. Close the browser and return to your programming environment

Passing an Identifier to a Route

The last argument of the RouteCollection.MapRoute() method, identified as defaults, is an anonymous object. Therefore, define it using the new operator and curly brackets. In the brackets, use each of the factors from the url argument and assign the appropriate value. The value you provide is not case-sensitive. This means that in this case, academics is the same as Academics and is the same as ACADEMICS. Here is an example:

new { controller = "ACADEMICS", . . . }

When you have specified this name, when the webserver is asked to display the webpage, the compiler will look for a controller that has that name in the current Web project. If there is not a controller with that name, the browser will display an error as "The resource cannot be found". Therefore, make sure you provide an existing controller name.

After assigning the name of a controller, specify the name of the desired action to access. If the controller exists, the compiler will look for the indicated action method in the controller class. If the action method doesn't exist in the controller, the browser will display an error as "The resource cannot be found". Therefore, make sure you assign an existing action method to action. Here is an example:

new { controller = "ACADEMICS", "Admission", . . . }

If you are not planning to use an identifier in the address, assign UrlParameter.Optional to Id. If you are planning to use an identifier in the address, assign it to Id. When the webserver is asked to display the webpage, if it finds an identifier with the indicated value, it would display it.

To make your code easy to read, you can apply each argument to the name of the corresponding argument used in the syntax of the method. Here is an example:

using System.Web.Mvc;
using System.Web.Routing;

namespace Exercise1
{
    public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.MapRoute(defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
                            url: "{controller}/{action}/{id}",
                            name: "Detailed Report");
        }
    }
}

In the action method that handles the route, write code to select a record. Normally, to select a record, you would call a method of the class that handles the collection of records. That collection should (must) provide the means to use the value passed as argument to select a record that will be uniquely identified by that value. Once you have selected the record, you can display it in a view.

Practical LearningPractical Learning: Creating a Controller

  1. In the Solution Explorer, right-click Controllers -> Add -> New Scaffolded Item...
  2. In the middle list of the Add Scaffold dialog box, make sure MVC 5 Controller With Read/Write Actions is selected. Click Add
  3. Type TrafficViolations to get TrafficViolationsController
  4. Click Add
  5. Change the TrafficViolationsController class as follows:
    using System;
    using System.IO;
    using System.Net;
    using System.Web.Mvc;
    using System.Collections.Generic;
    using TrafficTicketsSystem2.Models;
    using System.Runtime.Serialization.Formatters.Binary;
    
    namespace TrafficTicketsSystem2.Controllers
    {
        public class TrafficViolationsController : Controller
        {
            // GET: TrafficViolations
            public ActionResult Index()
            {
                FileStream fsTrafficViolations = null;
                BinaryFormatter bfTrafficViolations = new BinaryFormatter();
                List<TrafficViolation> violations = new List<TrafficViolation>();
    
                string strTrafficViolationsFile = Server.MapPath("~/App_Data/TrafficViolations.tts");
    
                if (System.IO.File.Exists(strTrafficViolationsFile))
                {
                    using (fsTrafficViolations = new FileStream(strTrafficViolationsFile, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        violations = (List<TrafficViolation>)bfTrafficViolations.Deserialize(fsTrafficViolations);
                    }
                }
    
                return View(violations);
            }
    
            // GET: TrafficViolations/Details/5
            public ActionResult Details(int? id)
            {
                if (id == null)
                {
                    return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
                }
    
                TrafficViolation violation = null;
                FileStream fsTrafficViolations = null;
                BinaryFormatter bfTrafficViolations = new BinaryFormatter();
                List<TrafficViolation> violations = new List<TrafficViolation>();
                string strTrafficViolationsFile = Server.MapPath("~/App_Data/TrafficViolations.tts");
    
                if (System.IO.File.Exists(strTrafficViolationsFile))
                {
                    using (fsTrafficViolations = new FileStream(strTrafficViolationsFile, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        violations = (List<TrafficViolation>)bfTrafficViolations.Deserialize(fsTrafficViolations);
                    }
    
                    violation = violations.Find(tv => tv.TrafficViolationId == id);
                }
    
                if (violation == null)
                {
                    return HttpNotFound();
                }
    
                return View(violation);
            }
    
            // GET: TrafficViolations/Create
            public ActionResult Create()
            {
                Random rndNumber = new Random();
                BinaryFormatter bfCameras = new BinaryFormatter();
                FileStream fsCameras = null, fsViolationsTypes = null;
                List<Camera> cameras = new List<Camera>();
                BinaryFormatter bfViolationsTypes = new BinaryFormatter();
                string strCamerasFile = Server.MapPath("~/App_Data/Cameras.tts");
                List<ViolationType> violationsTypes = new List<ViolationType>();
                string strViolationsTypesFile = Server.MapPath("~/App_Data/ViolationsTypes.tts");
    
                List<SelectListItem> itemsCameras = new List<SelectListItem>();
                List<SelectListItem> paymentsStatus = new List<SelectListItem>();
                List<SelectListItem> itemsPhotoAvailable = new List<SelectListItem>();
                List<SelectListItem> itemsVideoAvailable = new List<SelectListItem>();
                List<SelectListItem> itemsViolationsTypes = new List<SelectListItem>();
    
                if (System.IO.File.Exists(strCamerasFile))
                {
                    using (fsCameras = new FileStream(strCamerasFile, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        cameras = (List<Camera>)bfCameras.Deserialize(fsCameras);
    
                        foreach (Camera cmr in cameras)
                        {
                            itemsCameras.Add(new SelectListItem() { Text = cmr.CameraNumber + " - " + cmr.Location, Value = cmr.CameraNumber });
                        }
                    }
                }
    
                if (System.IO.File.Exists(strViolationsTypesFile))
                {
                    using (fsViolationsTypes = new FileStream(strViolationsTypesFile, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        violationsTypes = (List<ViolationType>)bfViolationsTypes.Deserialize(fsViolationsTypes);
    
                        foreach (ViolationType vt in violationsTypes)
                        {
                            itemsViolationsTypes.Add(new SelectListItem() { Text = vt.ViolationName, Value = vt.ViolationName });
                        }
                    }
                }
    
                itemsPhotoAvailable.Add(new SelectListItem() { Value = "Unknown" });
                itemsPhotoAvailable.Add(new SelectListItem() { Text = "No", Value = "No" });
                itemsPhotoAvailable.Add(new SelectListItem() { Text = "Yes", Value = "Yes" });
                itemsVideoAvailable.Add(new SelectListItem() { Value = "Unknown" });
                itemsVideoAvailable.Add(new SelectListItem() { Text = "No", Value = "No" });
                itemsVideoAvailable.Add(new SelectListItem() { Text = "Yes", Value = "Yes" });
    
                paymentsStatus.Add(new SelectListItem() { Value = "Unknown" });
                paymentsStatus.Add(new SelectListItem() { Text = "Pending", Value = "Pending" });
                paymentsStatus.Add(new SelectListItem() { Text = "Rejected", Value = "Rejected" });
                paymentsStatus.Add(new SelectListItem() { Text = "Cancelled", Value = "Cancelled" });
                paymentsStatus.Add(new SelectListItem() { Text = "Paid Late", Value = "Paid Late" });
                paymentsStatus.Add(new SelectListItem() { Text = "Paid On Time", Value = "Paid On Time" });
    
                ViewBag.CameraNumber = itemsCameras;
                ViewBag.PaymentStatus = paymentsStatus;
                ViewBag.PhotoAvailable = itemsPhotoAvailable;
                ViewBag.VideoAvailable = itemsVideoAvailable;
                ViewBag.ViolationName = itemsViolationsTypes;
                ViewBag.TrafficViolationNumber = rndNumber.Next(10000001, 99999999);
    
                return View();
            }
    
            // POST: TrafficViolations/Create
            [HttpPost]
            public ActionResult Create(FormCollection collection)
            {
                try
                {
                    // TODO: Add insert logic here
                    int trafficViolationId = 0;
                    bool vehicleFound = false;
                    List<Camera> cameras = new List<Camera>();
                    List<Vehicle> vehicles = new List<Vehicle>();
                    BinaryFormatter bfCameras = new BinaryFormatter();
                    BinaryFormatter bfDrivers = new BinaryFormatter();
                    int cameraId = 0, vehicleId = 0, violationTypeId = 0;
                    BinaryFormatter bfViolationsTypes = new BinaryFormatter();
                    List<ViolationType> violationsTypes = new List<ViolationType>();
                    BinaryFormatter bfTrafficViolations = new BinaryFormatter();
                    string strCamerasFile = Server.MapPath("~/App_Data/Cameras.tts");
                    string strVehiclesFile = Server.MapPath("~/App_Data/Vehicles.tts");
                    List<TrafficViolation> trafficViolations = new List<TrafficViolation>();
                    string strViolationsTypesFile = Server.MapPath("~/App_Data/ViolationsTypes.tts");
                    string strTrafficViolationsFile = Server.MapPath("~/App_Data/TrafficViolations.tts");
                    FileStream fsTrafficViolations = null, fsVehicles = null, fsCameras = null, fsViolationsTypes = null;
    
    
                    // Open the file for the cameras
                    if (System.IO.File.Exists(strCamerasFile))
                    {
                        using (fsCameras = new FileStream(strCamerasFile, FileMode.Open, FileAccess.Read, FileShare.Read))
                        {
                            /* After opening the file, get the list of cameras from it
                             * and store it in the List<Camera> variable. */
                            cameras = (List<Camera>)bfCameras.Deserialize(fsCameras);
    
                            // Check each record
                            foreach (Camera cmr in cameras)
                            {
                                /* When you get to a record, find out if its CameraNumber value 
                                 * is the same as the camera number the user selected. */
                                if (cmr.CameraNumber == collection["CameraNumber"])
                                {
                                    /* If you find a record with that tag number, make a note. */
                                    cameraId = cmr.CameraId;
                                    break;
                                }
                            }
                        }
                    }
    
                    // Open the file for the vehicles
                    if (System.IO.File.Exists(strVehiclesFile))
                    {
                        using (fsVehicles = new FileStream(strVehiclesFile, FileMode.Open, FileAccess.Read, FileShare.Read))
                        {
                            /* After opening the file, get the list of vehicles from it
                             * and store it in the List<Vehicle> variable. */
                            vehicles = (List<Vehicle>)bfDrivers.Deserialize(fsVehicles);
    
                            // Check each record
                            foreach (Vehicle car in vehicles)
                            {
                                /* When you get to a record, find out if its TagNumber value 
                                 * is the same as the tag number the user provided. */
                                if (car.TagNumber == collection["TagNumber"])
                                {
                                    /* If you find a record with that tag number, make a note. */
                                    vehicleId = car.VehicleId;
                                    vehicleFound = true;
                                    break;
                                }
                            }
                        }
                    }
                    
                    if (System.IO.File.Exists(strViolationsTypesFile))
                    {
                        using (fsViolationsTypes = new FileStream(strViolationsTypesFile, FileMode.Open, FileAccess.Read, FileShare.Read))
                        {
                            violationsTypes = (List<ViolationType>)bfViolationsTypes.Deserialize(fsViolationsTypes);
                            
                            foreach (ViolationType vt in violationsTypes)
                            {
                                if (vt.ViolationName == collection["ViolationName"])
                                {
                                    violationTypeId = vt.ViolationTypeId;
                                    break;
                                }
                            }
                        }
                    }
    
                    /* If the vehicleFound is true, it means the car that committed the infraction has been identified. */
                    if (vehicleFound == true)
                    {
                        // Check whether a file for traffic violations was created already.
                        if (System.IO.File.Exists(strTrafficViolationsFile))
                        {
                            // If a file for traffic violations exists already, open it ...
                            using (fsTrafficViolations = new FileStream(strTrafficViolationsFile, FileMode.Open, FileAccess.Read, FileShare.Read))
                            {
                                // ... and store the records in our trafficViolations variable
                                trafficViolations = (List<TrafficViolation>)bfTrafficViolations.Deserialize(fsTrafficViolations);
                            }
    
                            foreach (TrafficViolation tv in trafficViolations)
                                trafficViolationId = tv.TrafficViolationId;
                        }
    
                        trafficViolationId++;
    
                        TrafficViolation citation = new TrafficViolation()
                        {
                            TrafficViolationId = trafficViolationId,
                            TrafficViolationNumber = int.Parse(collection["TrafficViolationNumber"]),
                            CameraId = cameraId,
                            VehicleId = vehicleId,
                            ViolationTypeId = violationTypeId,
                            ViolationDate = collection["ViolationDate"],
                            ViolationTime = collection["ViolationTime"],
                            PhotoAvailable = collection["PhotoAvailable"],
                            VideoAvailable = collection["VideoAvailable"],
                            PaymentDueDate = collection["PaymentDueDate"],
                            PaymentDate = collection["PaymentDate"],
                            PaymentAmount = double.Parse(collection["PaymentAmount"]),
                            PaymentStatus = collection["PaymentStatus"]
                        };
    
                        trafficViolations.Add(citation);
    
                        using (fsTrafficViolations = new FileStream(strTrafficViolationsFile, FileMode.Create, FileAccess.Write, FileShare.Write))
                        {
                            bfTrafficViolations.Serialize(fsTrafficViolations, trafficViolations);
                        }
                    }
    
                    return RedirectToAction("Index");
                }
                catch
                {
                    return View();
                }
            }
    
            // GET: TrafficViolations/Edit/5
            public ActionResult Edit(int ? id)
            {
                if (id == null)
                {
                    return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
                }
    
                TrafficViolation violation = null;
                FileStream fsTrafficViolations = null;
                BinaryFormatter bfTrafficViolations = new BinaryFormatter();
                List<TrafficViolation> violations = new List<TrafficViolation>();
                string strTrafficViolationsFile = Server.MapPath("~/App_Data/TrafficViolations.tts");
    
                if (System.IO.File.Exists(strTrafficViolationsFile))
                {
                    using (fsTrafficViolations = new FileStream(strTrafficViolationsFile, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        violations = (List<TrafficViolation>)bfTrafficViolations.Deserialize(fsTrafficViolations);
                    }
    
                    violation = violations.Find(viol => viol.TrafficViolationId == id);
    
                    List<SelectListItem> itemsCameras = new List<SelectListItem>();
                    List<SelectListItem> paymentsStatus = new List<SelectListItem>();
                    List<SelectListItem> itemsPhotoAvailable = new List<SelectListItem>();
                    List<SelectListItem> itemsVideoAvailable = new List<SelectListItem>();
                    List<SelectListItem> itemsViolationsTypes = new List<SelectListItem>();
    
                    List<Camera> cameras = new List<Camera>();
                    BinaryFormatter bfCameras = new BinaryFormatter();
                    FileStream fsCameras = null, fsViolationsTypes = null;
                    string strCamerasFile = Server.MapPath("~/App_Data/Cameras.tts");
    
                    if (System.IO.File.Exists(strCamerasFile))
                    {
                        using (fsCameras = new FileStream(strCamerasFile, FileMode.Open, FileAccess.Read, FileShare.Read))
                        {
                            cameras = (List<Camera>)bfCameras.Deserialize(fsCameras);
    
    
                            foreach (Camera cmr in cameras)
                            {
                                itemsCameras.Add(new SelectListItem() { Text = cmr.CameraNumber, Value = cmr.CameraNumber, Selected = (violation.CameraId == cmr.CameraId) });
                            }
                        }
                    }
    
                    BinaryFormatter bfViolationsTypes = new BinaryFormatter();
                    List<ViolationType> violationsTypes = new List<ViolationType>();
                    string strViolationsTypesFile = Server.MapPath("~/App_Data/ViolationsTypes.tts");
    
                    if (System.IO.File.Exists(strViolationsTypesFile))
                    {
                        using (fsViolationsTypes = new FileStream(strViolationsTypesFile, FileMode.Open, FileAccess.Read, FileShare.Read))
                        {
                            violationsTypes = (List<ViolationType>)bfViolationsTypes.Deserialize(fsViolationsTypes);
    
                            foreach (ViolationType vt in violationsTypes)
                            {
                                itemsViolationsTypes.Add(new SelectListItem() { Text = vt.ViolationName, Value = vt.ViolationName, Selected = (violation.ViolationTypeId == vt.ViolationTypeId) });
                            }
                        }
                    }
    
                    itemsPhotoAvailable.Add(new SelectListItem() { Value = "Unknown" });
                    itemsPhotoAvailable.Add(new SelectListItem() { Text = "No", Value = "No", Selected = (violation.PhotoAvailable == "No") });
                    itemsPhotoAvailable.Add(new SelectListItem() { Text = "Yes", Value = "Yes", Selected = (violation.PhotoAvailable == "Yes") });
                    itemsVideoAvailable.Add(new SelectListItem() { Value = "Unknown" });
                    itemsVideoAvailable.Add(new SelectListItem() { Text = "No", Value = "No", Selected = (violation.VideoAvailable == "No") });
                    itemsVideoAvailable.Add(new SelectListItem() { Text = "Yes", Value = "Yes", Selected = (violation.VideoAvailable == "Yes") });
    
                    paymentsStatus.Add(new SelectListItem() { Value = "Unknown" });
                    paymentsStatus.Add(new SelectListItem() { Text = "Pending", Value = "Pending", Selected = (violation.PaymentStatus == "Pending") });
                    paymentsStatus.Add(new SelectListItem() { Text = "Rejected", Value = "Rejected", Selected = (violation.PaymentStatus == "Rejected") });
                    paymentsStatus.Add(new SelectListItem() { Text = "Cancelled", Value = "Cancelled", Selected = (violation.PaymentStatus == "Cancelled") });
                    paymentsStatus.Add(new SelectListItem() { Text = "Paid Late", Value = "Paid Late", Selected = (violation.PaymentStatus == "Paid Late") });
                    paymentsStatus.Add(new SelectListItem() { Text = "Paid On Time", Value = "Paid On Time", Selected = (violation.PaymentStatus == "Paid On Time") });
    
                    Vehicle car = null;
                    FileStream fsVehicles = null;
                    string strTagNumber = string.Empty;
                    List<Vehicle> vehicles = new List<Vehicle>();
                    BinaryFormatter bfVehicles = new BinaryFormatter();
                    string strVehiclesFile = Server.MapPath("~/App_Data/Vehicles.tts");
    
                    if (System.IO.File.Exists(strVehiclesFile))
                    {
                        using (fsVehicles = new FileStream(strVehiclesFile, FileMode.Open, FileAccess.Read, FileShare.Read))
                        {
                            vehicles = (List<Vehicle>)bfVehicles.Deserialize(fsVehicles);
                        }
    
                        car = vehicles.Find(engine => engine.VehicleId == violation.VehicleId);
                    }
    
                    ViewBag.CameraNumber = itemsCameras;
                    ViewBag.PaymentStatus = paymentsStatus;
                    ViewBag.TagNumber = car.TagNumber;
                    ViewBag.PaymentDate = violation.PaymentDate;
                    ViewBag.ViolationName = itemsViolationsTypes;
                    ViewBag.PhotoAvailable = itemsPhotoAvailable;
                    ViewBag.VideoAvailable = itemsVideoAvailable;
                    ViewBag.PaymentAmount = violation.PaymentAmount;
                    ViewBag.ViolationDate = violation.ViolationDate;
                    ViewBag.ViolationTime = violation.ViolationTime;
                    ViewBag.PaymentDueDate = violation.PaymentDueDate;
                    ViewBag.TrafficViolationNumber = violation.TrafficViolationNumber;
                }
    
                if (violation == null)
                {
                    return HttpNotFound();
                }
    
                return View(violation);
            }
    
            // POST: TrafficViolations/Edit/5
            [HttpPost]
            public ActionResult Edit(int id, FormCollection collection)
            {
                try
                {
                    // TODO: Add update logic here
                    FileStream fsTrafficViolations = null;
                    TrafficViolation violation = new TrafficViolation();
                    BinaryFormatter bfTrafficViolations = new BinaryFormatter();
                    List<TrafficViolation> violations = new List<TrafficViolation>();
                    string strTrafficViolationsFile = Server.MapPath("~/App_Data/TrafficViolations.tts");
    
                    if (!string.IsNullOrEmpty("TrafficViolationNumber"))
                    {
                        if (System.IO.File.Exists(strTrafficViolationsFile))
                        {
                            using (fsTrafficViolations = new FileStream(strTrafficViolationsFile, FileMode.Open, FileAccess.Read, FileShare.Read))
                            {
                                violations = (List<TrafficViolation>)bfTrafficViolations.Deserialize(fsTrafficViolations);
                            }
                        }
    
                        violation = violations.FindLast(viol => viol.TrafficViolationId == id);
    
                        int cameraId = 0;
                        FileStream fsCameras = null;
                        List<Camera> cameras = new List<Camera>();
                        BinaryFormatter bfCameras = new BinaryFormatter();
                        string strCamerasFile = Server.MapPath("~/App_Data/Cameras.tts");
    
                        if (System.IO.File.Exists(strCamerasFile))
                        {
                            using (fsCameras = new FileStream(strCamerasFile, FileMode.Open, FileAccess.Read, FileShare.Read))
                            {
                                cameras = (List<Camera>)bfCameras.Deserialize(fsCameras);
                            }
    
                            foreach(Camera cmr in cameras)
                            {
                                if(cmr.CameraNumber == collection["CameraNumber"])
                                {
                                    cameraId = cmr.CameraId;
                                    break;
                                }
                            }
                        }
    
                        int vehicleId = 0;
                        FileStream fsVehicles = null;
                        List<Vehicle> vehicles = new List<Vehicle>();
                        BinaryFormatter bfVehicles = new BinaryFormatter();
                        string strVehiclesFile = Server.MapPath("~/App_Data/Vehicles.tts");
    
                        if (System.IO.File.Exists(strVehiclesFile))
                        {
                            using (fsVehicles = new FileStream(strVehiclesFile, FileMode.Open, FileAccess.Read, FileShare.Read))
                            {
                                vehicles = (List<Vehicle>)bfVehicles.Deserialize(fsVehicles);
                            }
    
                            foreach(Vehicle car in vehicles)
                            {
                                if(car.TagNumber == collection["TagNumber"])
                                {
                                    vehicleId = car.VehicleId;
                                    break;
                                }
                            }
                        }
    
                        int violationTypeId = 0;
                        FileStream fsViolationsTypes = null;
                        BinaryFormatter bfViolationsTypes = new BinaryFormatter();
                        List<ViolationType> violationsTypes = new List<ViolationType>();
                        string strViolationsTypesFile = Server.MapPath("~/App_Data/ViolationsTypes.tts");
    
                        if (System.IO.File.Exists(strViolationsTypesFile))
                        {
                            using (fsViolationsTypes = new FileStream(strViolationsTypesFile, FileMode.Open, FileAccess.Read, FileShare.Read))
                            {
                                violationsTypes = (List<ViolationType>)bfViolationsTypes.Deserialize(fsViolationsTypes);
                            }
    
                            foreach(ViolationType vt in violationsTypes)
                            {
                                if(vt.ViolationName == collection["ViolationName"])
                                {
                                    violationTypeId = vt.ViolationTypeId;
                                    break;
                                }
                            }
                        }
    
                        violation.TrafficViolationNumber = int.Parse(collection["TrafficViolationNumber"]);
                        violation.CameraId = cameraId;
                        violation.VehicleId = vehicleId;
                        violation.ViolationTypeId = violationTypeId;
                        violation.ViolationDate = collection["ViolationDate"];
                        violation.ViolationTime = collection["ViolationTime"];
                        violation.PhotoAvailable = collection["PhotoAvailable"];
                        violation.VideoAvailable = collection["VideoAvailable"];
                        violation.PaymentDueDate = collection["PaymentDueDate"];
                        violation.PaymentDate = collection["PaymentDate"];
                        violation.PaymentAmount = double.Parse(collection["PaymentAmount"]);
                        violation.PaymentStatus = collection["PaymentStatus"];
    
                        using (fsTrafficViolations = new FileStream(strTrafficViolationsFile, FileMode.Create, FileAccess.Write, FileShare.Write))
                        {
                            bfTrafficViolations.Serialize(fsTrafficViolations, violations);
                        }
                    }
    
                    return RedirectToAction("Index");
                }
                catch
                {
                    return View();
                }
            }
    
            // GET: TrafficViolations/Delete/5
            public ActionResult Delete(int? id)
            {
                if (id == null)
                {
                    return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
                }
    
                TrafficViolation violation = null;
                FileStream fsTrafficViolations = null;
                BinaryFormatter bfTrafficViolations = new BinaryFormatter();
                List<TrafficViolation> violations = new List<TrafficViolation>();
                string strTrafficViolationsFile = Server.MapPath("~/App_Data/TrafficViolations.tts");
    
                if (System.IO.File.Exists(strTrafficViolationsFile))
                {
                    using (fsTrafficViolations = new FileStream(strTrafficViolationsFile, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        violations = (List<TrafficViolation>)bfTrafficViolations.Deserialize(fsTrafficViolations);
                    }
    
                    violation = violations.Find(tv => tv.TrafficViolationId == id);
                }
    
                if (violation == null)
                {
                    return HttpNotFound();
                }
    
                return View(violation);
            }
    
            // POST: TrafficViolations/Delete/5
            [HttpPost]
            public ActionResult Delete(int id, FormCollection collection)
            {
                try
                {
                    // TODO: Add delete logic here
                    FileStream fsTrafficViolations = null;
                    TrafficViolation violation = new TrafficViolation();
                    BinaryFormatter bfTrafficViolations = new BinaryFormatter();
                    List<TrafficViolation> violations = new List<TrafficViolation>();
                    string strTrafficViolationsFile = Server.MapPath("~/App_Data/TrafficViolations.tts");
    
                    if (!string.IsNullOrEmpty("TrafficViolationNumber"))
                    {
                        if (System.IO.File.Exists(strTrafficViolationsFile))
                        {
                            using (fsTrafficViolations = new FileStream(strTrafficViolationsFile, FileMode.Open, FileAccess.Read, FileShare.Read))
                            {
                                violations = (List<TrafficViolation>)bfTrafficViolations.Deserialize(fsTrafficViolations);
                            }
                        }
    
                        TrafficViolation tv = violations.Find(viol => viol.TrafficViolationId == id);
    
                        violations.Remove(tv);
    
                        using (fsTrafficViolations = new FileStream(strTrafficViolationsFile, FileMode.Create, FileAccess.Write, FileShare.Write))
                        {
                            bfTrafficViolations.Serialize(fsTrafficViolations, violations);
                        }
                    }
    
                    return RedirectToAction("Index");
                }
                catch
                {
                    return View();
                }
            }
    
            /* This function takes the available status of a photo and video taken during the traffic violation.
               The function returns a sentence that will instruct the driver about how to view the photo or video or the violation. */
            private string GetPhotoVideoOptions(string photo, string video)
            {
                var sentence = string.Empty;
                var pvAvailable = "No";
    
                if (photo == "Yes")
                {
                    if (video == "Yes")
                    {
                        pvAvailable = "Yes";
                        sentence = "To view the photo and/or video";
                    }
                    else
                    {
                        pvAvailable = "Yes";
                        sentence = "To see a photo";
                    }
                }
                else
                { // if (photo == "No")
                    if (video == "Yes")
                    {
                        pvAvailable = "Yes";
                        sentence = "To review a video";
                    }
                    else
                    {
                        pvAvailable = "No";
                    }
                }
    
                if (pvAvailable == "No")
                    return "There is no photo or video available of this infraction but the violation was committed.";
                else
                    return sentence + " of this violation, please access http://www.trafficviolationsmedia.com. In the form, enter the citation number and click Submit.";
            }
    
            // GET: Drivers/Citation/
            public ActionResult Citation(int id)
            {
                FileStream fsTrafficViolations = null;
                BinaryFormatter bfTrafficViolations = new BinaryFormatter();
                List<TrafficViolation> violations = new List<TrafficViolation>();
                string strTrafficViolationsFile = Server.MapPath("~/App_Data/TrafficViolations.tts");
    
                if (System.IO.File.Exists(strTrafficViolationsFile))
                {
                    using (fsTrafficViolations = new FileStream(strTrafficViolationsFile, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        violations = (List<TrafficViolation>)bfTrafficViolations.Deserialize(fsTrafficViolations);
                    }
    
                    TrafficViolation violation = violations.Find(viol => viol.TrafficViolationId == id);
    
                    ViewBag.TrafficViolationNumber = violation.TrafficViolationNumber;
    
                    ViewBag.ViolationDate = violation.ViolationDate;
                    ViewBag.ViolationTime = violation.ViolationTime;
                    ViewBag.PaymentAmount = violation.PaymentAmount.ToString("C");
                    ViewBag.PaymentDueDate = violation.PaymentDueDate;
    
                    ViewBag.PhotoVideo = GetPhotoVideoOptions(violation.PhotoAvailable, violation.VideoAvailable);
    
                    FileStream fsViolationsTypes = null;
                    ViolationType category = new ViolationType();
                    BinaryFormatter bfViolationsTypes = new BinaryFormatter();
                    List<ViolationType> violationsTypes = new List<ViolationType>();
                    string strViolationsTypesFile = Server.MapPath("~/App_Data/ViolationsTypes.tts");
    
                    if (System.IO.File.Exists(strViolationsTypesFile))
                    {
                        using (fsViolationsTypes = new FileStream(strViolationsTypesFile, FileMode.Open, FileAccess.Read, FileShare.Read))
                        {
                            violationsTypes = (List<ViolationType>)bfViolationsTypes.Deserialize(fsViolationsTypes);
                        }
                        
                        ViolationType type = violationsTypes.Find(cat => cat.ViolationTypeId == violation.ViolationTypeId);
                        ViewBag.ViolationName = type.ViolationName;
                        ViewBag.ViolationDescription = type.Description;
                    }
    
                    FileStream fsVehicles = null;
                    BinaryFormatter bfVehicles = new BinaryFormatter();
                    List<Vehicle> vehicles = new List<Vehicle>();
    
                    string strVehiclesFile = Server.MapPath("~/App_Data/Vehicles.tts");
    
                    using (fsVehicles = new FileStream(strVehiclesFile, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        vehicles = (List<Vehicle>)bfVehicles.Deserialize(fsVehicles);
                    }
    
                    Vehicle vehicle = vehicles.Find(car => car.VehicleId == violation.VehicleId);
    
                    ViewBag.Vehicle = vehicle.Make + " " + vehicle.Model + ", " +
                                      vehicle.Color + ", " + vehicle.VehicleYear + " (Tag # " +
                                      vehicle.TagNumber + ")";
    
                    FileStream fsDrivers = null;
                    BinaryFormatter bfDrivers = new BinaryFormatter();
                    List<Driver> drivers = new List<Driver>();
                    string strDriversFile = Server.MapPath("~/App_Data/Drivers.tts");
    
                    using (fsDrivers = new FileStream(strDriversFile, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        drivers = (List<Driver>)bfDrivers.Deserialize(fsDrivers);
                    }
    
                    Driver person = drivers.Find(driver => driver.DriverId == violation.VehicleId);
    
                    ViewBag.DriverName = person.FirstName + " " + person.LastName + " (Drv. Lic. # " + person.DrvLicNumber + ")";
                    ViewBag.DriverAddress = person.Address + " " + person.City + ", " + person.State + " " + person.ZIPCode;
    
                    FileStream fsCameras = null;
                    BinaryFormatter bfCameras = new BinaryFormatter();
                    List<Camera> cameras = new List<Camera>();
                    string strCamerasFile = Server.MapPath("~/App_Data/Cameras.tts");
    
                    using (fsCameras = new FileStream(strCamerasFile, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        cameras = (List<Camera>)bfCameras.Deserialize(fsCameras);
                    }
    
                    Camera viewer = cameras.Find(cmr => cmr.CameraId == violation.CameraId);
    
                    ViewBag.Camera = viewer.Make + " " + viewer.Model + " (" + viewer.CameraNumber + ")";
                    ViewBag.ViolationLocation = viewer.Location;
                }
    
                return View();
            }
        }
    }
  6. In the Solution Explorer, under Views, right-click Traffic Violations -> Add -> View...
  7. Type Citation
  8. Click Add
  9. Change the document as follows:
    @{
        ViewBag.Title = "Traffic Violation - Citation";
    }
    
    <h2 class="text-center common-font maroon bold">Traffic Violation - Citation</h2>
    
    <div>
        <h3 class="common-font bold text-center maroon">City of Jamies Town</h3>
        <h4 class="text-center common-font bold">6824 Cochran Ave, Ste 318<br />Jamies Town, MD 20540</h4>
    
        <div class="row common-font">
            <div class="col-md-8">
                <h5 class="common-font bold">Citation #: @ViewBag.TrafficViolationNumber</h5>
    
                <h5 class="common-font bold">Violation Type: @ViewBag.ViolationName Violation</h5>
                <hr />
                <h5 class="common-font bold">@ViewBag.DriverName</h5>
                <h5 class="common-font bold">@ViewBag.DriverAddress</h5>
                <h5 class="common-font bold">Vehicle: @ViewBag.Vehicle</h5>
                <hr />
                <h5 class="common-font bold">To @ViewBag.DriverName</h5>
    
                <p>Our records indicate that on @ViewBag.ViolationDate at @ViewBag.ViolationTime, at @ViewBag.ViolationLocation, the above mentioned vehicle committed a @ViewBag.ViolationName violation. @ViewBag.ViolationDescription.</p>
    
                <p>If you recognize the traffic violation, please pay @ViewBag.PaymentAmount by @ViewBag.PaymentDueDate. Failure to pay the amount by that date will result in an increase of the fine and could result in the suspension of your driving priviledges. If you dispute the violation, to eventually appear in court, please fill out the form on the back of this document and send it back to us.</p>
            </div>
            <div class="col-md-4">
                <p>@ViewBag.PhotoVideo</p>
            </div>
        </div>
    </div>
    
    <hr />
  10. In the Solution Explorer, under Views, right-click Traffic Violations -> Add -> View...
  11. Type Create
  12. Click Add
  13. Change the document as follows:
    @model TrafficTicketsSystem2.Models.TrafficViolation
    
    @{
        ViewBag.Title = "Create Traffic Violation";
    }
    
    <h2 class="common-font text-center bold maroon">Traffic Violation Issuance</h2>
    
    <hr />
    
    @using (Html.BeginForm())
    {
        @Html.AntiForgeryToken()
    
        <div class="containment">
            <div class="form-horizontal common-font">
                @Html.ValidationSummary(true, "", new { @class = "text-danger" })
                <div class="form-group">
                    @Html.LabelFor(model => model.TrafficViolationNumber, htmlAttributes: new { @class = "control-label col-md-5 maroon" })
                    <div class="col-md-7">
                        @Html.TextBox("TrafficViolationNumber", @ViewBag.TrafficViolationNumber as string, htmlAttributes: new { @class = "form-control" })
                        @Html.ValidationMessageFor(model => model.TrafficViolationNumber, "", new { @class = "text-danger" })
                    </div>
                </div>
    
                <div class="form-group">
                    <label for="cmrNumber" class="control-label col-md-5 maroon">Camera #</label>
                    <div class="col-md-7">
                        @Html.DropDownList("CameraNumber", ViewBag.CamerasNumbers as SelectList, htmlAttributes: new { @class = "form-control", id = "cmrNumber" })
                        @Html.ValidationMessageFor(model => model.CameraId, "", new { @class = "text-danger" })
                    </div>
                </div>
    
                <div class="form-group">
                    <label for="tagNbr" class="control-label col-md-5 maroon">Vehicle Tag #</label>
                    <div class="col-md-7">
                        @Html.TextBox("TagNumber", null, htmlAttributes: new { @class = "form-control", id = "tagNbr" })
                        @Html.ValidationMessageFor(model => model.VehicleId, "", new { @class = "text-danger" })
                    </div>
                </div>
    
                <div class="form-group">
                    <label for="violName" class="control-label col-md-5 maroon">Violation Name</label>
                    <div class="col-md-7">
                        @Html.DropDownList("ViolationName", ViewBag.ViolationName as SelectList, htmlAttributes: new { @class = "form-control", id = "violName" })
                        @Html.ValidationMessageFor(model => model.ViolationTypeId, "", new { @class = "text-danger" })
                    </div>
                </div>
    
                <div class="form-group">
                    @Html.LabelFor(model => model.ViolationDate, htmlAttributes: new { @class = "control-label col-md-5 maroon" })
                    <div class="col-md-7">
                        @Html.EditorFor(model => model.ViolationDate, new { htmlAttributes = new { @class = "form-control" } })
                        @Html.ValidationMessageFor(model => model.ViolationDate, "", new { @class = "text-danger" })
                    </div>
                </div>
    
                <div class="form-group">
                    @Html.LabelFor(model => model.ViolationTime, htmlAttributes: new { @class = "control-label col-md-5 maroon" })
                    <div class="col-md-7">
                        @Html.EditorFor(model => model.ViolationTime, new { htmlAttributes = new { @class = "form-control" } })
                        @Html.ValidationMessageFor(model => model.ViolationTime, "", new { @class = "text-danger" })
                    </div>
                </div>
    
                <div class="form-group">
                    @Html.LabelFor(model => model.PhotoAvailable, htmlAttributes: new { @class = "control-label col-md-5 maroon" })
                    <div class="col-md-7">
                        @Html.DropDownList("PhotoAvailable", ViewBag.PhotoAvailable as SelectList, htmlAttributes: new { @class = "form-control" })
                        @Html.ValidationMessageFor(model => model.PhotoAvailable, "", new { @class = "text-danger" })
                    </div>
                </div>
    
                <div class="form-group">
                    @Html.LabelFor(model => model.VideoAvailable, htmlAttributes: new { @class = "control-label col-md-5 maroon" })
                    <div class="col-md-7">
                        @Html.DropDownList("VideoAvailable", ViewBag.PhotoAvailable as SelectList, htmlAttributes: new { @class = "form-control" })
                        @Html.ValidationMessageFor(model => model.VideoAvailable, "", new { @class = "text-danger" })
                    </div>
                </div>
    
                <div class="form-group">
                    @Html.LabelFor(model => model.PaymentDueDate, htmlAttributes: new { @class = "control-label col-md-5 maroon" })
                    <div class="col-md-7">
                        @Html.TextBox("PaymentDueDate", null, htmlAttributes: new { @class = "form-control", type = "Date" })
                        @Html.ValidationMessageFor(model => model.PaymentDueDate, "", new { @class = "text-danger" })
                    </div>
                </div>
    
                <div class="form-group">
                    @Html.LabelFor(model => model.PaymentDate, htmlAttributes: new { @class = "control-label col-md-5 maroon" })
                    <div class="col-md-7">
                        @Html.EditorFor(model => model.PaymentDate, new { htmlAttributes = new { @class = "form-control" } })
                        @Html.ValidationMessageFor(model => model.PaymentDate, "", new { @class = "text-danger" })
                    </div>
                </div>
    
                <div class="form-group">
                    @Html.LabelFor(model => model.PaymentAmount, htmlAttributes: new { @class = "control-label col-md-5 maroon" })
                    <div class="col-md-7">
                        @Html.EditorFor(model => model.PaymentAmount, new { htmlAttributes = new { @class = "form-control" } })
                        @Html.ValidationMessageFor(model => model.PaymentAmount, "", new { @class = "text-danger" })
                    </div>
                </div>
    
                <div class="form-group">
                    @Html.LabelFor(model => model.PaymentStatus, htmlAttributes: new { @class = "control-label col-md-5 maroon" })
                    <div class="col-md-7">
                        @Html.DropDownList("PaymentStatus", ViewBag.PaymentStatus as SelectList, htmlAttributes: new { @class = "form-control" })
                        @Html.ValidationMessageFor(model => model.PaymentStatus, "", new { @class = "text-danger" })
                    </div>
                </div>
    
                <div class="form-group">
                    <label class="control-label col-md-6">
                        @Html.ActionLink("Traffic Violations", "Index")
                    </label>
                    <div class="col-md-6">
                        <input type="submit" value="Save this Traffic Violation Record" class="btn btn-warning" />
                    </div>
                </div>
            </div>
        </div>
    }
    
    <hr />
  14. In the Solution Explorer, under Views, right-click Traffic Violations -> Add -> View...
  15. Type Delete
  16. Click Add
  17. Change the document as follows:
    @model TrafficTicketsSystem2.Models.TrafficViolation
    
    @{
        ViewBag.Title = "Delete Traffic Violation";
    }
    
    <h2 class="maroon common-font text-center bold">Delete Traffic Violation</h2>
    
    <hr />
    
    <div class="containment">
        <dl class="dl-horizontal common-font">
            <dt class="maroon">@Html.DisplayNameFor(model => model.TrafficViolationId)</dt>
            <dd>@Html.DisplayFor(model => model.TrafficViolationId)</dd>
    
            <dt class="maroon">@Html.DisplayNameFor(model => model.TrafficViolationNumber)</dt>
            <dd>@Html.DisplayFor(model => model.TrafficViolationNumber)</dd>
    
            <dt class="maroon">@Html.DisplayNameFor(model => model.CameraId)</dt>
            <dd>@Html.DisplayFor(model => model.CameraId)</dd>
    
            <dt class="maroon">@Html.DisplayNameFor(model => model.VehicleId)</dt>
            <dd>@Html.DisplayFor(model => model.VehicleId)</dd>
    
            <dt class="maroon">@Html.DisplayNameFor(model => model.ViolationTypeId)</dt>
            <dd>@Html.DisplayFor(model => model.ViolationTypeId)</dd>
    
            <dt class="maroon">@Html.DisplayNameFor(model => model.ViolationDate)</dt>
            <dd>@Html.DisplayFor(model => model.ViolationDate)</dd>
    
            <dt class="maroon">@Html.DisplayNameFor(model => model.ViolationTime)</dt>
            <dd>@Html.DisplayFor(model => model.ViolationTime)</dd>
    
            <dt class="maroon">@Html.DisplayNameFor(model => model.PhotoAvailable)</dt>
            <dd>@Html.DisplayFor(model => model.PhotoAvailable)</dd>
    
            <dt class="maroon">@Html.DisplayNameFor(model => model.VideoAvailable)</dt>
            <dd>@Html.DisplayFor(model => model.VideoAvailable)</dd>
    
            <dt class="maroon">@Html.DisplayNameFor(model => model.PaymentDueDate)</dt>
            <dd>@Html.DisplayFor(model => model.PaymentDueDate)</dd>
    
            <dt class="maroon">@Html.DisplayNameFor(model => model.PaymentDate)</dt>
            <dd>@Html.DisplayFor(model => model.PaymentDate)</dd>
    
            <dt class="maroon">@Html.DisplayNameFor(model => model.PaymentAmount)</dt>
            <dd>@Html.DisplayFor(model => model.PaymentAmount)</dd>
    
            <dt class="maroon">@Html.DisplayNameFor(model => model.PaymentStatus)</dt>
            <dd>@Html.DisplayFor(model => model.PaymentStatus)</dd>
        </dl>
    
        <h3 class="common-font text-center bold blue">Are you sure you want to delete this traffic violation?</h3>
    
        @using (Html.BeginForm())
        {
            @Html.AntiForgeryToken()
    
            <div class="form-actions no-color">
                <input type="submit" value="Delete Traffic Violation" class="btn btn-warning" /> ::
                @Html.ActionLink("Traffic Violations", "Index")
            </div>
        }
    </div>
    
    <hr />
  18. In the Solution Explorer, under Views, right-click Traffic Violations -> Add -> View...
  19. Type Details
  20. Click Add
  21. Change the document as follows:
    @model TrafficTicketsSystem2.Models.TrafficViolation
    
    @{
        ViewBag.Title = "Traffic Violation Details";
    }
    
    <h2 class="common-font bold maroon text-center">Traffic Violation Details</h2>
    
    <hr />
    
    <div class="containment">
        <dl class="dl-horizontal common-font">
            <dt class="maroon">@Html.DisplayNameFor(model => model.TrafficViolationId)</dt>
            <dd>@Html.DisplayFor(model => model.TrafficViolationId)</dd>
    
            <dt class="maroon">@Html.DisplayNameFor(model => model.TrafficViolationNumber)</dt>
            <dd>@Html.DisplayFor(model => model.TrafficViolationNumber)</dd>
    
            <dt class="maroon">@Html.DisplayNameFor(model => model.CameraId)</dt>
            <dd>@Html.DisplayFor(model => model.CameraId)</dd>
    
            <dt class="maroon">@Html.DisplayNameFor(model => model.VehicleId)</dt>
            <dd>@Html.DisplayFor(model => model.VehicleId)</dd>
    
            <dt class="maroon">@Html.DisplayNameFor(model => model.ViolationTypeId)</dt>
            <dd>@Html.DisplayFor(model => model.ViolationTypeId)</dd>
    
            <dt class="maroon">@Html.DisplayNameFor(model => model.ViolationDate)</dt>
            <dd>@Html.DisplayFor(model => model.ViolationDate)</dd>
    
            <dt class="maroon">@Html.DisplayNameFor(model => model.ViolationTime)</dt>
            <dd>@Html.DisplayFor(model => model.ViolationTime)</dd>
    
            <dt class="maroon">@Html.DisplayNameFor(model => model.PhotoAvailable)</dt>
            <dd>@Html.DisplayFor(model => model.PhotoAvailable)</dd>
    
            <dt class="maroon">@Html.DisplayNameFor(model => model.VideoAvailable)</dt>
            <dd>@Html.DisplayFor(model => model.VideoAvailable)</dd>
    
            <dt class="maroon">@Html.DisplayNameFor(model => model.PaymentDueDate)</dt>
            <dd>@Html.DisplayFor(model => model.PaymentDueDate)</dd>
    
            <dt class="maroon">@Html.DisplayNameFor(model => model.PaymentDate)</dt>
            <dd>@Html.DisplayFor(model => model.PaymentDate)</dd>
    
            <dt class="maroon">@Html.DisplayNameFor(model => model.PaymentAmount)</dt>
            <dd>@Html.DisplayFor(model => model.PaymentAmount)</dd>
    
            <dt class="maroon">@Html.DisplayNameFor(model => model.PaymentStatus)</dt>
            <dd>@Html.DisplayFor(model => model.PaymentStatus)</dd>
        </dl>
    </div>
    
    <p class="text-center">
        @Html.ActionLink("Edit", "Edit", new { id = Model.TrafficViolationId }) |
        @Html.ActionLink("Traffic Violations", "Index")</p>
  22. In the Solution Explorer, under Views, right-click Traffic Violations -> Add -> View...
  23. Type Edit
  24. Click Add
  25. Change the document as follows:
    @model TrafficTicketsSystem2.Models.TrafficViolation
    
    @{
        ViewBag.Title = "Edit/Update TrafficViolation";
    }
    
    <h2 class="common-font text-center bold maroon">Edit/Update Traffic Violation</h2>
    
    <hr />
    
    @using (Html.BeginForm())
    {
        @Html.AntiForgeryToken()
    
        <div class="containment">
            <div class="form-horizontal common-font">
                @Html.ValidationSummary(true, "", new { @class = "text-danger" })
                @Html.HiddenFor(model => model.TrafficViolationId)
    
                <div class="form-group">
                    @Html.LabelFor(model => model.TrafficViolationNumber, htmlAttributes: new { @class = "control-label col-md-5 maroon" })
                    <div class="col-md-7">
                        @Html.EditorFor(model => model.TrafficViolationNumber, null, new { htmlAttributes = new { @class = "form-control" } })
                        @Html.ValidationMessageFor(model => model.TrafficViolationNumber, "", new { @class = "text-danger" })
                    </div>
                </div>
    
                <div class="form-group">
                    @Html.LabelFor(model => model.CameraId, htmlAttributes: new { @class = "control-label col-md-5 maroon" })
                    <div class="col-md-7">
                        @Html.DropDownList("CameraNumber", ViewBag.CamerasNumbers as SelectList, htmlAttributes: new { @class = "form-control" })
                        @Html.ValidationMessageFor(model => model.CameraId, "", new { @class = "text-danger" })
                    </div>
                </div>
    
                <div class="form-group">
                    <label for="drvLicNbr" class="control-label col-md-5 maroon">Vehicle's Tag #</label>
                    <div class="col-md-7">
                        @Html.TextBox("TagNumber", null, htmlAttributes: new { @class = "form-control", id = "drvLicNbr" })
                        @Html.ValidationMessageFor(model => model.VehicleId, "", new { @class = "text-danger" })
                    </div>
                </div>
    
                <div class="form-group">
                    <label for="violName" class="control-label col-md-5 maroon">Violation Name</label>
                    <div class="col-md-7">
                        @Html.DropDownList("ViolationName", ViewBag.ViolationName as SelectList, htmlAttributes: new { @class = "form-control", id = "violName" })
                        @Html.ValidationMessageFor(model => model.VehicleId, "", new { @class = "text-danger" })
                    </div>
                </div>
    
                <div class="form-group">
                    @Html.LabelFor(model => model.ViolationDate, htmlAttributes: new { @class = "control-label col-md-5 maroon" })
                    <div class="col-md-7">
                        @Html.EditorFor(model => model.ViolationDate, new { htmlAttributes = new { @class = "form-control" } })
                        @Html.ValidationMessageFor(model => model.ViolationDate, "", new { @class = "text-danger" })
                    </div>
                </div>
    
                <div class="form-group">
                    @Html.LabelFor(model => model.ViolationTime, htmlAttributes: new { @class = "control-label col-md-5 maroon" })
                    <div class="col-md-7">
                        @Html.EditorFor(model => model.ViolationTime, new { htmlAttributes = new { @class = "form-control" } })
                        @Html.ValidationMessageFor(model => model.ViolationTime, "", new { @class = "text-danger" })
                    </div>
                </div>
    
                <div class="form-group">
                    @Html.LabelFor(model => model.PhotoAvailable, htmlAttributes: new { @class = "control-label col-md-5 maroon" })
                    <div class="col-md-7">
                        @Html.DropDownList("PhotoAvailable", ViewBag.PhotoAvailable as SelectList, htmlAttributes: new { @class = "form-control" })
                        @Html.ValidationMessageFor(model => model.PhotoAvailable, "", new { @class = "text-danger" })
                    </div>
                </div>
    
                <div class="form-group">
                    @Html.LabelFor(model => model.VideoAvailable, htmlAttributes: new { @class = "control-label col-md-5 maroon" })
                    <div class="col-md-7">
                        @Html.DropDownList("VideoAvailable", ViewBag.PhotoAvailable as SelectList, htmlAttributes: new { @class = "form-control" })
                        @Html.ValidationMessageFor(model => model.VideoAvailable, "", new { @class = "text-danger" })
                    </div>
                </div>
    
                <div class="form-group">
                    @Html.LabelFor(model => model.PaymentDueDate, htmlAttributes: new { @class = "control-label col-md-5 maroon" })
                    <div class="col-md-7">
                        @Html.TextBox("PaymentDueDate", null, htmlAttributes: new { @class = "form-control", type = "Date" })
                        @Html.ValidationMessageFor(model => model.PaymentDueDate, "", new { @class = "text-danger" })
                    </div>
                </div>
    
                <div class="form-group">
                    @Html.LabelFor(model => model.PaymentDate, htmlAttributes: new { @class = "control-label col-md-5 maroon" })
                    <div class="col-md-7">
                        @Html.EditorFor(model => model.PaymentDate, new { htmlAttributes = new { @class = "form-control" } })
                        @Html.ValidationMessageFor(model => model.PaymentDate, "", new { @class = "text-danger" })
                    </div>
                </div>
    
                <div class="form-group">
                    @Html.LabelFor(model => model.PaymentAmount, htmlAttributes: new { @class = "control-label col-md-5 maroon" })
                    <div class="col-md-7">
                        @Html.EditorFor(model => model.PaymentAmount, new { htmlAttributes = new { @class = "form-control" } })
                        @Html.ValidationMessageFor(model => model.PaymentAmount, "", new { @class = "text-danger" })
                    </div>
                </div>
    
                <div class="form-group">
                    @Html.LabelFor(model => model.PaymentStatus, htmlAttributes: new { @class = "control-label col-md-5 maroon" })
                    <div class="col-md-7">
                        @Html.DropDownList("PaymentStatus", ViewBag.PaymentStatus as SelectList, htmlAttributes: new { @class = "form-control" })
                        @Html.ValidationMessageFor(model => model.PaymentStatus, "", new { @class = "text-danger" })
                    </div>
                </div>
    
                <div class="form-group">
                    <label class="control-label col-md-6">
                        @Html.ActionLink("Traffic Violations", "Index")
                    </label>
                    <div class="col-md-6">
                        <input type="submit" value="Update this Traffic Violation" class="btn btn-warning" />
                    </div>
                </div>
            </div>
        </div>
    }
    
    <hr />
  26. In the Solution Explorer, under Views, right-click Traffic Violations -> Add -> View...
  27. Type Index as the name of the view
  28. Click Add
  29. Change the document as follows:
    @model IEnumerable<TrafficTicketsSystem2.Models.TrafficViolation>
    
    @{
        ViewBag.Title = "Traffic Violations";
    }
    
    <h2 class="bold maroon common-font text-center">Traffic Violations</h2>
    
    <table class="table table-hover common-font">
        <tr>
            <th class="text-center maroon">@Html.DisplayNameFor(model => model.TrafficViolationId)</th>
            <th class="text-center maroon">@Html.DisplayNameFor(model => model.TrafficViolationNumber)</th>
            <th class="text-center maroon">@Html.DisplayNameFor(model => model.CameraId)</th>
            <th class="text-center maroon">@Html.DisplayNameFor(model => model.VehicleId)</th>
            <th class="maroon text-center">@Html.DisplayNameFor(model => model.ViolationTypeId)</th>
            <th class="maroon text-center">@Html.DisplayNameFor(model => model.ViolationDate)</th>
            <th class="maroon text-center">@Html.DisplayNameFor(model => model.ViolationTime)</th>
            <th class="maroon text-center">@Html.DisplayNameFor(model => model.PhotoAvailable)</th>
            <th class="maroon text-center">@Html.DisplayNameFor(model => model.VideoAvailable)</th>
            <th class="maroon text-center">@Html.DisplayNameFor(model => model.PaymentDueDate)</th>
            <th class="maroon text-center">@Html.DisplayNameFor(model => model.PaymentDate)</th>
            <th class="maroon">@Html.DisplayNameFor(model => model.PaymentAmount)</th>
            <th class="maroon">@Html.DisplayNameFor(model => model.PaymentStatus)</th>
            <th class="maroon">@Html.ActionLink("Process New Traffic Violation", "Create")</th>
        </tr>
    
        @foreach (var item in Model)
        {
        <tr>
            <td class="text-center">@Html.DisplayFor(modelItem => item.TrafficViolationId)</td>
            <td class="text-center">@Html.DisplayFor(modelItem => item.TrafficViolationNumber)</td>
            <td class="text-center">@Html.DisplayFor(modelItem => item.CameraId)</td>
            <td class="text-center">@Html.DisplayFor(modelItem => item.VehicleId)</td>
            <td class="text-center">@Html.DisplayFor(modelItem => item.ViolationTypeId)</td>
            <td class="text-center">@Html.DisplayFor(modelItem => item.ViolationDate)</td>
            <td class="text-center">@Html.DisplayFor(modelItem => item.ViolationTime)</td>
            <td class="text-center">@Html.DisplayFor(modelItem => item.PhotoAvailable)</td>
            <td class="text-center">@Html.DisplayFor(modelItem => item.VideoAvailable)</td>
            <td class="text-center">@Html.DisplayFor(modelItem => item.PaymentDueDate)</td>
            <td class="text-center">@Html.DisplayFor(modelItem => item.PaymentDate)</td>
            <td>@Html.DisplayFor(modelItem => item.PaymentAmount)</td>
            <td>@Html.DisplayFor(modelItem => item.PaymentStatus)</td>
            <td>
                @Html.ActionLink("Edit", "Edit", new { id = item.TrafficViolationId }) |
                @Html.ActionLink("Details", "Details", new { id = item.TrafficViolationId }) |
                @Html.ActionLink("Delete", "Delete", new { id = item.TrafficViolationId }) | 
                @Html.ActionLink("Citation", "Citation", new { id = item.TrafficViolationId })
            </td>
        </tr>
        }
    </table>
    
    <hr />
  30. To execute the application, on the main menu, click Debug and click Start Without Debugging
  31. Click the TRAFFIC VIOLATIONS link
  32. Click Process New Traffic Violation

    Route Patterns

  33. Add a few records as follows:
     
    Camera # Tag # Violation Type Violation Date Violation Time Photo Available Video Available Pmt Due Date Pmt Date Pmt Amt Pmt Status
    MSR-59575 KLT4805 Stop Sign 01/18/2018 09:12:35 No Yes 02/28/2018   75 Pending
    DHT-29417 971384 Speed 02/06/2018 11:58:06 No Yes 04/05/2018   85 Pending
    DGH-38460 PER2849 Red Light Steady 01/31/2018 05:15:18 Yes No 03/10/2018   125 Pending
    DHT-29417 FKEWKR Speed 03-05-2018 16:07:15 Yes Yes 04-22-2018   85 Pending
    MSR-59575 8DE9275 Stop Sign 01/18/2018 14:22:48 No Yes 03/10/2018   60 Pending
    ELQ-79284 KLT4805 Speed 04-12-2018 08:16:22 No Yes 06-08-2018   100 Pending
    HTR-93847 PER2849 Red Light Flashing 01/28/2018 22:14:53 No No 03/02/2018   45 Pending
    AHR-41518 MWH4685 Speed 03-31-2018 22:07:31 Yes No 05/15/2018   75 Pending
    DGH-38460 KAS9314 Red Light Right Turn 01-31-2018 12:30:11 Yes No 02-28-2018   60 Pending
    DHT-29417 971384 Speed 02/06/2018 19:04:47 Yes Yes 04-05-2018   85 Pending
    ELQ-79284 8DE9275 Speed 04-15-2018 15:25:53 Yes No 06/02/2018   40 Pending

    Linked Lists - Traffic Tickets System - Traffic Violations

  34. Edit the records for the payment dates, amounts, and status as follows:
     
    Camera # Tag # Violation Type Violation Date Violation Time Photo Available Video Available Pmt Due Date Pmt Date Pmt Amt Pmt Status
    MSR-59575 KLT4805 Stop Sign 01/18/2018 09:12:35 Yes Yes 02/28/2018 02-27-2018 75 Paid On Time
    DHT-29417 971384 Speed 02/06/2018 11:58:06 No Yes 04/05/2018 03/31/2018 85 Paid On Time
    DGH-38460 PER2849 Red Light Steady 01/31/2018 05:15:18 Yes No 03/10/2018   125 Pending
    DHT-29417 FKEWKR Speed 03/05/2018 16:07:15 No Yes 04/22/2018 04/15/2018 85 Paid On Time
    MSR-59575 8DE9275 Stop Sign 01/18/2018 14:22:48 No Yes 03/10/2018 03/27/2018 90 Paid Late
    ELQ-79284 KLT4805 Speed 04/12/2018 08:16:22 No Yes 06/08/2018   100 Cancelled
    HTR-93847 PER2849 Red Light Flashing 01/28/2018 22:14:53 No No 03/02/2018 03-01-2018 45 Rejected
    AHR-41518 MWH4685 Speed 03/31/2018 22:07:31 Yes No 05/15/2018   75 Pending
    DGH-38460 KAS9314 Red Light Right Turn 01/31/2018 12:30:11 Yes No 02-28-2018 04-02-2018 90 Paid Late
    DHT-29417 971384 Speed 02/06/2018 19:04:47 No Yes 04-05-2018 03-31-2018 85 Paid On Time
    ELQ-79284 8DE9275 Speed 04/15/2018 15:25:53 Yes No 06/02/2018   40 Pending

    Linked Lists - Traffic Tickets System - Traffic Violations

  35. Click the Citation link of the 3rd record:

    Linked Lists - Traffic Tickets System - Traffic Violations

  36. In the address bar, change 3 to 9

    Route Patterns

  37. Close the browser and return to your programming environment

Ignoring a Route

Another method of the RouteCollection class indicates a URL scheme that should be ignored. This method is named IgnoreRoute. Its syntax is:

public void IgnoreRoute(string url);

This method takes one argument as a string that contains the URL pattern.

At Application Start-Up

To let you indicate how the routing must be done in your ASP.NET MVC project, when you create a project in Microsoft Visual Studio, the studio creates a folder named App_Start in the project. In that folder, it creates a C# file named RouteConfig.cs. In that file, it creates a class named RouteConfig. In that class, it creates a static method named RegisterRoutes. The compiler will refer to that class for routing purposes.

ApplicationPractical Learning: Routing in MVC

  1. In the Solution Explorer, expand App_Start if necessary and double-click RouteConfig.cs to open it
  2. Change the document as follows:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    using System.Web.Routing;
    
    namespace TrafficTicketSystem2
    {
        public class RouteConfig
        {
            public static void RegisterRoutes(RouteCollection routes)
            {
                routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    
                routes.MapRoute(
                    name: "Default",
                    url: "{controller}/{action}/{id}",
                    defaults: new { controller = "TrafficViolations", action = "Index", id = UrlParameter.Optional }
                );
            }
        }
    }
  3. To execute the project, on the main menu, click Debug -> Start Without Debugging
  4. Close the browser and return to your programming environment

The Entry Page of a Web Site

When you decide to create a website, the most important object is a file referred to as the entry webpage. This is the webpage that displays when a visitor types a domain name (such as yahoo.com, microsoft.com, or csharpkey.com, etc) in the address bar of a browser and presses Enter. Behind-the-scenes, that is, in the webserver, this file is usually named index, Index, default, or Default, and has the extension .htm, .html, or something like that. This is neither a rule nor a law, only a routine. When creating your website, you can decide what webpage must display when.

Options on Creating Routes

Ignoring the Indentifier

When a webserver is asked to display a webpage, it switches to the routing configuration and checks the Id factor. If the Id is specified but there is no such identifier, it would be ignored. If you are not planning to use the Id factor, you can assign an empty string to Id. Here is an example:

using System.Web.Mvc;
using System.Web.Routing;

namespace Exercise1
{
    public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute("Detailed Report",
			    "{controller}/{action}/{id}",
			    new { controller = "Home", action = "Index", id = "" }
            );
        }
    }
}

Alternatively, if you don't want to use an identifier in the address, remove the Id factor in the url argument and omit it in the defaults argument. Here is an example:

using System.Web.Mvc;
using System.Web.Routing;

namespace Exercise1
{
    public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute("Detailed Report",
			    "{controller}/{action}/",
			    new { controller = "Home", action = "Index" }
            );
        }
    }
}

Creating a Collection of Routes

As mentioned previously, the class used to create routes, RouteCollection, is a collection class. This means that you can create and manage as different routes as you want. Each route is created by calling the RouteCollection.Add() method that we saw already. Here are examples:

using System.Web.Mvc;
using System.Web.Routing;

namespace Exercise1
{
    public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(name: "Academia Topics",
                            url: "{controller}/{action}",
                            defaults: new { controller = "Academics", action = "AdmissionApplication" });

            routes.MapRoute(name: "Home",
                            url: "{controller}/{action}/{id}",
                            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional });

            routes.MapRoute(name: "Human Resources",
                            url: "{controller}/{action}/",
                            defaults: new { controller = "Personnel", action = "TimeSheet" });
        }
    }
}

After creating the routes, if a visitor accesses your website using the domain name (such as blahblahblah.com), the webserver will refer to the RouteConfig.cs file and enter the RouteConfig.RegisterRoutes() method. As is always the case, the compiler would read the document from top to bottom. As a result, the first route would apply and may show its indicated webpage even if that's not the regular entry-poinit. Otherwise, the webserver would follow or access the views (the webpages) by the order of the routes creations.

View Redirection Using a Route

When an action has been performed, you can redirect the user or visitor to a view of your choice by specifying a route to take. To support this, the Controller class is equipped with an overloaded method named RedirectToRoute. One of the syntaxes used by this method is:

protected internal RedirectToRouteResult RedirectToRoute(object routeValues);

This method takes a route definition as argument. Here is an example:

public ActionResult Testimony()
{
    return RedirectToRoute(new { controller = "UnitedStates",
				    			 action = "Index",
			    	             id = UrlParameter.Optional });
}

Practical LearningPractical Learning: Ending the Lesson


Previous Copyright © 2018-2019, FunctionX Next