Top 100 C# (C-sharp) Interview Programs with Answers
1. Hello World Program:
using System;
class HelloWorld
{
static void Main(string[] args)
{
Console.WriteLine("Hello,
World!");
}
}
2. Variables and Data Types:
using System;
class VariablesAndDataTypes
{
static void Main(string[] args)
{
int age = 25;
double salary = 50000.50;
string name = "John";
Console.WriteLine($"Name: {name},
Age: {age}, Salary: {salary}");
}
}
3. Arithmetic Operations:
using System;
class ArithmeticOperations
{
static void Main(string[] args)
{
int num1 = 10;
int num2 = 5;
int sum = num1 + num2;
int difference = num1 - num2;
int product = num1 * num2;
double quotient = (double)num1 / num2;
Console.WriteLine($"Sum: {sum},
Difference: {difference}, Product: {product}, Quotient: {quotient}");
}
}
4. Conditional Statements (if-else):
using System;
class ConditionalStatements
{
static void Main(string[] args)
{
int num = 10;
if (num > 0)
{
Console.WriteLine("Number is
positive.");
}
else if (num < 0)
{
Console.WriteLine("Number is
negative.");
}
else
{
Console.WriteLine("Number is
zero.");
}
}
}
5. Loops (for, while):
using System;
class Loops
{
static void Main(string[] args)
{
// For loop
for (int i = 1; i <= 5; i++)
{
Console.WriteLine($"For loop
iteration: {i}");
}
// While loop
int j = 1;
while (j <= 5)
{
Console.WriteLine($"While loop
iteration: {j}");
j++;
}
}
}
6. Basic Input/Output:
using System;
class BasicIO
{
static void Main(string[] args)
{
Console.Write("Enter your name:
");
string name = Console.ReadLine();
Console.WriteLine($"Hello,
{name}!");
}
}
7. Arrays and Lists:
7.1 Finding the largest element in an array:
using System;
class LargestElement
{
static void Main(string[] args)
{
int[] numbers = { 10, 5, 20, 15, 25 };
int max = numbers[0];
foreach (int num in numbers)
{
if (num > max)
{
max = num;
}
}
Console.WriteLine($"The largest
element is: {max}");
}
}
7.2 Reversing an array:
using System;
class ReverseArray
{
static void Main(string[] args)
{
int[] numbers = { 10, 20, 30, 40, 50 };
int[] reversed = new
int[numbers.Length];
for (int i = 0; i < numbers.Length;
i++)
{
reversed[numbers.Length - 1 - i] =
numbers[i];
}
Console.Write("Reversed array:
");
foreach (int num in reversed)
{
Console.Write($"{num} ");
}
}
}
7.3 Finding duplicates in an array:
using System;
class FindDuplicates
{
static void Main(string[] args)
{
int[] numbers = { 2, 3, 4, 2, 7, 8, 4
};
Console.Write("Duplicate elements:
");
for (int i = 0; i < numbers.Length;
i++)
{
for (int j = i + 1; j <
numbers.Length; j++)
{
if (numbers[i] == numbers[j])
{
Console.Write($"{numbers[i]} ");
break;
}
}
}
}
}
7.4 Implementing a stack using an array:
using System;
class StackUsingArray
{
private int maxSize;
private int[] stackArray;
private int top;
public StackUsingArray(int size)
{
maxSize = size;
stackArray = new int[maxSize];
top = -1;
}
public void Push(int value)
{
if (top < maxSize - 1)
{
stackArray[++top] = value;
}
else
{
Console.WriteLine("Stack is
full. Cannot push element.");
}
}
public int Pop()
{
if (top >= 0)
{
return stackArray[top--];
}
else
{
Console.WriteLine("Stack is
empty. Cannot pop element.");
return -1;
}
}
public void PrintStack()
{
Console.Write("Stack: ");
for (int i = 0; i <= top; i++)
{
Console.Write($"{stackArray[i]} ");
}
Console.WriteLine();
}
static void Main(string[] args)
{
StackUsingArray stack = new
StackUsingArray(5);
stack.Push(10);
stack.Push(20);
stack.Push(30);
stack.PrintStack();
int poppedValue = stack.Pop();
Console.WriteLine($"Popped value:
{poppedValue}");
stack.PrintStack();
}
}
7.5 Implementing a queue using an array:
using System;
class QueueUsingArray
{
private int maxSize;
private int[] queueArray;
private int front;
private int rear;
private int itemCount;
public QueueUsingArray(int size)
{
maxSize = size;
queueArray = new int[maxSize];
front = 0;
rear = -1;
itemCount = 0;
}
public void Enqueue(int value)
{
if (itemCount < maxSize)
{
if (rear == maxSize - 1)
{
rear = -1;
}
queueArray[++rear] = value;
itemCount++;
}
else
{
Console.WriteLine("Queue is
full. Cannot enqueue element.");
}
}
public int Dequeue()
{
if (itemCount > 0)
{
int dequeuedValue =
queueArray[front++];
if (front == maxSize)
{
front = 0;
}
itemCount--;
return dequeuedValue;
}
else
{
Console.WriteLine("Queue is
empty. Cannot dequeue element.");
return -1;
}
}
public void PrintQueue()
{
Console.Write("Queue: ");
for (int i = 0; i < itemCount; i++)
{
int index = (front +
i) % maxSize;
Console.Write($"{queueArray[index]} ");
}
Console.WriteLine();
}
static void Main(string[] args)
{
QueueUsingArray queue = new
QueueUsingArray(5);
queue.Enqueue(10);
queue.Enqueue(20);
queue.Enqueue(30);
queue.PrintQueue();
int dequeuedValue = queue.Dequeue();
Console.WriteLine($"Dequeued
value: {dequeuedValue}");
queue.PrintQueue();
}
}
7.6 Working with Lists (Add, Remove, Search):
using System;
using
System.Collections.Generic;
class ListsExample
{
static void Main(string[] args)
{
List<string> names = new
List<string>();
names.Add("Alice");
names.Add("Bob");
names.Add("Charlie");
Console.WriteLine("List
contents:");
foreach (string name in names)
{
Console.WriteLine(name);
}
names.Remove("Bob");
Console.WriteLine("\nList after
removing 'Bob':");
foreach (string name in names)
{
Console.WriteLine(name);
}
if
(names.Contains("Charlie"))
{
Console.WriteLine("\n'Charlie'
found in the list.");
}
else
{
Console.WriteLine("\n'Charlie'
not found in the list.");
}
}
}
8. Strings:
8.1 Reversing a string:
using System;
class ReverseString
{
static void Main(string[] args)
{
string input = "Hello,
World!";
char[] charArray = input.ToCharArray();
Array.Reverse(charArray);
string reversed = new
string(charArray);
Console.WriteLine($"Reversed
string: {reversed}");
}
}
8.2 Checking if a string is a palindrome:
using System;
class PalindromeCheck
{
static bool IsPalindrome(string str)
{
int left = 0;
int right = str.Length - 1;
while (left < right)
{
if (str[left] != str[right])
{
return false;
}
left++;
right--;
}
return true;
}
static void Main(string[] args)
{
string input = "racecar";
if (IsPalindrome(input))
{
Console.WriteLine($"{input} is
a palindrome.");
}
else
{
Console.WriteLine($"{input} is
not a palindrome.");
}
}
}
8.3 Counting occurrences of a character:
using System;
class CountOccurrences
{
static void Main(string[] args)
{
string input = "programming";
char target = 'r';
int count = 0;
foreach (char c in input)
{
if (c == target)
{
count++;
}
}
Console.WriteLine($"Occurrences of
'{target}' in '{input}': {count}");
}
}
8.4 Finding the first non-repeated character:
using System;
using
System.Collections.Generic;
class FirstNonRepeated
{
static char FindFirstNonRepeated(string
str)
{
Dictionary<char, int> charCount =
new Dictionary<char, int>();
foreach (char c in str)
{
if (charCount.ContainsKey(c))
{
charCount[c]++;
}
else
{
charCount[c] = 1;
}
}
foreach (char c in str)
{
if (charCount[c] == 1)
{
return c;
}
}
return '\0';
}
static void Main(string[] args)
{
string input = "hello";
char result =
FindFirstNonRepeated(input);
if (result != '\0')
{
Console.WriteLine($"First
non-repeated character: {result}");
}
else
{
Console.WriteLine("No
non-repeated character found.");
}
}
}
8.5 String manipulation (concatenation, substring):
using System;
class StringManipulation
{
static void Main(string[] args)
{
string firstName = "John";
string lastName = "Doe";
string fullName = firstName + "
" + lastName;
Console.WriteLine($"Full name:
{fullName}");
string sentence = "The quick brown
fox jumps over the lazy dog";
string sub = sentence.Substring(4, 15);
// Extract "quick brown fox"
Console.WriteLine($"Substring:
{sub}");
}
}
8.6 Anagram detection:
using System;
class AnagramCheck
{
static bool AreAnagrams(string str1, string
str2)
{
if (str1.Length != str2.Length)
{
return false;
}
int[] charCount = new int[256];
foreach (char c in str1)
{
charCount[c]++;
}
foreach (char c in str2)
{
charCount[c]--;
}
foreach (int count in charCount)
{
if (count != 0)
{
return false;
}
}
return true;
}
static void Main(string[] args)
{
string word1 = "listen";
string word2 = "silent";
if (AreAnagrams(word1, word2))
{
Console.WriteLine($"{word1}
and {word2} are anagrams.");
}
else
{
Console.WriteLine($"{word1}
and {word2} are not anagrams.");
}
}
}
9. Functions and Methods:
9.1 Creating and calling a function:
using System;
class FunctionsExample
{
static void Greet()
{
Console.WriteLine("Hello,
there!");
}
static void Main(string[] args)
{
Greet();
}
}
9.2 Function with parameters and return value:
using System;
class FunctionWithParameters
{
static int Add(int num1, int num2)
{
return num1 + num2;
}
static void Main(string[] args)
{
int result = Add(5, 10);
Console.WriteLine($"Result:
{result}");
}
}
9.3 Recursive functions (factorial, Fibonacci):
using System;
class RecursiveFunctions
{
static int Factorial(int n)
{
if (n == 0 || n == 1)
{
return 1;
}
return n * Factorial(n - 1);
}
static int Fibonacci(int n)
{
if (n <= 1)
{
return n;
}
return Fibonacci(n - 1) + Fibonacci(n -
2);
}
static void Main(string[] args)
{
int num = 5;
Console.WriteLine($"Factorial of
{num}: {Factorial(num)}");
Console.WriteLine($"Fibonacci of
{num}: {Fibonacci(num)}");
}
}
9.4 Method overloading:
using System;
class MethodOverloading
{
static int Add(int num1, int num2)
{
return num1 + num2;
}
static double Add(double num1, double num2)
{
return num1 + num2;
}
static string Add(string str1, string str2)
{
return str1 + str2;
}
static void Main(string[] args)
{
Console.WriteLine($"Int addition:
{Add(5, 10)}");
Console.WriteLine($"Double
addition: {Add(3.14, 2.71)}");
Console.WriteLine($"String
concatenation: {Add("Hello, ", "World!")}");
}
}
9.5 Method overriding:
using System;
class MethodOverriding
{
class Shape
{
public virtual void Draw()
{
Console.WriteLine("Drawing a
shape.");
}
}
class Circle : Shape
{
public override void Draw()
{
Console.WriteLine("Drawing a
circle.");
}
}
static void Main(string[] args)
{
Shape shape = new Shape();
shape.Draw();
Circle circle = new Circle();
circle.Draw();
}
}
10. Object-Oriented Programming:
10.1 Class and Object:
using System;
class Car
{
public string Model { get; set; }
public int Year { get; set; }
public void StartEngine()
{
Console.WriteLine($"Starting the
engine of {Model}...");
}
}
class OOPExample
{
static void Main(string[] args)
{
Car myCar = new Car();
myCar.Model = "Toyota Camry";
myCar.Year = 2023;
Console.WriteLine($"Car:
{myCar.Model}, Year: {myCar.Year}");
myCar.StartEngine();
}
}
10.2 Inheritance:
using System;
class Shape
{
public virtual void Draw()
{
Console.WriteLine("Drawing a
shape.");
}
}
class Circle : Shape
{
public override void Draw()
{
Console.WriteLine("Drawing a
circle.");
}
}
class InheritanceExample
{
static void Main(string[] args)
{
Shape shape = new Shape();
shape.Draw();
Circle circle = new Circle();
circle.Draw();
}
}
10.3 Encapsulation:
using System;
class BankAccount
{
private double balance;
public void Deposit(double amount)
{
if (amount > 0)
{
balance += amount;
}
}
public void Withdraw(double amount)
{
if (amount > 0 && balance
>= amount)
{
balance -= amount;
}
}
public double GetBalance()
{
return balance;
}
}
class EncapsulationExample
{
static void Main(string[] args)
{
BankAccount account = new
BankAccount();
account.Deposit(1000);
account.Withdraw(500);
Console.WriteLine($"Account
balance: {account.GetBalance()}");
}
}
Object-Oriented Programming:
24. Creating a class and object
using System;
class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
class Program
{
static void Main(string[] args)
{
Person person = new Person();
person.Name = "John";
person.Age = 30;
Console.WriteLine($"Name: {person.Name},
Age: {person.Age}");
}
}
25. Constructors and destructors
using System;
class Car
{
public Car()
{
Console.WriteLine("Car constructor
called.");
}
~Car()
{
Console.WriteLine("Car destructor
called.");
}
}
class Program
{
static void Main(string[] args)
{
Car myCar = new Car();
// Other code...
}
}
26. Inheritance and base class
using System;
class Vehicle
{
public void StartEngine()
{
Console.WriteLine("Engine
started.");
}
}
class Car : Vehicle
{
public void Accelerate()
{
Console.WriteLine("Car is
accelerating.");
}
}
class Program
{
static void Main(string[] args)
{
Car myCar = new Car();
myCar.StartEngine();
myCar.Accelerate();
}
}
27. Polymorphism and method overriding
using System;
class Shape
{
public virtual void Draw()
{
Console.WriteLine("Drawing a
shape.");
}
}
class Circle : Shape
{
public override void Draw()
{
Console.WriteLine("Drawing a
circle.");
}
}
class Program
{
static void Main(string[] args)
{
Shape shape = new Circle();
shape.Draw();
}
}
28. Abstract classes and interfaces
using System;
abstract class Shape
{
public abstract void Draw();
}
interface IResizable
{
void Resize();
}
class Circle : Shape,
IResizable
{
public override void Draw()
{
Console.WriteLine("Drawing a
circle.");
}
public void Resize()
{
Console.WriteLine("Resizing the
circle.");
}
}
class Program
{
static void Main(string[] args)
{
Circle circle = new Circle();
circle.Draw();
circle.Resize();
}
}
29. Encapsulation and access modifiers
using System;
class BankAccount
{
private double balance;
public void Deposit(double amount)
{
if (amount > 0)
balance += amount;
}
public double GetBalance()
{
return balance;
}
}
class Program
{
static void Main(string[] args)
{
BankAccount account = new
BankAccount();
account.Deposit(1000);
Console.WriteLine($"Balance:
{account.GetBalance()}");
}
}
Exception Handling:
30. Handling exceptions (try-catch)
using System;
class Program
{
static void Main(string[] args)
{
try
{
int num =
int.Parse(Console.ReadLine());
int result = 10 / num;
Console.WriteLine($"Result:
{result}");
}
catch (DivideByZeroException)
{
Console.WriteLine("Cannot
divide by zero.");
}
catch (FormatException)
{
Console.WriteLine("Invalid
input format.");
}
catch (Exception ex)
{
Console.WriteLine($"An error
occurred: {ex.Message}");
}
}
}
31. Custom exceptions
using System;
class CustomException :
Exception
{
public CustomException(string message) :
base(message)
{
}
}
class Program
{
static void Main(string[] args)
{
try
{
throw new
CustomException("Custom exception occurred.");
}
catch (CustomException ex)
{
Console.WriteLine($"Custom
exception caught: {ex.Message}");
}
}
}
32. Finally block usage
using System;
class Program
{
static void Main(string[] args)
{
try
{
Console.WriteLine("Try
block.");
}
catch (Exception)
{
Console.WriteLine("Catch
block.");
}
finally
{
Console.WriteLine("Finally
block.");
}
}
}
33. Exception propagation
using System;
class Program
{
static void Method1()
{
throw new Exception("Exception
from Method1.");
}
static void Method2()
{
Method1();
}
static void Main(string[] args)
{
try
{
Method2();
}
catch (Exception ex)
{
Console.WriteLine($"Exception
caught: {ex.Message}");
}
}
}
File Handling:
34. Reading from a file
using System;
using System.IO;
class Program
{
static void Main(string[] args)
{
string filePath =
"sample.txt";
if (File.Exists(filePath))
{
string content =
File.ReadAllText(filePath);
Console.WriteLine(content);
}
else
{
Console.WriteLine("File not
found.");
}
}
}
35. Writing to a file
using System;
using System.IO;
class Program
{
static void Main(string[] args)
{
string filePath =
"output.txt";
string content = "Hello, this is
written to a file.";
File.WriteAllText(filePath, content);
Console.WriteLine("Content written
to the file.");
}
}
36. File manipulation (rename, delete)
using System;
using System.IO;
class Program
{
static void Main(string[] args)
{
string oldFilePath =
"oldfile.txt";
string newFilePath =
"newfile.txt";
if (File.Exists(oldFilePath))
{
File.Move(oldFilePath,
newFilePath);
Console.WriteLine("File
renamed.");
}
if (File.Exists(newFilePath))
{
File.Delete(newFilePath);
Console.WriteLine("File
deleted.");
}
}
}
37. Working with directories
using System;
using System.IO;
class Program
{
static void Main(string[] args)
{
string directoryPath =
"MyDirectory";
if (!Directory.Exists(directoryPath))
{
Directory.CreateDirectory(directoryPath);
Console.WriteLine("Directory
created.");
}
string[] files = Directory.GetFiles(directoryPath);
Console.WriteLine($"Files in the
directory: {string.Join(", ", files)}");
Directory.Delete(directoryPath);
Console.WriteLine("Directory
deleted.");
}
}
Collections and Generics:
38. Working with dictionaries
using System;
using
System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
Dictionary<string, int> ages =
new Dictionary<string, int>();
ages["John"] = 30;
ages
["Jane"] = 25;
foreach (var kvp in ages)
{
Console.WriteLine($"{kvp.Key}:
{kvp.Value} years old");
}
}
}
39. Working with hashsets
using System;
using
System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
HashSet<string> names = new HashSet<string>();
names.Add("John");
names.Add("Jane");
names.Add("John"); //
Duplicate entry, ignored by HashSet
foreach (var name in names)
{
Console.WriteLine(name);
}
}
}
40. Using generic classes
using System;
class MyGenericClass<T>
{
public T Value { get; set; }
}
class Program
{
static void Main(string[] args)
{
MyGenericClass<int> intContainer
= new MyGenericClass<int>();
intContainer.Value = 42;
MyGenericClass<string>
stringContainer = new MyGenericClass<string>();
stringContainer.Value = "Hello,
generics!";
Console.WriteLine(intContainer.Value);
Console.WriteLine(stringContainer.Value);
}
}
41. Using generic methods
using System;
class Program
{
static void Swap<T>(ref T a, ref T b)
{
T temp = a;
a = b;
b = temp;
}
static void Main(string[] args)
{
int num1 = 10, num2 = 20;
Console.WriteLine($"Before swap: num1 =
{num1}, num2 = {num2}");
Swap(ref num1, ref num2);
Console.WriteLine($"After swap:
num1 = {num1}, num2 = {num2}");
}
}
42. Creating custom generic classes
using System;
class MyGenericClass<T1,
T2>
{
public T1 Item1 { get; set; }
public T2 Item2 { get; set; }
}
class Program
{
static void Main(string[] args)
{
MyGenericClass<int, string>
myPair = new MyGenericClass<int, string>();
myPair.Item1 = 42;
myPair.Item2 = "Hello, generics
pair!";
Console.WriteLine($"Item1:
{myPair.Item1}, Item2: {myPair.Item2}");
}
}
LINQ (Language Integrated Query):
43. Filtering and sorting data
using System;
using System.Linq;
using
System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
List<int> numbers = new
List<int> { 5, 2, 8, 1, 7, 3 };
var filteredAndSorted = numbers.Where(n
=> n > 3).OrderBy(n => n);
foreach (var num in filteredAndSorted)
{
Console.WriteLine(num);
}
}
}
44. Projection and transformation
using System;
using System.Linq;
using
System.Collections.Generic;
class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
class Program
{
static void Main(string[] args)
{
List<Person> people = new
List<Person>
{
new Person { Name =
"John", Age = 30 },
new Person { Name =
"Jane", Age = 25 }
};
var names = people.Select(p =>
p.Name);
foreach (var name in names)
{
Console.WriteLine(name);
}
}
}
45. Joining multiple data sources
using System;
using System.Linq;
using
System.Collections.Generic;
class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
class Address
{
public string City { get; set; }
public string Country { get; set; }
}
class Program
{
static void Main(string[] args)
{
List<Person> people = new
List<Person>
{
new Person { Name =
"John", Age = 30 },
new Person { Name =
"Jane", Age = 25 }
};
List<Address> addresses = new
List<Address>
{
new Address { City = "New
York", Country = "USA" },
new Address { City =
"London", Country = "UK" }
};
var joinedData = people.Join(
addresses,
person => person.Name,
address => address.City,
(person, address) => new {
person.Name, person.Age, address.Country });
foreach (var item in joinedData)
{
Console.WriteLine($"{item.Name}, {item.Age}, {item.Country}");
}
}
}
46. Grouping and aggregation
using System;
using System.Linq;
using
System.Collections.Generic;
class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
class Program
{
static void Main(string[] args)
{
List<Person> people = new
List<Person>
{
new Person { Name =
"John", Age = 30 },
new Person { Name =
"Jane", Age = 25 },
new Person { Name =
"Alice", Age = 30 }
};
var groupedData = people.GroupBy(p
=> p.Age);
foreach (var group in groupedData)
{
Console.WriteLine($"Age:
{group.Key}");
foreach (var person in group)
{
Console.WriteLine($"-
{person.Name}");
}
}
}
}
Multithreading:
47. Creating and starting a thread:
using System;
using System.Threading;
class Program
{
static void Main(string[] args)
{
Thread thread = new Thread(new
ThreadStart(DoWork));
thread.Start();
}
static void DoWork()
{
Console.WriteLine("Thread is
working.");
}
}
48. Synchronization using locks:
using System;
using System.Threading;
class Program
{
static int counter = 0;
static object lockObject = new object();
static void Main(string[] args)
{
Thread thread1 = new
Thread(IncrementCounter);
Thread thread2 = new
Thread(IncrementCounter);
thread1.Start();
thread2.Start();
thread1.Join();
thread2.Join();
Console.WriteLine("Final counter
value: " + counter);
}
static void IncrementCounter()
{
for (int i = 0; i < 10000; i++)
{
lock (lockObject)
{
counter++;
}
}
}
}
49. Thread safety and race conditions:
// Similar to the code
provided in the previous section (Synchronization using locks)
// This example shows how
locks can help prevent race conditions
50. Background vs Foreground threads:
using System;
using System.Threading;
class Program
{
static void Main(string[] args)
{
Thread foregroundThread = new
Thread(new ThreadStart(DoWork));
Thread backgroundThread = new
Thread(new ThreadStart(DoWork));
foregroundThread.IsBackground = false;
// Foreground thread
backgroundThread.IsBackground =
true; // Background thread
foregroundThread.Start();
backgroundThread.Start();
Console.WriteLine("Main thread
exiting.");
}
static void DoWork()
{
Thread.Sleep(1000); // Simulate some
work
Console.WriteLine("Thread
completed.");
}
}
51. Using Task and async/await:
using System;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
await DoWorkAsync();
}
static async Task DoWorkAsync()
{
Console.WriteLine("Starting
asynchronous work.");
await Task.Delay(1000); // Simulate
asynchronous work
Console.WriteLine("Asynchronous
work completed.");
}
}
Delegates and Events:
52. Creating and invoking delegates:
using System;
class Program
{
delegate void MyDelegate(string message);
static void Main(string[] args)
{
MyDelegate myDelegate = new
MyDelegate(PrintMessage);
myDelegate("Hello,
delegates!");
}
static void PrintMessage(string message)
{
Console.WriteLine(message);
}
}
53. Multicast delegates:
using System;
class Program
{
delegate void MyDelegate(string message);
static void Main(string[] args)
{
MyDelegate myDelegate = PrintMessage1;
myDelegate += PrintMessage2;
myDelegate("Multicast
delegates");
}
static void PrintMessage1(string message)
{
Console.WriteLine("Message from
delegate 1: " + message);
}
static void PrintMessage2(string message)
{
Console.WriteLine("Message from
delegate 2: " + message);
}
}
54. Creating and raising events:
using System;
class Program
{
class EventPublisher
{
public event
EventHandler<MyEventArgs> MyEvent;
public void RaiseEvent(string message)
{
MyEvent?.Invoke(this, new
MyEventArgs(message));
}
}
class MyEventArgs : EventArgs
{
public string Message { get; }
public MyEventArgs(string message)
{
Message = message;
}
}
static void Main(string[] args)
{
EventPublisher publisher = new
EventPublisher();
publisher.MyEvent += EventSubscriber;
publisher.RaiseEvent("Event
raised!");
}
static void EventSubscriber(object sender,
MyEventArgs e)
{
Console.WriteLine("Event received:
" + e.Message);
}
}
55. Event subscribers and publishers:
// Similar to the code
provided in the previous section (Creating and raising events)
// This example demonstrates
how event subscribers can listen to events raised by publishers
Serialization:
56. Serialization and deserialization of objects:
using System;
using System.IO;
using
System.Runtime.Serialization;
using
System.Runtime.Serialization.Formatters.Binary;
class Program
{
[Serializable]
class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
static void Main(string[] args)
{
Person person = new Person { Name =
"John", Age = 30 };
// Serialization
IFormatter formatter = new
BinaryFormatter();
using (Stream stream = new
FileStream("person.bin", FileMode.Create, FileAccess.Write))
{
formatter.Serialize(stream,
person);
}
// Deserialization
using (Stream stream = new
FileStream("person.bin", FileMode.Open, FileAccess.Read))
{
Person deserializedPerson =
(Person)formatter.Deserialize(stream);
Console.WriteLine("Name:
" + deserializedPerson.Name);
Console.WriteLine("Age: "
+ deserializedPerson.Age);
}
}
}
57. Working with XML serialization:
using System;
using System.IO;
using
System.Xml.Serialization;
class Program
{
[Serializable]
[XmlRoot("Person")]
public class Person
{
[XmlElement("Name")]
public string Name { get; set; }
[XmlElement("Age")]
public int Age { get; set; }
}
static void Main(string[] args)
{
Person person = new Person { Name =
"Alice", Age = 25 };
// Serialization
XmlSerializer serializer = new
XmlSerializer(typeof(Person));
using (StreamWriter writer = new
StreamWriter("person.xml"))
{
serializer.Serialize(writer,
person);
}
// Deserialization
using (StreamReader reader = new
StreamReader("person.xml"))
{
Person deserializedPerson =
(Person)serializer.Deserialize(reader);
Console.WriteLine("Name:
" + deserializedPerson.Name);
Console.WriteLine("Age: "
+ deserializedPerson.Age);
}
}
}
58. JSON serialization and deserialization:
using System;
using System.IO;
using System.Text.Json;
class Program
{
class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
static void Main(string[] args)
{
Person person = new Person { Name =
"Bob", Age = 28 };
// Serialization
string json =
JsonSerializer.Serialize(person);
File.WriteAllText("person.json", json);
// Deserialization
string jsonContent =
File.ReadAllText("person.json");
Person deserializedPerson =
JsonSerializer.Deserialize
<Person>(jsonContent);
Console.WriteLine("Name: " +
deserializedPerson.Name);
Console.WriteLine("Age: " +
deserializedPerson.Age);
}
}
Reflection:
59. Getting type information using reflection:
using System;
using System.Reflection;
class Program
{
class MyClass
{
public int MyProperty { get; set; }
public void MyMethod() { }
}
static void Main(string[] args)
{
Type type = typeof(MyClass);
Console.WriteLine("Type name:
" + type.Name);
Console.WriteLine("Properties:");
foreach (var property in
type.GetProperties())
{
Console.WriteLine("- " +
property.Name);
}
Console.WriteLine("Methods:");
foreach (var method in
type.GetMethods())
{
Console.WriteLine("- " +
method.Name);
}
}
}
60. Creating an instance using reflection:
using System;
using System.Reflection;
class Program
{
class MyClass
{
public void MyMethod()
{
Console.WriteLine("MyMethod
called.");
}
}
static void Main(string[] args)
{
Type type = typeof(MyClass);
object instance =
Activator.CreateInstance(type);
MethodInfo method =
type.GetMethod("MyMethod");
method.Invoke(instance, null);
}
}
61. Invoking methods using reflection:
using System;
using System.Reflection;
class Program
{
class Calculator
{
public int Add(int a, int b) { return a
+ b; }
}
static void Main(string[] args)
{
Calculator calculator = new
Calculator();
Type type = typeof(Calculator);
MethodInfo method =
type.GetMethod("Add");
object result =
method.Invoke(calculator, new object[] { 5, 3 });
Console.WriteLine("Result: "
+ result);
}
}
Unit Testing:
62. Writing unit tests using MSTest or NUnit:
// This example assumes
NUnit. You can replace NUnit attributes with MSTest attributes if you prefer.
using NUnit.Framework;
class Calculator
{
public int Add(int a, int b) { return a +
b; }
}
[TestFixture]
class CalculatorTests
{
[Test]
public void TestAdd()
{
Calculator calculator = new
Calculator();
int result = calculator.Add(2, 3);
Assert.AreEqual(5, result);
}
}
63. Test fixtures and setup/teardown methods:
using NUnit.Framework;
[TestFixture]
class CalculatorTests
{
private Calculator calculator;
[SetUp]
public void SetUp()
{
calculator = new Calculator();
}
[TearDown]
public void TearDown()
{
// Clean up resources if needed
}
[Test]
public void TestAdd()
{
int result = calculator.Add(2, 3);
Assert.AreEqual(5, result);
}
}
64. Assert statements and test attributes:
using NUnit.Framework;
[TestFixture]
class CalculatorTests
{
private Calculator calculator;
[SetUp]
public void SetUp()
{
calculator = new Calculator();
}
[TearDown]
public void TearDown()
{
// Clean up resources if needed
}
[Test]
public void TestAdd()
{
int result = calculator.Add(2, 3);
Assert.AreEqual(5, result);
}
[Test]
public void TestSubtract()
{
int result = calculator.Subtract(5, 3);
// Assuming the Calculator class has a Subtract method
Assert.AreEqual(2, result);
}
}
Singleton Pattern (Index 65):
public class Singleton
{
private static Singleton instance;
private Singleton() { }
public static Singleton Instance
{
get
{
if (instance == null)
{
instance = new Singleton();
}
return instance;
}
}
}
Factory Pattern (Index 66):
public interface IProduct
{
void Create();
}
public class ConcreteProductA
: IProduct
{
public void Create()
{
Console.WriteLine("Creating
Product A");
}
}
public class ConcreteProductB
: IProduct
{
public void Create()
{
Console.WriteLine("Creating
Product B");
}
}
public class ProductFactory
{
public IProduct CreateProduct(string type)
{
switch (type)
{
case "A":
return new ConcreteProductA();
case "B":
return new ConcreteProductB();
default:
throw new
ArgumentException("Invalid product type");
}
}
}
Observer Pattern (Index 67):
using System;
using
System.Collections.Generic;
public interface IObserver
{
void Update(string message);
}
public class ConcreteObserver
: IObserver
{
private string name;
public ConcreteObserver(string name)
{
this.name = name;
}
public void Update(string message)
{
Console.WriteLine($"{name}
received message: {message}");
}
}
public class Subject
{
private List<IObserver> observers =
new List<IObserver>();
private string message;
public void Attach(IObserver observer)
{
observers.Add(observer);
}
public void Detach(IObserver observer)
{
observers.Remove(observer);
}
public void Notify()
{
foreach (var observer in observers)
{
observer.Update(message);
}
}
public string Message
{
get { return message; }
set
{
message = value;
Notify();
}
}
}
Decorator Pattern (Index 68):
public interface IComponent
{
void Operation();
}
public class
ConcreteComponent : IComponent
{
public void Operation()
{
Console.WriteLine("ConcreteComponent Operation");
}
}
public abstract class
Decorator : IComponent
{
protected IComponent component;
public Decorator(IComponent component)
{
this.component = component;
}
public virtual void Operation()
{
component.Operation();
}
}
public class
ConcreteDecoratorA : Decorator
{
public ConcreteDecoratorA(IComponent
component) : base(component) { }
public override void Operation()
{
base.Operation();
Console.WriteLine("Added behavior
from ConcreteDecoratorA");
}
}
public class
ConcreteDecoratorB : Decorator
{
public ConcreteDecoratorB(IComponent
component) : base(component) { }
public override void Operation()
{
base.Operation();
Console.WriteLine("Added behavior
from ConcreteDecoratorB");
}
}
Strategy Pattern (Index 69):
public interface IStrategy
{
void Execute();
}
public class
ConcreteStrategyA : IStrategy
{
public void Execute()
{
Console.WriteLine("Executing
strategy A");
}
}
public class
ConcreteStrategyB : IStrategy
{
public void Execute()
{
Console.WriteLine("Executing
strategy B");
}
}
public class Context
{
private IStrategy strategy;
public Context(IStrategy strategy)
{
this.strategy = strategy;
}
public void ExecuteStrategy()
{
strategy.Execute();
}
}
Connecting to a Database (Index 70):
using System.Data.SqlClient;
class DatabaseConnector
{
private SqlConnection connection;
public DatabaseConnector(string
connectionString)
{
connection = new
SqlConnection(connectionString);
}
public void OpenConnection()
{
if (connection.State !=
System.Data.ConnectionState.Open)
connection.Open();
}
public void CloseConnection()
{
if (connection.State !=
System.Data.ConnectionState.Closed)
connection.Close();
}
}
Executing SQL Queries (Index 71):
using System.Data.SqlClient;
class QueryExecutor
{
private SqlConnection connection;
public QueryExecutor(SqlConnection
connection)
{
this.connection = connection;
}
public void ExecuteNonQuery(string query)
{
using (SqlCommand command = new
SqlCommand(query, connection))
{
command.ExecuteNonQuery();
}
}
// Add methods for other query types
(SELECT, INSERT, etc.) similarly
}
Retrieving and Displaying Data (Index 72):
using System;
using System.Data.SqlClient;
class DataRetriever
{
private SqlConnection connection;
public DataRetriever(SqlConnection
connection)
{
this.connection = connection;
}
public void RetrieveAndDisplayData(string
query)
{
using (SqlCommand command = new
SqlCommand(query, connection))
{
using (SqlDataReader reader =
command.ExecuteReader())
{
while (reader.Read())
{
Console.WriteLine(reader.GetString(0));
// Assuming the first column is of string type
}
}
}
}
}
Using Parameterized Queries (Index 73):
using System.Data.SqlClient;
class
ParameterizedQueryExecutor
{
private SqlConnection connection;
public
ParameterizedQueryExecutor(SqlConnection connection)
{
this.connection = connection;
}
public void
ExecuteParameterizedQuery(string query, SqlParameter[] parameters)
{
using (SqlCommand command = new
SqlCommand(query, connection))
{
command.Parameters.AddRange(parameters);
command.ExecuteNonQuery();
}
}
}
Entity Framework:
74. Creating a model from a database:
First,
you need to install Entity Framework package using NuGet:
Install-Package
EntityFramework
Now,
here’s an example of creating a model from an existing database using Entity
Framework:
using System;
using System.Data.Entity;
namespace EFExample
{
public class Employee
{
public int EmployeeId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
// Other properties...
}
public class EmployeeContext : DbContext
{
public DbSet<Employee> Employees {
get; set; }
}
class Program
{
static void Main(string[] args)
{
using (var context = new
EmployeeContext())
{
foreach (var employee in
context.Employees)
{
Console.WriteLine($"Employee ID: {employee.EmployeeId}, Name:
{employee.FirstName} {employee.LastName}");
}
}
}
}
}
75. CRUD operations using Entity Framework:
// Assuming you have the
Employee and EmployeeContext classes from the previous example
using System;
using System.Linq;
namespace EFExample
{
class Program
{
static void Main(string[] args)
{
using (var context = new EmployeeContext())
{
// Create
var newEmployee = new Employee
{ FirstName = "John", LastName = "Doe" };
context.Employees.Add(newEmployee);
context.SaveChanges();
// Read
var employee =
context.Employees.FirstOrDefault(e => e.FirstName == "John");
if (employee != null)
{
Console.WriteLine($"Employee ID: {employee.EmployeeId}, Name:
{employee.FirstName} {employee.LastName}");
}
// Update
if (employee != null)
{
employee.LastName =
"Smith";
context.SaveChanges();
}
// Delete
if (employee != null)
{
context.Employees.Remove(employee);
context.SaveChanges();
}
}
}
}
}
76. Working with navigation properties:
Assuming
you have two entities: Department and Employee, where Department has a collection navigation property of employees.
// Assuming you have the
Department, Employee, and EmployeeContext classes with relationships
using System;
using System.Linq;
namespace EFExample
{
class Program
{
static void Main(string[] args)
{
using (var context = new
EmployeeContext())
{
var department =
context.Departments.Include("Employees").FirstOrDefault();
if (department != null)
{
Console.WriteLine($"Department: {department.Name}");
foreach (var employee in
department.Employees)
{
Console.WriteLine($"Employee: {employee.FirstName}
{employee.LastName}");
}
}
}
}
}
}
ASP.NET Basics:
77. Creating a basic ASP.NET web application:
To
create a basic ASP.NET web application, you can use Visual Studio. Follow these
steps:
- Open
Visual Studio.
- Click
“Create a new project.”
- Select
“ASP.NET Web Application.”
- Choose
a template (e.g., Empty, Web Forms, MVC) and configure the project
settings.
- Build
your application by adding pages, controls, and logic.
The
code for a complete ASP.NET web application is beyond the scope of a single
response.
78. Understanding the ASP.NET Page Lifecycle:
The
ASP.NET Page Lifecycle involves various stages like initialization, loading
view state, processing postbacks, rendering, etc. It’s quite extensive to
provide a complete code example here. You can refer to Microsoft’s documentation
for detailed explanations and examples: ASP.NET Page Life Cycle
79. Using WebForms controls (TextBox, Button, GridView):
Here’s
a simple example of using WebForms controls in an ASP.NET Web Forms page:
<%@ Page
Language="C#" AutoEventWireup="true"
CodeBehind="WebForm1.aspx.cs"
Inherits="WebApplication1.WebForm1" %>
<!DOCTYPE html>
<html
xmlns="http://www.w3.org/1999/xhtml">
<head
runat="server">
<title>WebForm with
Controls</title>
</head>
<body>
<form runat="server">
<div>
<asp:TextBox
ID="txtName" runat="server"></asp:TextBox>
<asp:Button
ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Click"
/>
<br />
<asp:GridView
ID="gridEmployees" runat="server"></asp:GridView>
</div>
</form>
</body>
</html>
using System;
using
System.Web.UI.WebControls;
namespace WebApplication1
{
public partial class WebForm1 :
System.Web.UI.Page
{
protected void Page_Load(object sender,
EventArgs e)
{
if (!IsPostBack)
{
// Initialize grid data here
}
}
protected void btnSubmit_Click(object
sender, EventArgs e)
{
string name = txtName.Text;
// Perform some action with the
entered name
}
}
}
Sure,
here are the code examples for each of the programs you mentioned:
ASP.NET MVC:
- Creating
an MVC application:
// Inside Global.asax.cs
using System.Web.Mvc;
using
System.Web.Optimization;
using System.Web.Routing;
namespace YourMVCApplication
{
public class MvcApplication :
System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
}
}
- Creating
controllers and actions:
// Inside
Controllers/HomeController.cs
using System.Web.Mvc;
namespace
YourMVCApplication.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult About()
{
ViewBag.Message = "Your
application description page.";
return View();
}
}
}
- Working
with views and Razor syntax:
<!-- Inside
Views/Home/Index.cshtml -->
@{
ViewBag.Title = "Home Page";
}
<h2>@ViewBag.Message</h2>
<p>Welcome to the
ASP.NET MVC application!</p>
- Model
binding and validation:
// Inside Models/User.cs
using
System.ComponentModel.DataAnnotations;
namespace
YourMVCApplication.Models
{
public class User
{
public int Id { get; set; }
[Required]
public string Username { get; set; }
[Required]
[EmailAddress]
public string Email { get; set; }
}
}
// Inside
Controllers/UserController.cs
using System.Web.Mvc;
using
YourMVCApplication.Models;
namespace
YourMVCApplication.Controllers
{
public class UserController : Controller
{
public ActionResult Register()
{
return View();
}
[HttpPost]
public ActionResult Register(User user)
{
if (ModelState.IsValid)
{
// Save user to database
return
RedirectToAction("Index", "Home");
}
return View(user);
}
}
}
Web API:
- Creating
a simple Web API:
// Inside
Controllers/ApiController.cs
using System.Web.Http;
namespace
YourWebAPIApplication.Controllers
{
public class ApiController : ApiController
{
public IHttpActionResult Get()
{
return Ok("Hello from Web
API!");
}
}
}
- Handling
HTTP verbs (GET, POST, PUT, DELETE):
// Inside
Controllers/ItemsController.cs
using
System.Collections.Generic;
using System.Web.Http;
namespace
YourWebAPIApplication.Controllers
{
public class ItemsController :
ApiController
{
private static List<string> items
= new List<string>();
public IEnumerable<string> Get()
{
return items;
}
public IHttpActionResult Post(string
item)
{
items.Add(item);
return Ok();
}
public IHttpActionResult Put(int id,
string newItem)
{
if (id >= 0 && id <
items.Count)
{
items[id] = newItem;
return Ok();
}
return NotFound();
}
public IHttpActionResult Delete(int id)
{
if (id >= 0 && id <
items.Count)
{
items.RemoveAt(id);
return Ok();
}
return NotFound();
}
}
}
- Returning
JSON data from Web API:
// Inside
Controllers/DataController.cs
using System.Web.Http;
namespace
YourWebAPIApplication.Controllers
{
public class DataController : ApiController
{
public IHttpActionResult Get()
{
var data = new
{
Name = "John",
Age = 30,
Location = "City"
};
return Ok(data);
}
}
}
Dependency Injection:
87. Understanding dependency injection:
using System;
public interface
IEmailService
{
void SendEmail(string recipient, string
message);
}
public class EmailService :
IEmailService
{
public void SendEmail(string recipient,
string message)
{
Console.WriteLine($"Sending email
to {recipient}: {message}");
}
}
public class
NotificationService
{
private readonly IEmailService
_emailService;
public NotificationService(IEmailService
emailService)
{
_emailService = emailService;
}
public void NotifyUser(string recipient,
string notificationMessage)
{
_emailService.SendEmail(recipient,
notificationMessage);
}
}
class Program
{
static void Main()
{
IEmailService emailService = new
EmailService();
NotificationService notificationService
= new NotificationService(emailService);
notificationService.NotifyUser("user@example.com",
"Your account has been updated.");
}
}
88. Using DI containers (e.g., Unity, Autofac): For this example, I’ll provide code for
using Unity as the DI container.
Install
the Unity NuGet package:
Install-Package Unity
using System;
using Unity;
public interface
IEmailService
{
void SendEmail(string recipient, string
message);
}
public class EmailService :
IEmailService
{
public void SendEmail(string recipient,
string message)
{
Console.WriteLine($"Sending email to
{recipient}: {message}");
}
}
public class
NotificationService
{
private readonly IEmailService
_emailService;
public NotificationService(IEmailService
emailService)
{
_emailService = emailService;
}
public void NotifyUser(string recipient,
string notificationMessage)
{
_emailService.SendEmail(recipient,
notificationMessage);
}
}
class Program
{
static void Main()
{
IUnityContainer container = new
UnityContainer();
container.RegisterType<IEmailService, EmailService>();
container.RegisterType<NotificationService>();
NotificationService notificationService
= container.Resolve<NotificationService>();
notificationService.NotifyUser("user@example.com",
"Your account has been updated.");
}
}
89. Injecting dependencies into controllers: In the context of ASP.NET MVC, here’s an
example of injecting dependencies into controllers.
using System;
using
Microsoft.AspNetCore.Mvc;
public interface
IEmailService
{
void SendEmail(string recipient, string
message);
}
public class EmailService :
IEmailService
{
public void SendEmail(string recipient,
string message)
{
Console.WriteLine($"Sending email
to {recipient}: {message}");
}
}
public class HomeController :
Controller
{
private readonly IEmailService
_emailService;
public HomeController(IEmailService
emailService)
{
_emailService = emailService;
}
public IActionResult Index()
{
_emailService.SendEmail("admin@example.com", "Welcome to
our website!");
return View();
}
}
// In Startup.cs:
public void
ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddSingleton<IEmailService,
EmailService>();
}
Authentication and Authorization:
90. Implementing user registration and login: For user registration and login, you would
generally need to use a database and ASP.NET Identity. Here’s a simplified example:
using
Microsoft.AspNetCore.Identity;
using
Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;
public class
AccountController : Controller
{
private readonly
UserManager<IdentityUser> _userManager;
private readonly SignInManager<IdentityUser>
_signInManager;
public
AccountController(UserManager<IdentityUser> userManager,
SignInManager<IdentityUser> signInManager)
{
_userManager = userManager;
_signInManager = signInManager;
}
[HttpGet]
public IActionResult Register()
{
return View();
}
[HttpPost]
public async Task<IActionResult>
Register(RegisterViewModel model)
{
if (ModelState.IsValid)
{
var user = new IdentityUser {
UserName = model.Email, Email = model.Email };
var result = await
_userManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
await
_signInManager.SignInAsync(user, isPersistent: false);
return
RedirectToAction("Index", "Home");
}
foreach (var error in
result.Errors)
{
ModelState.AddModelError("", error.Description);
}
}
return View(model);
}
[HttpGet]
public IActionResult Login()
{
return View();
}
[HttpPost]
public async Task<IActionResult>
Login(LoginViewModel model)
{
if (ModelState.IsValid)
{
var result = await
_signInManager.PasswordSignInAsync(model.Email, model.Password,
model.RememberMe, lockoutOnFailure: false);
if (result.Succeeded)
{
return
RedirectToAction("Index", "Home");
}
ModelState.AddModelError("",
"Invalid login attempt");
}
return View(model);
}
}
// ViewModels:
public class
RegisterViewModel
{
[Required]
[EmailAddress]
public string Email { get; set; }
[Required]
[DataType(DataType.Password)]
public string Password { get; set; }
[DataType(DataType.Password)]
[Compare("Password", ErrorMessage
= "Password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
}
public class LoginViewModel
{
[Required]
[EmailAddress]
public string Email { get; set; }
[Required]
[DataType(DataType.Password)]
public string Password { get; set; }
[Display(Name = "Remember me")]
public bool RememberMe { get; set; }
}
// In Startup.cs:
public void
ConfigureServices(IServiceCollection services)
{
services.AddIdentity<IdentityUser,
IdentityRole>()
.AddDefaultTokenProviders()
.AddEntityFrameworkStores<ApplicationDbContext>();
// Other services configuration
}
91. Using ASP.NET Identity for authentication: Please note that using ASP.NET Identity
involves database setup, entity models, and other considerations. This example
shows the registration and login process using ASP.NET Identity.
92. Applying role-based authorization: Here’s an example of applying role-based
authorization using ASP.NET Core’s policy-based authorization.
using
Microsoft.AspNetCore.Authorization;
using
Microsoft.AspNetCore.Mvc;
[Authorize(Roles =
"Admin")]
public class AdminController
: Controller
{
public IActionResult Index()
{
return View();
}
}
[Authorize(Roles =
"User")]
public class UserController :
Controller
{
public IActionResult Index()
{
return View();
}
}
// In Startup.cs:
public void
ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddAuthorization(options =>
{
options.AddPolicy("Admin",
policy => policy.RequireRole("Admin"));
options.AddPolicy("User",
policy => policy.RequireRole("User"));
});
}
Sure,
I can provide you with the code examples for each of the programs you’ve
mentioned. Please note that the following code snippets are simplified examples
and may need further adaptation to work within a larger application.
93. Using In-Memory Caching:
using System;
using System.Collections.Generic;
using
Microsoft.Extensions.Caching.Memory;
class Program
{
static void Main()
{
var cache = new MemoryCache(new
MemoryCacheOptions());
string key = "myKey";
string value = "myValue";
// Store data in cache
cache.Set(key, value);
// Retrieve data from cache
if (cache.TryGetValue(key, out string
cachedValue))
{
Console.WriteLine($"Value from
cache: {cachedValue}");
}
else
{
Console.WriteLine("Value not
found in cache.");
}
}
}
94. Using Distributed Caching (Redis):
Make
sure to install the StackExchange.Redis NuGet package.
using System;
using StackExchange.Redis;
class Program
{
static void Main()
{
var redisConnection =
ConnectionMultiplexer.Connect("localhost");
var cache =
redisConnection.GetDatabase();
string key = "myKey";
string value = "myValue";
// Store data in Redis cache
cache.StringSet(key, value);
// Retrieve data from Redis cache
string cachedValue =
cache.StringGet(key);
Console.WriteLine($"Value from
cache: {cachedValue}");
}
}
95. Output Caching in ASP.NET:
In
an ASP.NET application, you can use the OutputCache attribute to enable output caching for a
specific action or page.
using System;
using System.Web.Mvc;
namespace
OutputCachingExample.Controllers
{
public class HomeController : Controller
{
[OutputCache(Duration = 60)] // Cache
for 60 seconds
public ActionResult Index()
{
return View();
}
}
}
96. Basics of Microservices Architecture:
Microservices
architecture involves breaking down a complex application into smaller,
independent services that communicate with each other through APIs.
97. Communication Between Microservices:
Microservices
communicate over a network using protocols like HTTP, gRPC, or message queues
like RabbitMQ. Here’s a simplified example using HTTP:
// Microservice 1
using System;
using System.Net.Http;
using System.Threading.Tasks;
class Microservice1
{
static async Task Main()
{
using var httpClient = new
HttpClient();
string microservice2Url =
"http://localhost:5001/api/data";
HttpResponseMessage response = await
httpClient.GetAsync(microservice2Url);
if (response.IsSuccessStatusCode)
{
string data = await response.Content.ReadAsStringAsync();
Console.WriteLine($"Microservice 2 response: {data}");
}
else
{
Console.WriteLine("Microservice 2 request failed.");
}
}
}
// Microservice 2
using Microsoft.AspNetCore.Mvc;
namespace
Microservice2.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class DataController :
ControllerBase
{
[HttpGet]
public ActionResult<string>
GetData()
{
return "Data from Microservice
2";
}
}
}
98. Service Discovery and Load Balancing:
In
microservices, service discovery is the process of locating other services and
load balancers distribute incoming requests among available instances of a service.
Here’s a simplified example using a library like Polly for load balancing:
using System;
using System.Net.Http;
using Polly;
using Polly.LoadBalancing;
class Program
{
static void Main()
{
var loadBalancer = new RoundRobin();
var policy = Policy<HttpResponseMessage>
.Handle<Exception>()
.OrResult(response =>
!response.IsSuccessStatusCode)
.Retry(loadBalancer, retryCount:
3);
using var httpClient = new
HttpClient();
string[] serviceUrls = {
"http://service1", "http://service2",
"http://service3" };
HttpResponseMessage response =
policy.Execute(() =>
{
string selectedUrl =
loadBalancer.Select(serviceUrls);
return httpClient.GetAsync(selectedUrl).Result;
});
if (response.IsSuccessStatusCode)
{
string data =
response.Content.ReadAsStringAsync().Result;
Console.WriteLine($"Response
from service: {data}");
}
else
{
Console.WriteLine("Service request
failed.");
}
}
}
99. Cross-Site Scripting (XSS) Prevention:
Preventing
XSS involves encoding user-generated content before rendering it in the HTML.
using System.Web;
namespace XSSExample
{
class Program
{
static void Main()
{
string userInput =
"<script>alert('XSS Attack');</script>";
string encodedInput =
HttpUtility.HtmlEncode(userInput);
Console.WriteLine($"Encoded
Input: {encodedInput}");
}
}
}
100. SQL Injection Prevention:
Use
parameterized queries or ORM frameworks to prevent SQL injection.
using System.Data.SqlClient;
namespace SQLInjectionExample
{
class Program
{
static void Main()
{
string userInput = "'; DROP TABLE
Users; --";
string connectionString =
"your_connection_string_here";
using (SqlConnection connection =
new SqlConnection(connectionString))
{
connection.Open();
string query = "SELECT *
FROM Users WHERE Username = @username";
using SqlCommand command = new
SqlCommand(query, connection);
command.Parameters.AddWithValue("@username", userInput);
SqlDataReader reader =
command.ExecuteReader();
while (reader.Read())
{
// Process data
}
reader.Close();
}
}
}
}
0 Comments