MICTE 3rd Visual Programming Notes
MICTE 3rd Visual Programming Notes
Unit 1
Visual Programming and C#
1.1. Overview of Visual Programming, The need of Visual Programming
Visual Programming is a programming methodology that allows developers to create software
using graphical elements instead of writing text-based code. This approach is especially common in
environments where the development of graphical user interfaces (GUIs) or interactive elements is a
primary focus. Visual programming environments provide tools such as drag-and-drop interfaces,
flowcharts, and block diagrams that represent the logic and structure of a program visually. This visual
approach can often be more intuitive and easier to learn, especially for those without a strong
programming background.
Microsoft Visual Studio (WinForms and WPF): Allows developers to design user interfaces
visually while writing the underlying code in C# or other .NET languages.
1.2. Graphical User Interface and different types of Visual Programming Practices
Graphical User Interface (GUI)
A Graphical User Interface (GUI) is a user interface that allows users to interact with software
applications through graphical elements like buttons, icons, menus, and other visual indicators, rather
than using text-based commands. GUIs make software more intuitive and accessible, allowing users to
navigate and operate programs through visual elements.
Key Components of a GUI:
Windows: The main containers that hold different elements like buttons, text boxes, and menus.
Buttons: Clickable elements that perform actions when pressed.
Text Boxes: Fields where users can input text.
Labels: Text elements that provide information or describe other elements.
Menus: Lists of options or commands that users can select from.
Icons: Small images representing files, applications, or commands.
Benefits of GUI:
User-Friendly: Easier for non-technical users to operate software.
Consistency: Provides a consistent interface across applications, making it easier to learn and use
new software.
Interactivity: Offers immediate visual feedback and interactivity, enhancing user experience.
4. Form-Based Programming:
o Overview: Form-based programming is a visual approach where developers design software
by creating and arranging forms. Each form represents a screen or dialog box in the
application, and the development environment generates the underlying code.
o Examples:
Microsoft Access: A database management system that uses a form-based interface to
create and manage databases.
Delphi: An IDE that uses form-based programming for building Windows applications.
5. Model-Driven Development (MDD):
o Overview: MDD focuses on creating and exploiting domain models, which are conceptual
models of the domain that describe the structure and behavior of the application. Visual tools
allow developers to create models that generate code automatically.
o Examples:
UML Tools: Tools like Enterprise Architect use Unified Modeling Language (UML)
diagrams to model the software and generate code.
Out Systems: A low-code platform that uses model-driven development to create
enterprise applications.
6. Node-Based Programming:
o Overview: Node-based programming represents program logic as a graph of interconnected
nodes. Each node performs a specific task, and the connections between nodes define the flow
of data or control.
o Examples:
Unreal Engine Blueprint: A visual scripting system for the Unreal Engine, allowing
game developers to create gameplay elements without writing code.
Blender's Node Editor: Used for creating materials, shaders, and compositing effects in
3D modeling and animation.
Benefits of RAD:
Faster Time-to-Market: By focusing on rapid development and iterative cycles, RAD can
significantly reduce the time it takes to deliver a working product.
Reduced Risk: Early prototyping allows for issues to be identified and addressed sooner.
4
Improved User Satisfaction: Early user feedback and prototyping help ensure that the final
product meets the needs and expectations of the users.
Reduced Costs: The reuse of components and faster development can lead to lower overall costs.
RAD can help reduce development costs by minimizing rework and avoiding unnecessary
features.
Increased Flexibility: The iterative nature of RAD allows for flexibility to adapt to changing
requirements or market conditions.
Techniques in RAD
1. Prototyping: Prototyping involves creating a preliminary version of the software application,
which is then iteratively refined based on user feedback. This technique allows developers to test
concepts, gather requirements, and refine the application's design and functionality.
5
namespace EventDrivenExample
{
public partial class Form1 : Form
{
public Form1()
{
6
InitializeComponent();
In this example:
1. A Button control is created and associated with a Button1_Click event handler.
2. When the button is clicked, the Button1_Click method is executed, displaying a message box.
using System;
using System.Windows.Forms;
public MainForm()
{
// Initialize the button
button1 = new Button();
button1.Text = "Click Me!";
button1.Location = new System.Drawing.Point(50, 50);
[STAThread]
public static void Main()
{
// Run the application
Application.Run(new MainForm());
}
}
Output Sample
Explanation:
MainForm Class: This class inherits from Form, which represents a window or dialog box in a
Windows Forms application.
Button Initialization: A Button control is created, and its properties like Text and Location are set.
Event Subscription: The Click event of the button is wired to the Button1_Click event handler
using the += operator. This means when the button is clicked, the Button1_Click method will be
executed.
Event Handler: The Button1_Click method is defined to show a message box when the button is
clicked.
Key Points:
The Click event is an example of an event in C#. It is triggered when the user clicks the button.
The Button1_Click method is the event handler that responds to the Click event.
Events in C# are managed using delegates, ensuring that the event handler signature matches the
expected method signature for the event.
4. IoT Applications: In Internet of Things (IoT) applications, sensors and devices generate events
that trigger actions or data processing. C# can be used to build event-driven IoT applications,
especially when using .NET-based frameworks.
Programming Model:
Object-Oriented: .NET follows an object-oriented paradigm, emphasizing encapsulation,
inheritance, and polymorphism.
Type Safety: Ensures strong type checking at compile time to prevent common programming
errors.
Garbage Collection: Automatically manages memory allocation and deallocation, reducing the
risk of memory leaks.
Generics: Provides type safety and code reusability through parameterized types.
Linq: A powerful query language for working with collections and data sources.
Architecture:
Layered Architecture: .NET applications often follow a layered architecture, separating
concerns into distinct layers:
o Presentation Layer: Handles the user interface and interaction.
o Business Logic Layer: Implements the core functionality and business rules.
o Data Access Layer: Interacts with databases or other data storage mechanisms.
Model-View-Controller (MVC): A popular architectural pattern that separates the application
into Model (data), View (user interface), and Controller (logic) components.
Dependency Injection: A design pattern that promotes loose coupling between components,
making code more testable and maintainable.
namespace HelloWorld
{
class Program
{
static void Main(string[] args)
{
// This is a simple .NET Core console
application Console.WriteLine("Hello, World!");
}
}
}
Explanation:
Namespace: HelloWorld is the namespace that encapsulates the application’s code, helping to
organize it.
Class: Program is the main class that contains the entry point of the application.
Main Method: static void Main(string[] args) is the entry point of the application, where the
execution starts.
Console.WriteLine: This is a method from the .NET Base Class Library that outputs a string to
the console.
Example 2:
using System;
namespace MyNamespace
{
class Program
{
static void Main(string[] args)
{
// Create an instance of a class
Person person = new Person("Alice", 30);
1.6. Environment and IDE Setup and Configuration: Visual Studio and VS Code
Overview
Setting up the development environment and configuring your Integrated Development Environment
(IDE) is crucial for a smooth development experience in .NET. Visual Studio and Visual Studio Code
(VS Code) are the two most popular IDEs for .NET development, each with its own strengths and use
cases.
Azure Tools: For managing Azure resources directly from the IDE.
GitHub Extension: For integrating with GitHub repositories.
4. Create a New Project:
o To start a new project, go to File > New > Project.
o Select the project template based on the type of application you want to build, such as
Console App (.NET Core), ASP.NET Core Web Application, or WPF App.
o Configure the project settings (name, location, framework) and click Create.
5. Build and Run:
o After setting up your project, you can write your code in the editor.
o Use the F5 key to build and run the project with debugging, or Ctrl+F5 to run without
debugging.
o Visual Studio provides a powerful debugger, allowing you to set breakpoints, step through
code, and inspect variables.
6. Version Control:
o Visual Studio integrates with Git, allowing you to manage source control directly within the
IDE.
o You can clone repositories, commit changes, and push updates to remote repositories using
the integrated Git tools.
dotnet build
dotnet run
o Alternatively, use the Run and Debug view to configure debugging. VS Code will prompt
you to create a launch.json file for debugging configuration.
7. Extensions and Integrations:
o VS Code has a rich ecosystem of extensions. Some useful ones for .NET development include:
NuGet Package Manager: For managing NuGet packages within your project.
Azure Tools: For integrating with Azure services.
GitLens: For advanced Git features and visualization.
Docker: For containerizing your .NET applications.
8. Version Control:
o VS Code has built-in Git support. You can view changes, stage commits, and manage
branches from the Source Control view.
o Extensions like GitHub Pull Requests and Issues allow you to manage pull requests and issues
directly from VS Code.
Unit 2
C# Language Basics
1. Value Types
Value types hold the data directly. Common examples include:
int: Stores integers.
float: Stores single-precision floating-point numbers.
double: Stores double-precision floating-point numbers.
char: Stores a single character.
bool: Stores a Boolean value (true or false).
struct: A composite value type that can contain variables of different types.
enum: A distinct type consisting of a set of named constants.
2. Reference Types
Reference types store the reference (or address) to the actual data. Common examples include:
string: A sequence of characters.
array: A collection of elements of the same type.
class: A blueprint for creating objects.
interface: A contract that defines a set of methods and properties.
delegate: A reference type that holds a reference to a method.
Namespaces
Namespaces in C# are used to organize code and prevent name collisions. They provide a way to
group related classes, structs, enums, delegates, and interfaces together.
The System namespace is the root of many base namespaces in .NET.
You can define your own namespaces to organize your code.
14
namespace MyNamespace
{
class Program
{
static void Main(string[] args)
{
int number = 10;
double decimalNumber =
3.14; bool isTrue = true;
char character = 'A';
Console.WriteLine(number);
Console.WriteLine(decimalNumber);
Console.WriteLine(isTrue);
Console.WriteLine(character);
}
}
}
Implicit Conversion
Implicit conversion is safe and doesn’t require special syntax. It occurs when the conversion is
guaranteed not to cause data loss.
Implicit Conversion Example:
int myInt = 10;
double myDouble = myInt; // Implicit conversion from int to double
C# also provides the Convert class for converting between different types. This class offers various
methods like Convert.ToInt32(), Convert.ToDouble(), Convert.ToString(), etc.
Code Example:
string myString = "123";
int myInt = Convert.ToInt32(myString); // Converts string to int
1. for Loop
The for loop is used when the number of iterations is known beforehand. It repeats a block of code
a specific number of times.
Syntax:
for (initialization; condition; increment)
{
// Code to be executed
}
2. while Loop
The while loop is used when the number of iterations is not known beforehand. It continues to
execute a block of code as long as a specified condition is true.
Syntax:
while (condition)
{
// Code to be executed
}
namespace WhileLoopExample
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("While Loop Example:");
int i = 1;
while (i <=
5) While
{
Console.WriteLine("Iteration: " +
i); i++;
}
}
}
}
3. do-while Loop
The do-while loop is similar to the while loop, but it checks the condition after executing the loop
body. This ensures that the loop body is executed at least once.
Syntax:
do
{ Loop
// Code to be executed
} while (condition);
Code Example:
using System;
namespace DoWhileLoopExample
{
class Program
{
17
Output
static void Main(string[] args)
{ Do-While Loop
Console.WriteLine("Do-While Loop Example:"); Example: Iteration: 1
Iteration: 2
int i = 1; Iteration: 3
do Iteration: 4
{ Iteration: 5
Console.WriteLine("Iteration: " +
i); i++;
} while (i <= 5);
}
}
}
4. foreach Loop
The foreach loop is specifically used to iterate through the elements of a collection (like an array or
a list). It is particularly useful when you don't need to modify the collection while iterating over it.
Syntax:
foreach (type variable in collection)
{
// Code to be executed
}
Code Example:
using System;
namespace ForeachLoopExample
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Foreach Loop Example:");
Output:
Foreach Loop
Example: Fruit: Apple
Fruit: Banana
Fruit: Cherry
Fruit: Date
Fruit:
Elderberry
Combining Loops with Conditional Statements
You can also combine loops with conditional statements to control the flow based on specific
conditions.
2.4. Arrays
Arrays in C# are ordered collections of elements of the same type.
Arrays in C# are used to store multiple values of the same type in a single variable. An array is a
collection of elements stored in a contiguous memory location, and each element can be accessed
using an index.
1. Declaring and Initializing Arrays
You can declare an array by specifying the type of its elements followed by square brackets. You
can also initialize the array with values at the time of declaration.
19
Code Example:
using System;
namespace ArrayExample
{
class Program
{
static void Main(string[] args)
{
// Declaring and initializing an array
int[] numbers = { 10, 20, 30, 40, 50 };
Console.WriteLine("Array Elements:");
Output:
Array Elements:
Element at index 0: 10
Element at index 1: 20
Element at index 2: 30
Element at index 3: 40
Element at index 4: 50
namespace AccessModifyArray
{
class Program
{
static void Main(string[] args)
{
// Declaring and initializing an
array string[] fruits = new string[3];
fruits[0] = "Apple";
fruits[1] =
"Banana"; fruits[2]
= "Cherry";
20
3. Multidimensional Arrays
C# supports multidimensional arrays, which are arrays of arrays. The most common
multidimensional array is the two-dimensional array, which can be thought of as a matrix or table.
Code Example: Output
4. Jagged Arrays
A jagged array is an array of arrays, where each inner array can have a different size. Unlike
multidimensional arrays, jagged arrays are not required to have uniform dimensions.
Console.WriteLine("Jagged Array:");
5. Array Methods
C# provides several methods to perform operations on arrays, such as sorting, reversing, and
finding elements.
Code Example:
using System;
namespace ArrayMethodsExample
{
class Program
{
static void Main(string[] args)
{
int[] numbers = { 5, 2, 9, 1, 5, 6 };
22
namespace StructExample
{
// Define a structure
struct Book
{
public string Title;
public string Author;
public int Year;
// Constructor
public Book(string title, string author, int year)
{
23
Title = title;
Author =
author; Year =
year;
}
class Program
{
static void Main(string[] args)
{
// Create an instance of the Book struct
Book book1 = new Book("1984", "George Orwell", 1949);
Output:
Enumerations in C#
Enumerations, or enums, are special data types that allow a variable to be a set of predefined
constants. They make your code more readable and manageable by replacing numeric constants with
descriptive names.
Defining an Enumeration
Enumerations are defined using the enum keyword, and each member of the enum is associated with
an integer value, starting from 0 by default.
Code Example:
using System;
namespace EnumExample
{
// Define an enumeration for days of the week
enum DayOfWeek
{
Sunday, // 0
Monday, // 1
Tuesday, // 2
Wednesday, // 3
Thursday, // 4
Friday, // 5
Saturday // 6
}
class Program
{
static void Main(string[] args)
{
// Assign an enum value to a variable
DayOfWeek today = DayOfWeek.Friday;
Output:
Today is:
Friday Day
number: 5
Days of the
week: Sunday = 0
Monday = 1
Tuesday = 2
Wednesday = 3
Thursday = 4
Friday = 5
Saturday = 6
Key Points about Enumerations:
Strongly Typed: Enums are strongly typed constants. An enum variable can only be assigned one
of the predefined enum constants.
Underlying Type: The default underlying type of the elements in the enum is int, but you can
specify another integral type (e.g., byte, short, long).
Custom Values: You can assign custom integer values to enum members.
namespace CustomEnumExample
{
// Define an enumeration with custom values
enum Severity
{
Low = 1,
Medium = 5,
High = 10,
Critical = 15
}
class Program
{
static void Main(string[] args)
{
// Assign and display a custom enum value
Severity level = Severity.High;
Console.WriteLine("Severity Level: " + level); // Outputs: Severity Level: High
Console.WriteLine("Severity Value: " + (int)level); // Outputs: Severity Value:
10
}
}
}
26
Output:
Severity Level:
High Severity
Value: 10
2.6. Strings, Regular Expressions and Collections
1. Strings in C#
Strings in C# are sequences of characters used to represent text. The string type is an alias for
System.String and is immutable, meaning once a string object is created, it cannot be changed.
String Operations
You can perform various operations on strings, such as concatenation, comparison, searching, and
more.
Code Example:
using System;
namespace StringExample
{
class Program
{
static void Main(string[] args)
{
string firstName = "John";
string lastName = "Doe";
// String concatenation
string fullName = firstName + " " + lastName;
Console.WriteLine("Full Name: " + fullName);
// String length
Console.WriteLine("Length of Full Name: " + fullName.Length);
// String comparison
bool areEqual = firstName.Equals(lastName);
Console.WriteLine("Are First Name and Last Name equal? " + areEqual);
// String substring
string substring = fullName.Substring(0, 4);
Console.WriteLine("Substring of Full Name: " + substring);
// String replace
string replacedString = fullName.Replace("John", "Jane");
Console.WriteLine("Replaced String: " + replacedString);
Output:
Full Name: John Doe
Length of Full Name:
8
Are First Name and Last Name equal?
False Substring of Full Name: John
Replaced String: Jane
Doe Upper Case: JOHN
DOE Lower Case: john
2. Regular Expressions in C#
Regular expressions (regex) are used to define patterns for matching strings. C# provides the
System.Text.RegularExpressions namespace for working with regular expressions.
namespace RegexExample
{
class Program
{
static void Main(string[] args)
{
string input = "The quick brown fox jumps over the lazy dog.";
Output:
Words found in input string:
The
quick
brown
fox
jumps
over
the
lazy
dog
String after replacement: THE QUICK BROWN FOX JUMPS OVER THE LAZY
3. Collections in C#
Collections in C# are used to store groups of related objects. The .NET Framework provides
several types of collections, including arrays, lists, dictionaries, and more. Collections are found in
the System.Collections and System.Collections.Generic namespaces.
Commonly Used Collections
1. List<T>: A generic collection that can store elements of a specific type.
2. Dictionary<TKey, TValue>: A collection that stores key-value pairs.
3. Queue<T>: A collection that represents a first-in, first-out (FIFO) queue.
4. Stack<T>: A collection that represents a last-in, first-out (LIFO) stack.
Code Example:
using System;
using System.Collections.Generic;
namespace CollectionsExample
{
class Program
{
static void Main(string[] args)
{
// List<T>
List<string> fruits = new List<string> { "Apple", "Banana", "Cherry" };
fruits.Add("Date");
Console.WriteLine("List of
Fruits:"); foreach (string fruit in
fruits)
{
Console.WriteLine(fruit);
}
29
Output
// Dictionary<TKey, TValue> List of
Dictionary<int, string> students = new Dictionary<int, Fruits: Apple
string>(); students.Add(1, "John"); Banana
students.Add(2, "Jane"); Cherry
students.Add(3, "Jim"); Console.WriteLine("\ Date
nDictionary of Students:"); foreach (KeyValuePair<int,
string> student in students)
Dictionary of
{
Students: ID: 1, Name:
Console.WriteLine("ID: " + student.Key + ", Name: " + student.Value);
} John
ID: 2, Name:
// Queue<T> Jane ID: 3,
Queue<string> queue = new Name: Jim
Queue<string>(); queue.Enqueue("First");
queue.Enqueue("Second"); Queue Elements:
queue.Enqueue("Third"); First
Console.WriteLine("\nQueue Elements:"); Second
while (queue.Count > 0) Third
{
Console.WriteLine(queue.Dequeue()); Stack
}
Elements:
// Stack<T> Third
Stack<string> stack = new
Stack<string>(); stack.Push("First");
stack.Push("Second");
stack.Push("Third");
Console.WriteLine("\nStack
Elements:"); while (stack.Count > 0)
{
Console.WriteLine(stack.Pop());
}
}
}
}
30
Unit 3
Object Oriented Concepts in C#
s1.id = 101;
s1.name = "Sonoo Jaiswal";
Console.WriteLine(s1.id);
Console.WriteLine(s1.name);
}
}
}
}
33
2. Method Overriding
If derived class defines same method as defined in its base class, it is known as method
overriding in C#. It is used to achieve runtime polymorphism. It enables you to provide
specific implementation of the method which is already provided by its base class.
To perform method overriding in C#, you need to use virtual keyword with base class method
and override keyword with derived class method.
Abstract method: can only be used in an abstract class, and it does not have a body. The body is
provided by the derived class (inherited from).
An abstract class can have both abstract and regular methods:
Example
using System;
namespace MyApplication
{
// Abstract class
abstract class Animal
{
// Abstract method (does not have a body)
public abstract void animalSound();
// Regular method
public void sleep()
{
Console.WriteLine("Zzz");
}
}
35
class Program
{
static void Main(string[] args)
{
Pig myPig = new Pig(); // Create a Pig object
myPig.animalSound();
myPig.sleep();
}
}
}
Output
2. Interfaces
Interface in C# is a blueprint of a class. It is like abstract class because all the methods which
are declared inside the interface are abstract methods. It cannot have method body and cannot
be instantiated.
It is used to achieve multiple inheritance which can't be achieved by class. It is used to achieve
fully abstraction because it cannot have method body.
Its implementation must be provided by class or struct. The class or struct which implements
the interface, must provide the implementation of all the methods declared inside the interface.
C# interface example
Let's see the example of interface in C# which has draw() method. Its implementation is provided
by two classes: Rectangle and Circle.
using System; Output
public interface Drawable drawing rectangle...
{
void draw(); drawing circle...
}
public class Rectangle : Drawable
{
public void draw()
{
Console.WriteLine("drawing rectangle...");
}
}
public class Circle : Drawable
{
public void draw()
{
Console.WriteLine("drawing circle...");
}
}
public class TestInterface
{
public static void Main()
{
Drawable d;
d = new Rectangle(); d.draw();
d = new Circle(); d.draw();} }
38
3. Encapsulation
Encapsulation is the concept of wrapping data into a single unit. It collects data members and
member functions into a single unit called class. The purpose of encapsulation is to prevent
alteration of data from outside. This data can only be accessed by getter functions of the class.
A fully encapsulated class has getter and setter functions that are used to read and write data.
This class does not allow data access directly.
Here, we are creating an example in which we have a class that encapsulates properties and
provides getter and setter functions.
Example Output
using System;
namespace AccessSpecifiers
{
class Program
{
static void Main(string[] args)
{
Student student = new Student();
// Setting values to the
properties student.ID = "101";
student.Name = "Mohan Ram";
student.Email = "[email protected]";
// getting values
Console.WriteLine("ID = "+student.ID);
Console.WriteLine("Name = "+student.Name)
;
Console.WriteLine("Email = "+student.Email)
;
}
}
}
39
4. Polymorphism
Polymorphism allows objects of different classes to be treated as objects of a common superclass.
It is the ability of different classes to respond to the same method call in different ways.
Example of Polymorphism:
The term "Polymorphism" is the combination of "poly" + "morphs" which means many forms.
It is a greek word. In object-oriented programming, we use 3 main concepts: inheritance,
encapsulation and polymorphism.
There are two types of polymorphism in C#: compile time polymorphism and runtime
polymorphism.
Compile time polymorphism is achieved by method overloading and operator overloading in
C#. It is also known as static binding or early binding.
Runtime polymorphism in achieved by method overriding which is also known as dynamic
binding or late binding.
}
public class TestPolymorphism
{
public static void Main()
{
Animal a= new Dog();
a.eat();
}
}
}
public class Circle : Shape
{
public override void draw()
{
Console.WriteLine("drawing circle...");
}
}
public class TestPolymorphism
{
public static void Main()
{
Shape s;
s = new
Shape();
s.draw();
s = new Rectangle();
s.draw();
s = new Circle();
s.draw();
}
}
5. Abstraction
Abstraction is the concept of hiding the complex implementation details and showing only the
essential features of the object. It allows you to focus on what the object does rather than how
it does it.
Data abstraction is the process of hiding certain details and showing only essential
information to the user.
Abstraction can be achieved with either abstract classes or interfaces.
The abstract keyword is used for classes and methods:
Abstract class: is a restricted class that cannot be used to create objects (to access it, it must be
inherited from another class).
Abstract method: can only be used in an abstract class, and it does not have a body. The body
is provided by the derived class (inherited from).
Example of Abstraction
using System;
public abstract class Shape
{
public abstract void draw();
}
41
6. Visual Inheritance
Visual Inheritance in C# is a feature in Visual Studio that allows developers to create derived
forms (or controls) that inherit the visual interface of a base form (or control). This is particularly
useful in Windows Forms applications, where you can create a base form with common UI
elements and then derive other forms from it.
// This would be in
BaseForm.cs public class
BaseForm : Form
{
protected Button commonButton;
public BaseForm()
{
InitializeComponent();
}
42
It maintains the normal flow of the application. In such case, rest of the code is executed event after
exception.
C# Exception Handling Keywords
In C#, we use 4 keywords to perform exception handling:
o try
o catch
o finally, and
o throw
C# try/catch example
using System;
public class ExExample
{
public static void Main(string[] args)
{
try
{
int a = 10;
int b = 0;
int x = a / b;
}
catch (Exception e) { Console.WriteLine(e); }
Output:
C# finally
C# finally block is used to execute important code which is to be executed whether exception is
handled or not. It must be preceded by catch or try block.
C# finally example if exception is handled
using System;
public class Example
{
public static void Main(string[] args)
{
try
{
int a = 10;
int b = 0;
int x = a / b;
}
catch (Exception e)
{
Console.WriteLine(e);
}
finally
44
{
Console.WriteLine("Finally block is executed");
}
Console.WriteLine("Rest of the code");
}
}
Output:
1. System-Defined Exceptions
System-defined exceptions are exceptions that are part of the .NET framework and are raised when
common errors occur during program execution.
Example of System-Defined Exceptions:
Example 1
using System;
class Program
{
static void Main(string[] args)
{
try
{
int[] numbers = { 1, 2, 3 };
Console.WriteLine(numbers[5]); // IndexOutOfRangeException
}
catch (IndexOutOfRangeException ex)
{
Console.WriteLine($"Caught an exception: {ex.Message}");
}
finally
{
Console.WriteLine("This block is always executed.");
}
}
}
Output:
45
Example 2
using System;
public class ExExample
{
public static void Main(string[] args)
{
try
{
int a = 10;
int b = 0;
int x = a /
b;
}
catch (Exception e)
{
Console.WriteLine(e);
}
finally
{ Console.WriteLine("Finally block is executed");
}
Console.WriteLine("Rest of the code");
}
}
Output:
Explanation:
The try block contains code that may cause an exception.
The catch block catches and handles the Exception e.
The finally block always executes, whether an exception was caught or not.
2. Custom/User-defined Exceptions
In addition to using system-defined exceptions, you can create custom exceptions to
represent specific error conditions in your application. Custom exceptions are typically
derived from the System.Exception class.
C# allows us to create user-defined or custom exception. It is used to make the meaningful
exception. To do this, we need to inherit Exception class.
Example of a Custom Exception:
To create a user-defined exception, you need to create a new class that inherits from the
System.Exception class or one of its derived classes.
using System;
}
}
class Program
{
static void Main(string[] args)
{
try
{
throw new CustomException("This is a custom exception.");
}
catch (CustomException ex)
{
Console.WriteLine($"Custom Exception: {ex.Message}");
}
catch (Exception ex)
{
Console.WriteLine($"General Exception: {ex.Message}");
}
}
}
Output:
}
}
public class TestUserDefinedException
{
static void validate(int age)
{
if (age < 18)
{
throw new InvalidAgeException("Sorry, Age must be great an 18");
}
}
public static void Main(string[] args)
{
try
{
validate(12);}
47
catch (InvalidAgeException e) { Console.WriteLine(e); }
Console.WriteLine("Rest of the code");
}
}
Output:
3. Throwing Exceptions
The throw keyword is used to explicitly raise an exception. You can throw system-defined
exceptions or custom exceptions.
Example of Throwing Exceptions:
using System;
class Program
{
static void Main(string[] args)
{
try
{
int dividend = 10;
int divisor = 0;
if (divisor ==
0)
{
throw new DivideByZeroException("Cannot divide by zero.");
}
int result = dividend / divisor;
}
catch (DivideByZeroException ex)
{
Console.WriteLine($"Caught an exception: {ex.Message}");
}
}
}
Output:
Explanation:
The throw statement is used to raise a DivideByZeroException when an attempt to divide by
zero is detected.
The catch block catches the exception and prints the error message.
48
Example 2
using System;
namespace MyApplication
{
class Program
{
static void checkAge(int age)
{
if (age < 18)
{
throw new ArithmeticException("Access denied - You must be at least 18 years old.");
}
else
{
Console.WriteLine("Access granted - You are old enough!");
}
}
Output
1. Parallel Programming
Parallel programming in C# can be achieved using the System.Threading.Tasks namespace, which
provides several ways to run code concurrently, including Parallel.For, Parallel.ForEach, and the
Task class.
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Parallel For
loop:"); Parallel.For(0, 10, i =>
{
49
Console.WriteLine("\nParallel ForEach
loop:"); int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8,
9, 10 };
Parallel.ForEach(numbers, number =>
{
Console.WriteLine($"Processing number {number} on thread {Task.CurrentId}");
});
Console.WriteLine("\nParallel Tasks:");
Task task1 = Task.Run(() => PrintNumbers("Task
1")); Task task2 = Task.Run(() =>
PrintNumbers("Task 2")); Task.WaitAll(task1, task2);
}
Parallel Tasks:
Task 1 - Number: 1
Task 1 - Number: 2
Task 1 - Number: 3
Task 1 - Number: 4
Task 1 - Number: 5
Task 2 - Number: 1
Task 2 - Number: 2
Task 2 - Number: 3
Task 2 - Number: 4
Task 2 - Number: 5
Explanation:
Parallel.For: This method runs a for loop in parallel, distributing the iterations across multiple
threads.
Parallel.ForEach: This method works like Parallel.For, but is used for iterating over collections.
Tasks: Tasks represent asynchronous operations. The Task.Run method is used to run a
method asynchronously, and Task.WaitAll waits for all tasks to complete.
2. Concurrent Collections
Concurrent collections in C# are part of the System.Collections.Concurrent namespace and are
designed to handle multi-threaded scenarios safely. Common concurrent collections include
ConcurrentDictionary, ConcurrentQueue, ConcurrentStack, and ConcurrentBag.
class Program
{
static void Main(string[] args)
{
ConcurrentDictionary<int, string> dict = new ConcurrentDictionary<int, string>();
Console.WriteLine("ConcurrentDictionary contents:");
foreach (var kvp in dict)
{
Console.WriteLine($"{kvp.Key}: {kvp.Value}");
}
ConcurrentQueue<int> queue = new ConcurrentQueue<int>();
Output:
ConcurrentDictionary contents:
0: Value 0
1: Value 1
2: Value 2
3: Value 3
4: Value 4
5: Value 5
6: Value 6
7: Value 7
8: Value 8
9: Value 9
ConcurrentQueue
contents: 0
1
2
3
4
5
6
7
8
9
Explanation:
ConcurrentDictionary: A thread-safe dictionary where you can add, update, or remove key-
value pairs concurrently.
ConcurrentQueue: A thread-safe FIFO (First-In-First-Out) collection that allows multiple
threads to enqueue and dequeue items safely.
52
Unit 4
ADO.NET and WPF (Windows Presentation Foundation)
From the above components, two components are compulsory. One is the command object and the
other one is the connection object. Irrespective of the operations like Insert, Update, Delete and Select,
the command and connection object you always need. For a better understanding, please have a look at
the following image.
53
OR
Oracle, MySQL, etc. To create a connection object, you need at least two things. The first one is
where is your database located i.e. the Machine name or IP Address or someplace where your
database is located. And the second thing is the security credentials i.e. whether it is a Windows
authentication or SQL Authentication i.e. user name and password-based authentication. So, the
first is to create the connection object and the connection object is required to connect the front-
end application with the backend data source.
2. Command:
The Second important component of ADO.NET Architecture is the Command Object. When we
talk about databases like SQL Server, Oracle, MySQL, etc., we know one thing, these databases
only understand SQL. The Command Object is the component where you go and write your SQL
queries. Later you take the command object and execute it over the connection. That means using
the command object, you can fetch data or send data to the database i.e. performing the Database
CRUD Operations.
Note: From the Command Object onwards, you can go in two different ways. One is you can go
with the DataSet way and the other is, you can go with the DataReader way. Which way you
need to choose, basically will depend on the situation.
3. DataReader:
DataReader is a read-only connection-oriented recordset that helps us to read the records only in
the forward mode. Here, you need to understand three things i.e. read-only, connection-oriented,
and forward mode. Read-Only means using DataReader, we cannot Insert, Update, and Delete the
data. Connection-Oriented means, it always requires an active and open connection to fetch the
data. Forward mode means you can always read the next record, there is no way that you can read
the previous record.
4. DataSet:
It is a Disconnected record set that can be browsed in both i.e. forward and backward mode. It is
not read-only i.e. you can update the data present in the data set. Actually, DataSet is a
collection of DataTables that holds the data and we can add, update, and delete data in a data
table. DataSet gets filled by somebody called DataAdapter.
5. DataAdapter:
The DataAdapter is one of the Components of ADO.NET which acts as a bridge between the
command object and the dataset. What the DataAdapter does is, it takes the data from the
command object and fills the data set.
6. DataView Class
The DataView class enables us to create different views of the data stored in a DataTable. This is
most often used in data-binding applications. Using a DataView, we can expose the data in a table
with different sort orders, and you can filter the data by row state or based on a filter expression.
CommandBuilder:
Automatically generates SQL commands based on changes made to the DataSet, simplifying the
process of updating the database.
class Program
{
static void Main()
{
string connectionString = "Server=your_server_name;Database=your_database_name;User
Id=your_username;Password=your_password;";
Output
Connection to the database is successful.
class Program
{
static void Main()
{
string connectionString = "Server=your_server_name;Database=your_database_name;User
Id=your_username;Password=your_password;";
SqlDataReader reader =
command.ExecuteReader(); while (reader.Read())
{
Console.WriteLine($"{reader["EmployeeID"]}, {reader["FirstName"]},
56
{
reader["LastName"]}");
}
reader.Close();
}
}
}
Output
1, John, Doe
2, Jane, Smith
class Program
{
static void Main()
{
string connectionString = "Server=your_server_name;Database=your_database_name;User
Id=your_username;Password=your_password;";
Output
1 row(s) inserted.
57
class Program
{
static void Main()
{
string connectionString = "Server=your_server_name;Database=your_database_name;User
Id=your_username;Password=your_password;";
Output
1 row(s) updated.
class Program
{
static void Main()
{
string connectionString = "Server=your_server_name;Database=your_database_name;User
Id=your_username;Password=your_password;";
Output
1 row(s) deleted.
Connection Classes
Each data provider includes a connection class that establishes a connection to the database. The most
common connection classes are:
SqlConnection: For SQL Server.
OracleConnection: For Oracle databases.
OleDbConnection: For databases using OLE DB.
OdbcConnection: For databases using ODBC.
Connection Strings
Connection strings contain the information required to establish a connection to a database, such as the
server name, database name, and credentials.
Example: SQL Server Connection String
"Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;"
Connection Pooling
Connection pooling improves performance by reusing existing connections instead of opening and
closing connections for each request. This reduces the overhead associated with establishing new
connections.
59
class Program
{
static void Main()
{
string connectionString = "Server=myServerAddress;Database=myDataBase;User
Id=myUsername;Password=myPassword;";
Output
Connection state changed from Closed to Open.
Connection opened.
Connection state changed from Open to Closed.
Full Code Example: Connecting to SQL Server with Connection Pooling and Events
using System;
using System.Data.SqlClient;
class Program
{
static void Main()
{
60
connection.Open();
Console.WriteLine("Connection
opened.");
connection.Close();
Console.WriteLine("Connection closed.");
}
}
Output:
Connection state changed from Closed to Open.
Connection opened.
Connection state changed from Open to Closed.
Connection closed.
ExecuteNonQuery() Executes a command that does not return rows (e.g., INSERT, UPDATE,
DELETE).
ExecuteScalar() Executes a command and returns a single value (e.g., aggregate functions).
1. Command Object
The Command object in ADO.NET represents a SQL command or stored procedure to be
executed. It is part of the .NET Data Provider's namespace and is specific to each type of database:
SqlCommand: Used with SQL Server.
OleDbCommand: Used with OLE DB data sources.
OdbcCommand: Used with ODBC data sources.
2. Creating a Command
To create a command, you instantiate a Command object, set its properties (like CommandText
and CommandType), and then execute it using one of the available methods (ExecuteReader,
ExecuteNonQuery, ExecuteScalar, ExecuteXmlReader).
Example: Creating a SqlCommand Object
using System;
using System.Data.SqlClient;
class Program
{
static void Main()
{
string connectionString = "Server=myServerAddress;Database=myDataBase;
User Id=myUsername;Password=myPassword;";
Output:
Total Employees: 100
3. Executing Commands
There are different methods to execute a command depending on what you want to achieve:
a. ExecuteReader()
Used when you need to retrieve rows from a data source.
using System;
using System.Data.SqlClient;
class Program
{
static void Main()
{
string connectionString = "Server=myServerAddress;Database=myDataBase;
User Id=myUsername;Password=myPassword;";
using System;
using System.Data.SqlClient;
class Program
{
static void Main()
{
string connectionString = "Server=myServerAddress;Database=myDataBase;User
Id=myUsername;Password=myPassword;";
Output:
1 row(s) inserted....
1. Batch Queries
Batch queries involve executing multiple SQL statements in a single database round trip. This is
particularly useful when you want to perform multiple operations (like inserts, updates, and deletes)
together.
Example: Executing a Batch Query with ExecuteNonQuery()
using System;
using System.Data.SqlClient;
class Program
{
64
Output:
2 row(s) affected. // Total number of affected rows across all operations
2. Stored Procedures
Stored procedures are precompiled collections of SQL statements stored in the database. They can
accept parameters, perform complex operations, and return results. They are efficient because they are
compiled and stored in the database, reducing the need to send SQL code over the network repeatedly.
Example: Creating and Executing a Stored Procedure
1. Create a Stored Procedure in SQL Server
CREATE PROCEDURE GetEmployeeCountByDepartment
@DepartmentName NVARCHAR(50)
AS
BEGIN
SELECT COUNT(*) AS
EmployeeCount FROM Employees
WHERE Department =
@DepartmentName; END;
class Program
{
65
static void Main()
{
string connectionString = "Server=myServerAddress;Database=myDataBase;
User Id=myUsername;Password=myPassword;";
Output:
class Program
{
static void Main()
{
66
Departments:
1, Sales
2, Marketing
67
class Program
{
static void Main()
{
string connectionString = "Server=myServerAddress;Database=myDataBase;
User Id=myUsername;Password=myPassword;";
string selectCommandText = "SELECT EmployeeID, FirstName, LastName FROM Employees";
Output:
EmployeeID: 1, Name: John Doe
EmployeeID: 2, Name: Jane
Smith
2. Modifying Data and Updating the Database
Next, let's modify the data in the DataSet and update the database.
using System;
using
System.Data;
using System.Data.SqlClient;
class Program
{
static void Main()
{
string connectionString = "Server=myServerAddress;Database=myDataBase;
User Id=myUsername;Password=myPassword;";
string selectCommandText = "SELECT EmployeeID, FirstName, LastName FROM Employees";
Output:
Updated Data:
EmployeeID: 1, Name: John Smith
EmployeeID: 3, Name: Michael Jordan
Explanation:
1. Filling the DataSet:
o The SqlDataAdapter is used to fill the DataSet with data from the Employees table in the
database.
o The DataSet contains a DataTable named "Employees".
2. Modifying Data:
o We modify the last name of the first employee.
o A new employee ("Michael Jordan") is added to the DataTable.
o The second employee ("Jane Smith") is deleted from the DataTable.
3. Updating the Database:
o The SqlDataAdapter is used to update the database with the changes made in the DataSet.
o The SqlCommandBuilder automatically generates the necessary SQL commands (INSERT,
UPDATE, DELETE) based on the modifications in the DataTable.
class Program
{
static void Main()
{
// Define the connection string
string connectionString = "Server=myServerAddress;Database=myDataBase;
User Id=myUsername;Password=myPassword;";
// Create a DataContext
DataContext dataContext = new DataContext(connectionString);
[Column]
public string ProductName { get; set; }
[Column]
public decimal Price { get; set; }
}
Output:
Products with Price > 300:
ProductID: 1, Name: Laptop, Price: 800.00
ProductID: 2, Name: Smartphone, Price: 500.00
72
Explanation:
1. DataContext and Product Entity:
o DataContext is used to manage the connection and translate LINQ queries to SQL.
o The Product class is decorated with [Table] and [Column] attributes, mapping it to the
Products table in the database.
2. LINQ Query:
o The LINQ query retrieves products where the price is greater than 300.
o The results are loaded into a DataTable within a DataSet.
3. Loading Data into DataSet:
o The DataTable is defined with columns corresponding to the Products table.
o The query results are added as rows in the DataTable, which is then added to the DataSet.
4. Displaying Data:
o The contents of the DataTable are displayed, showing products with prices greater than 300.
4.9 WPF Controls, Layouts, Dialogs, Menus, Commands and Data bindings
WPF is known as Windows Presentation Foundation. Windows Presentation Foundation is known as
the development framework. WPF is also known as the sub-system of the .Net framework. Windows
Presentation Foundation framework can build the Windows Client Application. Windows Application
can run on the Windows Operating System. We use XAML language for the frontend and C# language
as the backend.
Windows Presentation Foundation (WPF) is a powerful UI framework in .NET that allows developers
to create rich and interactive applications. This section covers WPF controls, layouts, dialogs, menus,
commands, and data bindings.
WPF employs XAML, which is an XML based language. XML is used to define and link the various
elements. An application that is developed with the use of the WPF, we can deploy them as the
Standalone desktop programs, or we can host the WPF applications as the embedded object on a
website.
1. WPF Controls
WPF Controls are the building blocks for any user interface in a WPF application. Common controls
include Button, TextBox, Label, ListBox, etc.
Example: Basic WPF Controls
XML
<Window x:Class="WpfApp.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="WPF Controls Example" Height="200" Width="300">
<StackPanel Margin="10">
<TextBlock Text="Enter your name:" />
<TextBox Name="nameTextBox" Width="200" Margin="0,5,0,5"/>
<Button Content="Submit" Click="SubmitButton_Click" Width="200"/>
<Label Name="outputLabel" Margin="0,10,0,0"/>
</StackPanel>
</Window>
Csharp
using System.Windows;
namespace WpfApp
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
Output:
A simple UI where the user enters their name in a text box. When the "Submit" button is clicked, a
greeting message is displayed in the label.
Visual Diagram:
StackPanel arranges the controls vertically.
TextBlock prompts the user for input.
TextBox captures user input.
Button triggers an action when clicked.
Label displays the result.
74
2. Layouts
Layouts in WPF determine how UI elements are arranged on the screen. Some common layout
panels include Grid, StackPanel, DockPanel, and Canvas.
Example: Using Grid Layout
XML
<<Window x:Class="WpfApp.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="WPF Layout Example" Height="200" Width="300">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
3. Dialogs
Dialogs are windows that prompt the user to provide information or make decisions. WPF
provides several built-in dialogs like MessageBox, OpenFileDialog, and SaveFileDialog.
Csharp
private void ShowMessageBox()
{
MessageBoxResult result = MessageBox.Show("Do you want to continue?", "Confirmation",
MessageBoxButton.YesNo, MessageBoxImage.Question);
if (result == MessageBoxResult.Yes)
{
MessageBox.Show("You chose to continue.", "Information", MessageBoxButton.OK,
MessageBoxImage.Information);
}
else
{
MessageBox.Show("You chose not to continue.", "Information", MessageBoxButton.OK,
MessageBoxImage.Information);
}
}
Output:
A dialog box asking the user if they want to continue, with subsequent messages based on the
user's choice.
Visual Diagram:
MessageBox shows a prompt with Yes/No options.
Result Handling determines the next step based on user input.
4. Menus
Menus are used to organize commands or options in a hierarchical structure. The Menu and
MenuItem controls are used to create these menus.
Example: Creating a Menu
XML
<Window x:Class="WpfApp.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="WPF Menu Example" Height="300" Width="400">
<DockPanel>
<Menu DockPanel.Dock="Top">
<MenuItem Header="_File">
<MenuItem Header="_New" Click="New_Click"/>
<MenuItem Header="_Open" Click="Open_Click"/>
<Separator/>
<MenuItem Header="_Exit" Click="Exit_Click"/>
</MenuItem>
<MenuItem Header="_Edit">
<MenuItem Header="_Copy" Click="Copy_Click"/>
<MenuItem Header="_Paste" Click="Paste_Click"/>
</MenuItem>
</Menu>
76
Csharp
using System.Windows;
namespace WpfApp
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
Output:
A text editor window with a menu containing File and Edit options.
Visual Diagram:
77
5. Commands
Commands encapsulate the logic for actions that can be triggered by controls. WPF uses
the ICommand interface to implement commands, allowing separation of UI and business
logic. Example: Implementing a Simple Command
Csharp
using System;
using System.Windows;
using System.Windows.Input;
namespace WpfApp
{
public partial class MainWindow : Window
{
public ICommand MyCommand { get; set; }
public MainWindow()
{
InitializeComponent();
MyCommand = new RelayCommand(ExecuteMyCommand, CanExecuteMyCommand);
DataContext = this;
}
XML
<Window x:Class="WpfApp.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="WPF Command Example" Height="200" Width="300">
<StackPanel>
<Button Content="Click Me" Command="{Binding MyCommand}" Width="100"
Height="30" Margin="10"/>
</StackPanel>
</Window>
Output:
A button that, when clicked, triggers the command and shows a message box.
Visual Diagram:
Button is bound to a command via the Command property.
Command Execution shows a message box.
6. Data Binding
Data Binding in WPF is a powerful mechanism that connects the UI to data sources like objects, collections,
or databases. It enables automatic updates of the UI when the underlying data changes.
Example: Simple Data Binding
Csharp
public class Person
{
public string Name { get; set;
} public int Age { get; set; }
}
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = new Person { Name = "John Doe", Age = 30 };
}
}
79
XML
<Window x:Class="WpfApp.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
<StackPanel>
</StackPanel>
</Window>
Output:
A form where the text boxes are automatically populated with data from a Person object.
Visual Diagram:
DataContext is set to a Person object.
TextBoxes are bound to properties of the Person object.
80
Unit 5
ASP.NET and ASP.NET Core
app.Run();
Explanation:
WebApplication.CreateBuilder: Sets up the application with default configurations.
app.MapGet("/"): Maps the root URL (/) to a simple handler that returns "Hello, World!".
app.Run(): Runs the application.
namespace MyMvcApp.Controllers
{
public class HomeController : Controller
{
public IActionResult Index()
{
ViewData["Message"] = "Welcome to ASP.NET Core
MVC!"; return View();
}
}
}
3. Add a View:
Create a Views/Home/Index.cshtml file:
HTML
@page
@{
ViewData["Title"] = "Home";
}
<h2>@ViewData["Message"]</h2>
82
3. Controller: Manages user requests, interacts with the model, and renders the appropriate view.
Diagram: MVC Architecture
using Microsoft.AspNetCore.Mvc;
using MyMvcApp.Models;
using System.Collections.Generic;
namespace MyMvcApp.Controllers
{
public class ProductsController : Controller
{
// Simulating a database with an in-memory list of products
private static readonly List<Product> Products = new
List<Product>
{
new Product { Id = 1, Name = "Laptop", Price = 999.99M, Description = "A high-
performance laptop." },
new Product { Id = 2, Name = "Smartphone", Price = 499.99M, Description = "A sleek
smartphone." }
};
Details View (Product Details): Create a Details.cshtml file in the Views/Products folder to display the
product details:
@model MyMvcApp.Models.Product
<h2>@Model.Name</h2>
<p><strong>Price:</strong> @Model.Price.ToString("C")</p>
<p><strong>Description:</strong> @Model.Description</p>
Now, open a browser and navigate to https://localhost:5001/Products to view the list of products. You
can click on the "View Details" link for any product to see more information.
Output
Index View (List of Products):
OR
6. Implementing Security
Security is crucial, and ASP.NET MVC 5 provides several features to secure your applications:
Use ASP.NET Identity for authentication and authorization.
Enable SSL in your project to ensure data is encrypted during transit.
Prevent cross-site scripting (XSS) by encoding HTML outputs.
Protect against cross-site request forgery (CSRF) using anti-forgery tokens in your forms.
By following these steps, you can systematically build a web application using ASP.NET MVC 5,
from initial setup to deployment. There are a few steps to check before, during and after deployment,
which we will talk about below.
[Route("api/[controller]")]
[ApiController]
public class ProductsController : ControllerBase
{
private static readonly List<Product> Products = new List<Product>
{
new Product { Id = 1, Name = "Laptop", Price = 999.99M, Description = "A high-performance
laptop." },
new Product { Id = 2, Name = "Smartphone", Price = 499.99M, Description = "A sleek
smartphone." }
};
// GET: api/products
[HttpGet]
public ActionResult<IEnumerable<Product>> GetProducts()
{
return Products;
}
// GET: api/products/{id}
[HttpGet("{id}")]
public ActionResult<Product> GetProduct(int id)
{
var product = Products.FirstOrDefault(p => p.Id == id);
if (product == null)
return NotFound();
return product;
}
// POST: api/products
[HttpPost]
public ActionResult<Product> CreateProduct(Product product)
{
product.Id = Products.Count + 1;
Products.Add(product);
return CreatedAtAction(nameof(GetProduct), new { id = product.Id }, product);
}
// PUT: api/products/{id}
[HttpPut("{id}")]
public IActionResult UpdateProduct(int id, Product updatedProduct)
{
var product = Products.FirstOrDefault(p => p.Id == id);
if (product == null)
return NotFound();
89
product.Name = updatedProduct.Name;
product.Price =
updatedProduct.Price;
product.Description =
updatedProduct.Description; return NoContent();
}
// DELETE: api/products/{id}
[HttpDelete("{id}")]
public IActionResult DeleteProduct(int id)
{
var product = Products.FirstOrDefault(p => p.Id == id);
if (product == null)
return NotFound();
Products.Remove(product);
return NoContent();
}
}
4. Test the API Endpoints: You can use tools like Postman or Swagger (built-in to ASP.NET Core
templates) to test each endpoint.
<h1>@ViewData["Title"]</h1>
<p>Welcome to the ASP.NET Core Razor page example!</p>
2. Use C# Code: You can insert C# code in Razor pages with the @ symbol.
html
<h2>@DateTime.Now.ToString("yyyy-MM-dd")</h2>
Unit 6
Web Applications with Blazor
Unit 7
Cross-Platform Development with Xamarin