2081

BIT351 · TU past paper

NET Centric Computing 2081 question paper

The complete TU 2081 exam paper for NET Centric Computing (BIT351), all 12 questions with solved model answers written to the mark scheme.

Past Papers2081.120812080

Tap a question to open its answer.

  1. 110 marksIndexersAnswer

    Define indexers. What is the use of base keyword? How can you apply polymorphism in code extensibility?[10]

    Indexers, Base Keyword, and Polymorphism in Code Extensibility

    Note: No specific curriculum notes were provided for this question. The answer below is based on standard C# / Object-Oriented Programming concepts as taught in TU BSc CSIT curriculum.


    1. Indexers (3 marks)

    Definition

    An indexer is a special class member in C# that allows an object to be indexed like an array. It enables instances of a class to be accessed using the subscript notation ([]), making the class behave like a virtual array.

    Syntax

    <access_modifier> <return_type> this[<parameter_type> index]
    {
        get { // return value }
        set { // set value }
    }
    

    Example

    class StudentMarks
    {
        private int[] marks = new int[5];
    
        // Indexer definition
        public int this[int index]
        {
            get
            {
                return marks[index];
            }
            set
            {
                marks[index] = value;
            }
        }
    }
    
    class Program
    {
        static void Main()
        {
            StudentMarks s = new StudentMarks();
            s[0] = 85;   // uses set accessor
            s[1] = 90;   // uses set accessor
            Console.WriteLine(s[0]);  // uses get accessor -> Output: 85
        }
    }
    

    Key Features of Indexers

    FeatureDescription
    Keyword usedthis
    Can be overloadedYes
    Can have get/setYes
    Parameter typeCan be int, string, or any type
    Access modifierCan be public, private, etc.

    2. The base Keyword (3 marks)

    Definition

    The base keyword in C# is used to access members of the base (parent) class from within a derived (child) class. It is used when a derived class wants to call or refer to the parent class's constructor, methods, or properties that have been overridden.

    Uses of base Keyword

    a) Calling Base Class Constructor

    class Animal
    {
        string name;
    
        public Animal(string name)
        {
            this.name = name;
            Console.WriteLine("Animal constructor called: " + name);
        }
    }
    
    class Dog : Animal
    {
        public Dog(string name) : base(name)  // calls Animal's constructor
        {
            Console.WriteLine("Dog constructor called");
        }
    }
    

    b) Calling Overridden Base Class Method

    class Shape
    {
        public virtual void Draw()
        {
            Console.WriteLine("Drawing a Shape");
        }
    }
    
    class Circle : Shape
    {
        public override void Draw()
        {
            base.Draw();  // calls Shape's Draw() method
            Console.WriteLine("Drawing a Circle");
        }
    }
    

    Output:

    Drawing a Shape
    Drawing a Circle
    

    Summary of base Keyword Uses

    • base.MethodName() -- calls the parent class method
    • base(arguments) -- calls the parent class constructor
    • Prevents ambiguity when method names are the same in parent and child classes

    3. Polymorphism in Code Extensibility (4 marks)

    Definition

    Polymorphism means "many forms." It is the ability of a method, object, or variable to take multiple forms. In OOP, polymorphism allows a single interface to represent different underlying data types or behaviors.

    Types of Polymorphism

    TypeAlso Known AsAchieved By
    Compile-timeStatic / Early BindingMethod Overloading, Operator Overloading
    Run-timeDynamic / Late BindingMethod Overriding (virtual/override)

    How Polymorphism Enables Code Extensibility

    Code extensibility means the ability to add new functionality without modifying existing code. Polymorphism supports this through:

    1. Open/Closed Principle -- classes are open for extension but closed for modification.
    2. Runtime polymorphism allows new derived classes to be added without changing the base class or calling code.

    Example: Polymorphism for Code Extensibility

    // Base class
    class Shape
    {
        public virtual double Area()
        {
            return 0;
        }
    
        public void Display()
        {
            Console.WriteLine("Area = " + Area());
        }
    }
    
    // Derived class 1
    class Circle : Shape
    {
        double radius;
        public Circle(double r) { radius = r; }
    
        public override double Area()
        {
            return 3.14 * radius * radius;
        }
    }
    
    // Derived class 2
    class Rectangle : Shape
    {
        double length, width;
        public Rectangle(double l, double w) { length = l; width = w; }
    
        public override double Area()
        {
            return length * width;
        }
    }
    
    // NEW class added WITHOUT modifying existing code
    class Triangle : Shape
    {
        double base_t, height;
        public Triangle(double b, double h) { base_t = b; height = h; }
    
        public override double Area()
        {
            return 0.5 * base_t * height;
        }
    }
    
    class Program
    {
        static void Main()
        {
            // Polymorphic array
            Shape[] shapes = new Shape[3];
            shapes[0] = new Circle(5);
            shapes[1] = new Rectangle(4, 6);
            shapes[2] = new Triangle(3, 8);
    
            foreach (Shape s in shapes)
            {
                s.Display();  // calls the correct overridden Area()
            }
        }
    }
    

    Output:

    Area = 78.5
    Area = 24
    Area = 12
    

    Explanation of Extensibility

    • The Display() method in Shape calls Area() which is virtual.
    • When a new shape like Triangle is added
  2. 210 marksMVC pattern componentsAnswer

    What are the tasks of ASP. NET web forms? Explain the MVC pattern of ASP.NET.[10]

    ASP.NET Web Forms and MVC Pattern


    Part 1: Tasks of ASP.NET Web Forms

    ASP.NET Web Forms is a web application framework that provides an event-driven programming model for building dynamic web pages. The major tasks of ASP.NET Web Forms are:

    1. Page Rendering

    • Web Forms handle the rendering of HTML pages to the client browser.
    • The .aspx file contains the UI markup and the code-behind file (.aspx.cs) contains the logic.
    • The framework automatically generates HTML from server controls.

    2. Event Handling

    • Web Forms support an event-driven model similar to Windows Forms.
    • Events like Button_Click, Page_Load, TextChanged, etc. are handled on the server side.
    • The framework manages the round-trip between client and server for event processing.

    3. State Management

    • Web Forms manage ViewState to preserve the state of controls across postbacks.
    • Other state management techniques include Session, Application, Cookies, and QueryString.
    • ViewState is stored as a hidden field in the HTML page.

    4. Data Binding

    • Web Forms provide powerful data binding capabilities.
    • Controls like GridView, DataList, Repeater, and DropDownList can be bound to data sources.
    • Supports binding to databases, XML, collections, and other data sources.

    5. Validation

    • Web Forms include built-in validation controls such as:
      • RequiredFieldValidator
      • RangeValidator
      • RegularExpressionValidator
      • CompareValidator
      • CustomValidator
    • Both client-side and server-side validation are supported.

    6. User Authentication and Authorization

    • Web Forms integrate with ASP.NET membership and role providers.
    • Controls like Login, LoginView, CreateUserWizard simplify authentication tasks.
    • Forms-based authentication is commonly used.

    7. Session and Application Management

    • Web Forms manage user sessions and application-level data.
    • Session object stores user-specific data across multiple requests.
    • Application object stores data shared across all users.

    8. Master Pages and Themes

    • Web Forms support Master Pages for consistent layout across multiple pages.
    • Themes and Skins allow uniform styling of controls throughout the application.

    9. Postback Mechanism

    • Web Forms use a postback mechanism where form data is submitted back to the same page.
    • The IsPostBack property is used to distinguish between the first load and subsequent postbacks.

    10. Code-Behind Model

    • Web Forms separate UI design (.aspx) from business logic (.aspx.cs).
    • This promotes cleaner code organization and maintainability.

    Part 2: MVC Pattern of ASP.NET

    What is MVC?

    MVC (Model-View-Controller) is a software architectural pattern that separates an application into three interconnected components. ASP.NET MVC is Microsoft's implementation of this pattern for building web applications.

    +------------------+       +------------------+       +------------------+
    |      MODEL       |<----->|   CONTROLLER     |<----->|      VIEW        |
    |                  |       |                  |       |                  |
    | - Data           |       | - Request Handler|       | - UI Display     |
    | - Business Logic |       | - Coordinates M&V|       | - Presentation   |
    | - Data Access    |       | - Action Methods |       | - Razor Templates|
    +------------------+       +------------------+       +------------------+
                                        ^
                                        |
                                   HTTP Request
                                   from Browser
    

    The Three Components

    1. Model

    • The Model represents the data and business logic of the application.
    • It is responsible for:
      • Retrieving data from the database
      • Validating data
      • Storing and updating data
      • Representing the application's data structure
    • In ASP.NET MVC, models are typically C# classes that represent entities.
    • Example:
    public class Student
    {
        public int StudentId { get; set; }
        public string Name { get; set; }
        public string Email { get; set; }
        public int Age { get; set; }
    }
    

    2. View

    • The View is responsible for displaying the data (UI presentation layer).
    • It receives data from the Controller and renders it as HTML.
    • In ASP.NET MVC, Views use Razor syntax (.cshtml files).
    • The View should contain no business logic -- only presentation logic.
    • Example:
    @model Student
    <h2>Student Details</h2>
    <p>Name: @Model.Name</p>
    <p>Email: @Model.Email</p>
    <p>Age: @Model.Age</p>
    

    3. Controller

    • The Controller acts as the intermediary between Model and View.
    • It handles incoming HTTP requests, processes them, interacts with the Model, and returns the appropriate View.
    • Controllers contain Action Methods that respond to user requests.
    • Example:
    public class StudentController : Controller
    {
        public ActionResult Index()
        {
            Student student = new Student
            {
                StudentId = 1,
                Name = "Ram Sharma",
                Email = "[email protected]",
                Age = 20
            };
            return View(student);
        }
    }
    

    How MVC Works: Request Flow

    The flow of a request in ASP.NET MVC is as follows:

    Step 1: User sends HTTP Request (e.g., /Student/Index)
               |
               v
    Step 2: Routing Engine maps URL to Controller and Action Method
               |
               v
    Step 3: Controller's Action Method is invoked
               |
               v
    Step 4: Controller interacts with Model (fetch/update data)
               |
               v
    Step 5: Controller passes Model data to View
               |
               v
    Step 6: View renders the HTML using the Model data (Razor engine)
               |
               v
    Step 7: Rendered HTML response is sent back to the browser
    

    Advantages of the MVC Pattern in ASP.NET

    AdvantageReason
    Separation of concernsData, presentation and request handling live in three different places
    TestabilityControllers and models are plain classes, so they can be unit tested without a browser
    Full control of the markupThere is no view state and no server control identifiers, so the HTML is exactly what the developer wrote
    Clean URLsRouting maps readable URLs onto controllers and actions
    Parallel developmentOne team can work on views while another works on models and controllers

    Conclusion

    ASP.NET Web Forms hides HTTP behind an event-driven, control-based page model, with postback, view state and the code-behind file doing the work, which makes a page quick to build but harder to test and heavier on the wire. ASP.NET MVC replaces that with three explicit roles: the Model holds the data and business rules, the View renders it with Razor, and the Controller receives the routed request, drives the Model and selects the View. The request flow above shows the whole cycle, and it is the reason MVC gives clean URLs, testable code and complete control over the generated markup.

  3. 310 marksControllers and action methodsAnswer

    How do you create Controllers, Actions and Action results? Explain.[10]

    Controllers, Actions, and Action Results in ASP.NET MVC

    Note: The reference notes did not contain specific content on this topic. The following answer is based on standard ASP.NET MVC curriculum as taught in TU BSc CSIT, using correct and widely accepted terminology.


    1. Controllers in ASP.NET MVC

    A Controller is a class that handles incoming HTTP requests, processes user input, interacts with the model, and returns an appropriate response (view or data).

    Rules for Creating a Controller:

    • The class name must end with "Controller" (e.g., HomeController)
    • It must inherit from the Controller base class
    • It is placed inside the Controllers folder of the MVC project
    • It must be a public class

    Syntax to Create a Controller:

    using System.Web.Mvc;
    
    namespace MyApp.Controllers
    {
        public class HomeController : Controller
        {
            // Actions go here
        }
    }
    

    Ways to Create a Controller:

    1. Manually - Create a class file in the Controllers folder following the naming convention.
    2. Using Scaffolding - Right-click on Controllers folder > Add > Controller > Select template (Empty, with Read/Write actions, etc.)

    2. Actions in ASP.NET MVC

    An Action is a public method inside a controller that responds to a specific HTTP request (GET, POST, etc.).

    Rules for Action Methods:

    • Must be a public method
    • Must not be static
    • Must not have [NonAction] attribute (unless intentionally excluded)
    • Returns an ActionResult or its derived types

    Example of Action Methods:

    public class StudentController : Controller
    {
        // Action for GET request
        public ActionResult Index()
        {
            return View();
        }
    
        // Action for displaying details
        public ActionResult Details(int id)
        {
            // fetch student by id
            return View();
        }
    
        // Action for GET - show form
        [HttpGet]
        public ActionResult Create()
        {
            return View();
        }
    
        // Action for POST - submit form
        [HttpPost]
        public ActionResult Create(Student student)
        {
            if (ModelState.IsValid)
            {
                // save to database
                return RedirectToAction("Index");
            }
            return View(student);
        }
    }
    

    Action Selectors (Attributes):

    AttributeDescription
    [HttpGet]Handles GET requests
    [HttpPost]Handles POST requests
    [HttpPut]Handles PUT requests
    [HttpDelete]Handles DELETE requests
    [ActionName("name")]Assigns a different name to the action
    [NonAction]Excludes a public method from being an action

    3. Action Results in ASP.NET MVC

    An ActionResult is the return type of an action method. It is an abstract base class from which all specific result types are derived. It represents the result of executing an action method.

    Common ActionResult Types:

    ActionResult TypeHelper MethodDescription
    ViewResultView()Renders a view (HTML page)
    PartialViewResultPartialView()Renders a partial view
    RedirectResultRedirect()Redirects to a URL
    RedirectToRouteResultRedirectToAction()Redirects to another action
    ContentResultContent()Returns plain text/string content
    JsonResultJson()Returns JSON formatted data
    FileResultFile()Returns a file to download
    EmptyResult(none)Returns nothing (void equivalent)
    HttpNotFoundResultHttpNotFound()Returns 404 error

    Examples of Different Action Results:

    public class DemoController : Controller
    {
        // Returns a View
        public ActionResult Index()
        {
            return View();
        }
    
        // Returns JSON data
        public JsonResult GetData()
        {
            var data = new { Name = "Ram", Age = 20 };
            return Json(data, JsonRequestBehavior.AllowGet);
        }
    
        // Returns plain content
        public ContentResult ShowMessage()
        {
            return Content("Hello from ASP.NET MVC!");
        }
    
        // Redirects to another action
        public ActionResult GoHome()
        {
            return RedirectToAction("Index", "Home");
        }
    
        // Returns a file
        public FileResult DownloadFile()
        {
            byte[] fileBytes = System.IO.File.ReadAllBytes(
                Server.MapPath("~/Files/sample.pdf"));
            return File(fileBytes, "application/pdf", "sample.pdf");
        }
    
        // Returns 404
        public ActionResult FindStudent(int id)
        {
            if (id <= 0)
                return HttpNotFound();
            return View();
        }
    }
    

    4. Summary Diagram

    HTTP Request
         |
         v
      Controller  (inherits Controller class)
         |
         v
      Action Method  (public method, returns ActionResult)
         |
         v
      ActionResult  (ViewResult / JsonResult / RedirectResult ...)
         |
         v
      HTTP Response (HTML / JSON / File / Redirect ...)
    

    5. Key Points to Remember

    • A Controller handles requests and inherits from Controller.
    • An Action is a public method inside a controller that processes a request.
    • An ActionResult is the return type that determines what response is sent back to the client.
    • The View() method returns a ViewResult which renders an HTML page.
    • RedirectToAction() is used to redirect from one action to another.
    • Json() is used in AJAX-based applications to return JSON data.
  4. 45 marksEntity Framework advantagesAnswer

    List the advantages of Entity framework over ADO.NET. [5]

    Advantages of Entity Framework over ADO.NET

    Note: The reference notes did not contain this topic directly. The following answer is based on standard .NET curriculum content appropriate for BSc CSIT.


    Entity Framework vs ADO.NET

    Entity Framework (EF) is an Object-Relational Mapper (ORM) built on top of ADO.NET that allows developers to work with databases using .NET objects, eliminating most of the manual data-access code.


    Advantages of Entity Framework over ADO.NET

    1. Automatic Object Mapping

    • In ADO.NET, developers must manually map database columns to object properties using DataReader or DataSet.
    • In EF, database tables are automatically mapped to C# classes (entities), reducing boilerplate code significantly.

    2. No Need to Write SQL Queries Manually

    • ADO.NET requires writing raw SQL queries for every database operation.
    • EF uses LINQ (Language Integrated Query) to query the database using C# syntax, making code more readable and type-safe.
    // EF Example
    var students = context.Students.Where(s => s.Age > 20).ToList();
    

    3. Database Independence

    • ADO.NET code is often tightly coupled to a specific database (SQL Server, MySQL, etc.).
    • EF supports multiple database providers, and switching databases requires minimal code changes.

    4. Automatic Change Tracking

    • EF automatically tracks changes made to entity objects and generates the appropriate INSERT, UPDATE, or DELETE SQL statements when SaveChanges() is called.
    • In ADO.NET, developers must write all these SQL statements manually.

    5. Reduced Development Time and Code

    • ADO.NET requires writing repetitive code for connection management, command execution, and data reading.
    • EF reduces the amount of code significantly, leading to faster development, easier maintenance, and fewer bugs.

    Summary Table

    FeatureADO.NETEntity Framework
    SQL WritingManualAuto-generated via LINQ
    Object MappingManualAutomatic
    Change TrackingManualAutomatic
    Database IndependenceLowHigh
    Development SpeedSlowerFaster

    Conclusion: Entity Framework provides a higher level of abstraction over ADO.NET, making database operations simpler, faster to develop, and easier to maintain, though ADO.NET offers more fine-grained control for performance-critical scenarios.

  5. 55 marksState management techniquesAnswer

    How do you manage state on stateless HTTP? [5]

    HTTP is a stateless protocol -- each request-response cycle is independent. The server retains no memory of previous requests from the same client. However, real web applications (shopping carts, login sessions, etc.) require state to be...

  6. 65 marksForm validation requirementsAnswer

    Why do we need to validate the form? Describe. [5]

    Form Validation

    Why Do We Need to Validate the Form?

    Form validation is the process of checking the data entered by a user in a form before it is submitted to the server. It ensures that the submitted data is correct, complete, and in the expected format.


    Reasons for Form Validation

    1. To Ensure Required Fields Are Filled

    Many form fields are mandatory (e.g., name, email, password). Without validation, a user might submit an empty form, causing errors in processing. Validation ensures all required fields contain data before submission.

    2. To Ensure Correct Data Format

    Data must be in the correct format for the system to process it properly. For example:

    • An email address must contain @ and a domain (e.g., [email protected])
    • A phone number must contain only digits
    • A date must follow a specific format (e.g., DD/MM/YYYY)

    3. To Prevent Invalid or Garbage Data

    Without validation, users may enter meaningless or incorrect data (e.g., entering letters in an age field). Validation prevents such invalid data from being stored in the database.

    4. To Enhance Security

    Validation helps protect the application from malicious inputs such as:

    • SQL Injection attacks
    • Cross-Site Scripting (XSS) attacks

    By validating and sanitizing inputs, the application becomes more secure.

    5. To Improve User Experience

    Client-side validation provides immediate feedback to the user without requiring a round trip to the server. This saves time and helps users correct mistakes quickly.

    6. To Reduce Server Load

    If invalid data is caught on the client side before submission, unnecessary requests to the server are avoided, reducing server processing load and bandwidth usage.


    Types of Form Validation

    TypeDescription
    Client-Side ValidationDone in the browser using HTML5 attributes or JavaScript before data is sent to the server
    Server-Side ValidationDone on the server after data is submitted; more secure and reliable

    Example (JavaScript Validation)

    function validateForm() {
        var name = document.getElementById("name").value;
        if (name == "") {
            alert("Name field cannot be empty!");
            return false;
        }
        return true;
    }
    

    Conclusion

    Form validation is essential to ensure data integrity, security, and a good user experience. It prevents incorrect, incomplete, or harmful data from entering the system, making web applications more reliable and safe.

  7. 75 marksReact form creationAnswer

    Create a form using React with your own assumption. [5]

    • A User Registration Form with fields: Name, Email, Password, and Gender. - Using React functional component with useState hook for state management. - Basic form validation on submit. --- --- Concept Purpose ------ useState Manages for...
  8. 85 marksVulnerability detection and preventionAnswer

    How do you detect and prevent vulnerabilities in ASP.NET core application. [5]

    Note: No specific reference notes were found for this topic. The following answer is based on standard ASP.NET Core security practices as taught in security/web development courses. --- - Detection: Code review for raw SQL queries; use s...

  9. 95 marksAuthentication purposesAnswer

    What are the purposes of adding authentications to apps? Explain. [5]

    Purposes of Adding Authentication to Apps

    Definition

    Authentication is the process of verifying the identity of a user, device, or system before granting access to an application or its resources. It answers the fundamental question: "Who are you?"


    Purposes of Adding Authentication to Apps

    1. Identity Verification

    Authentication ensures that only legitimate and verified users can access the application. It confirms that the person attempting to log in is who they claim to be, preventing unauthorized individuals from gaining access.

    2. Security and Protection of Data

    Authentication protects sensitive user data and application resources from unauthorized access. Without authentication, any person could access private information such as personal details, financial records, or confidential business data.

    3. Access Control and Authorization

    Authentication works as a gateway for authorization. Once a user is authenticated, the system can determine what resources or features that user is permitted to access (e.g., admin vs. regular user). This enforces role-based access control.

    4. Accountability and Audit Trails

    When users are authenticated, all their actions can be tracked and logged. This creates an audit trail that helps in monitoring suspicious activities, debugging issues, and ensuring accountability for any changes made within the system.

    5. Prevention of Unauthorized Modifications

    Authentication prevents malicious users or attackers from modifying, deleting, or corrupting application data. Only authenticated users with proper permissions can perform critical operations.

    6. Building User Trust

    When an application implements proper authentication (e.g., login, OTP, two-factor authentication), it builds user confidence and trust that their data is safe and the platform is secure.

    7. Compliance with Security Standards

    Many industries require authentication as part of legal and regulatory compliance (e.g., GDPR, HIPAA). Adding authentication helps applications meet these standards and avoid legal penalties.


    Summary Table

    PurposeBenefit
    Identity VerificationConfirms who the user is
    Data SecurityProtects sensitive information
    Access ControlLimits what users can do
    AccountabilityTracks user actions
    Trust BuildingIncreases user confidence
    ComplianceMeets legal requirements

    In short, authentication is a fundamental security mechanism that protects both the application and its users from unauthorized access, data breaches, and misuse.

  10. 105 marksHosting models for ASP.NET CoreAnswer

    Describe any two hosting models for ASP.NET core application. [5]

    Note: The reference notes did not contain material on this topic. The following answer is based on standard ASP.NET Core documentation and is correct for TU BSc CSIT examinations. --- In the in-process hosting model, the ASP.NET Core app...

  11. 115 marksNumericalCRUD operations with ADO.NETAnswer

    Given a table BOOK(ISBN,Name,Author,Price), write a program to update the price of the book to 1000 whose author is John. [5]

    Updating the price of a book from a .NET program

    The table is BOOK(ISBN, Name, Author, Price) and the requirement is a single row update: every book whose Author is John must end up with Price set to 1000. The database work itself is one SQL statement.

    UPDATE BOOK
    SET Price = @price
    WHERE Author = @author;
    

    BIT351 is a .NET paper, so the program that carries that statement to the server is written in C#, using either ADO.NET (SqlConnection, SqlCommand, SqlParameter) or Entity Framework Core. Both are acceptable; the ADO.NET version is shown first because it makes the database work explicit.

    The ADO.NET version

    using System;
    using System.Data;
    using Microsoft.Data.SqlClient;
    
    public static class Program
    {
        public static void Main()
        {
            const string connectionString =
                "Server=localhost;Database=Library;Trusted_Connection=True;TrustServerCertificate=True;";
    
            const string sql = "UPDATE BOOK SET Price = @price WHERE Author = @author";
    
            // using declarations close and dispose the connection and command even on an exception.
            using var connection = new SqlConnection(connectionString);
            using var command = new SqlCommand(sql, connection);
    
            // The two values travel as typed parameters, never as text pasted into the command.
            command.Parameters.Add("@price", SqlDbType.Decimal).Value = 1000m;
            command.Parameters.Add("@author", SqlDbType.NVarChar, 50).Value = "John";
    
            try
            {
                connection.Open();
    
                int rows = command.ExecuteNonQuery();
    
                if (rows > 0)
                {
                    Console.WriteLine(rows + " book(s) by John now cost 1000.");
                }
                else
                {
                    Console.WriteLine("No book by John was found, so nothing was updated.");
                }
            }
            catch (SqlException ex)
            {
                Console.WriteLine("Database error: " + ex.Message);
            }
        }
    }
    

    ExecuteNonQuery is the method used for INSERT, UPDATE and DELETE: it returns the number of rows the statement affected, which is exactly what is needed to report whether any book by John existed. ExecuteReader would be wrong here because an update returns a row count and not a result set, and ExecuteScalar would be wrong because there is no single value to read back.

    The flow of the program is the ordinary ADO.NET sequence.

    What happensHow
    Describe the server, database and credentialsthe connection string
    Hold the parameterised command textSqlCommand
    Bind the new price and the author safelySqlParameter objects added to command.Parameters
    Open the network connectionconnection.Open()
    Run the update and read the row countExecuteNonQuery()
    Release the connection back to the poolthe using declarations

    Why the values are bound and not pasted in

    The command text above is a constant. It is fixed at compile time, and the author name and the price reach the server separately, as data. That matters even in a small exam program: if a value such as the author name were joined onto the command text at run time, a name containing a quote or a trailing OR 1=1 would change the meaning of the statement and update every row in the table. That is SQL injection, and escaping quotes by hand is not a substitute for binding, because it depends on the programmer remembering it at every call site. Parameters remove the problem by construction, and they also let the server reuse the cached execution plan.

    The Entity Framework Core version

    If the project already has a model, the same update is expressed against objects and EF Core writes the parameterised SQL for you.

    using System;
    using System.Linq;
    using Microsoft.EntityFrameworkCore;
    
    [Table("BOOK")]
    public class Book
    {
        [Key]
        public string ISBN { get; set; } = "";
        public string Name { get; set; } = "";
        public string Author { get; set; } = "";
        public decimal Price { get; set; }
    }
    
    public class LibraryContext : DbContext
    {
        public DbSet<Book> Books => Set<Book>();
    
        protected override void OnConfiguring(DbContextOptionsBuilder options) =>
            options.UseSqlServer(
                "Server=localhost;Database=Library;Trusted_Connection=True;TrustServerCertificate=True;");
    }
    
    public static class UpdatePrice
    {
        public static void Run()
        {
            using var db = new LibraryContext();
    
            foreach (Book book in db.Books.Where(b => b.Author == "John"))
            {
                book.Price = 1000m;
            }
    
            int rows = db.SaveChanges();
            Console.WriteLine(rows + " row(s) updated.");
        }
    }
    

    The comparison b.Author == "John" is translated into a parameterised WHERE clause, so this version is as safe as the first one, and SaveChanges wraps the writes in a transaction.

    If the result is displayed in an ASP.NET Core page rather than a console, print it through Razor (for example @rows), which HTML encodes the value automatically, so a book name or author taken from the database can never be interpreted as markup in the browser.

  12. 125 marksView rendering with HTMLAnswer

    How rendering HTML with views is done? Explain. [5]

    In Express.js (Node.js framework), rendering HTML with views means generating and sending dynamic HTML pages to the client using a template engine. Instead of writing static HTML, views allow embedding dynamic data into HTML templates. -...