Posts

Showing posts from January, 2024

Inheritance | OOP

 Inheritance is one of the core concepts of object-oriented programming (OOP) that allows a class (called a subclass or derived class) to inherit the properties and behaviors (fields and methods) of another class (called a superclass or base class). This promotes code reuse and the creation of a hierarchical relationship between classes. Example in C#: class Program {     static void Main() {         // Create an instance of the Dog class         Dog dog = new Dog();         dog.Name = "Buddy" ;         // Access methods from the base class         dog.Eat();         // Access methods from the derived class         dog.Bark();     } } In this example: - `Animal` is the base class with a property `Name` and a method `Eat`. - `Dog` is the derived class that inherits from `Animal` and adds a method `Bark`. When we create ...

Encapsulation | OOP

Encapsulation is one of the fundamental principles of Object-Oriented Programming (OOP). It involves bundling data (attributes) and methods (functions) that operate on that data into a single unit called a class. The data within a class is typically kept private, and access to it is controlled through public methods, often called getters and setters. This ensures that the internal state of an object is protected and can only be modified in a controlled manner. Here's an example in C# that demonstrates encapsulation: using System; public class Person {     // Private fields (attributes)     private string name;     private int age;     // Public constructor     public Person( string name, int age)     {         this .name = name;         this .age = age;     }     // Public method to get the name (getter)     public string GetName()   ...

C# OOP's concepts

  1. What is C#?    - C# is a modern, object-oriented programming language developed by Microsoft. It is widely used for building Windows applications, web applications, and more. 2. What is Object-Oriented Programming (OOP)?    - OOP is a programming paradigm that uses objects and classes to structure code. It emphasizes concepts like encapsulation, inheritance, and polymorphism. 3. What is a class and an object in C#?    - A class is a blueprint for creating objects. An object is an instance of a class, which contains data and methods defined in the class. 4. What is encapsulation in OOP?    - Encapsulation is the concept of bundling data (attributes) and methods (functions) that operate on the data into a single unit called a class. It restricts access to the data through access modifiers. 5. Explain inheritance in C#.    - Inheritance is a mechanism in C# that allows a class to inherit properties and behaviors (methods) from ano...

Dependency Injection (DI) | design pattern

 Dependency Injection (DI) is a design pattern used in software development, primarily in object-oriented programming. It offers several benefits: 1. Decoupling: DI helps decouple the components of a system by removing the direct dependencies between them. This makes the codebase more modular and easier to maintain. 2. Testability: With DI, you can easily substitute real implementations with mock objects or stubs during unit testing. This promotes better test coverage and more robust testing. 3. Flexibility: DI allows you to change the behavior of a component by simply swapping its dependencies. This makes it easier to adapt to changing requirements. 4. Reusability: Components that use DI are often more reusable because they are not tightly bound to specific implementations. This promotes code reusability across different parts of an application. 5. Scalability: DI can simplify the process of adding new components or features to a system. You can introduce new dependencies withou...

Bootstrapping in Angular

 Bootstrapping in the context of Angular typically refers to the process of initializing or starting an Angular application. Angular applications are typically bootstrapped in one of the following ways: 1. Manual Bootstrapping: In earlier versions of Angular (AngularJS), you would manually bootstrap your Angular application by calling the `angular.bootstrap` function in your HTML file. This method is less common in modern Angular applications. 2. Automatic Bootstrapping: In Angular 2 and later versions, the bootstrap process is typically automatic. Angular looks for a main module (usually named `AppModule`) and automatically starts the application when the page loads. This is usually done in the `main.ts` file using the `platformBrowserDynamic().bootstrapModule(AppModule)` method. Here's a simplified example of what the `main.ts` file might look like in an Angular application: ```typescript import { platformBrowserDynamic } from '@angular/platform-browser-dynamic' ; impor...

Questions about ASP.NET and the .NET Framework:

  1. What is ASP.NET?    ASP.NET is a web application framework developed by Microsoft. It allows developers to build dynamic, data-driven web applications and services using various programming languages like C# or VB.NET. 2. What is the .NET Framework?    The .NET Framework is a software development platform by Microsoft. It provides a large class library and support for multiple programming languages, facilitating the development of various types of applications, including desktop, web, and mobile. 3. Key Differences between Web Forms and ASP.NET MVC:    - Web Forms: Event-driven, uses server controls, and follows a stateful model.    - ASP.NET MVC: Follows the Model-View-Controller architectural pattern, is more control-based, and allows for cleaner separation of concerns. 4. Page Life Cycle in ASP.NET:    The Page Life Cycle in ASP.NET defines the sequence of events that occur when a web page is requested, processed, and render...

Interface and abstract class

How to decide when to use Interface and abstract class The choice between using an interface and an abstract class in your code depends on the specific requirements and design goals of your application. Here are some guidelines to help you decide when to use each: 1. Interfaces:    - Multiple Inheritance: In languages that support multiple inheritance (like Java and C#), you can implement multiple interfaces in a class, allowing you to inherit behaviors from multiple sources.    - Contract-based: Use interfaces when you want to define a contract that multiple unrelated classes should adhere to. Interfaces specify what methods or properties a class must implement, but they don't provide any default implementation.    - Polymorphism: When you want to enable polymorphism, interfaces are often preferred. You can use interfaces to create collections of objects that share a common behavior, regardless of their concrete types.    - Lightweight: Interface...

Action mvc | .NET

 In ASP.NET MVC, action results are objects returned by controller action methods to represent the result of a request. Action results encapsulate the data to be sent back to the client, including the HTTP status code, content type, and the actual data or view to be rendered. Here are some common types of action results in ASP.NET MVC: 1. ViewResult:    - Represents a view to be rendered and returned as HTML to the client's browser.    - Typically used to render HTML templates (views) that display data to the user.    ```csharp    public ActionResult Index()    {        // Logic to retrieve data        return View(); // Returns a ViewResult    }    ``` 2. PartialViewResult:    - Represents a partial view, which is a reusable portion of a view, to be rendered and returned as HTML.    - Often used to render small UI components that can be inserted into oth...

Bundling | .NET

 In ASP.NET MVC, bundling is a feature that allows you to combine and minify multiple CSS and JavaScript files into a single file, which can help improve the performance of your web application by reducing the number of HTTP requests made to the server. Bundling is typically used to optimize the delivery of static resources like stylesheets and scripts. Here's how to work with bundling in ASP.NET MVC: 1. BundleConfig:    - Open the `BundleConfig.cs` file in the `App_Start` folder of your MVC project. This file is responsible for configuring bundles. 2. Defining Bundles:    - Define bundles using the `BundleCollection` object provided by the `BundleConfig` class. You specify the files to bundle and their virtual paths.    ```csharp    bundles.Add(new ScriptBundle("~/bundles/jquery").Include(                "~/Scripts/jquery-{version}.js"));    bundles.Add(new StyleBundle("~/Content/css").Includ...

Razor tags | .NET

 Razor is a view engine used in ASP.NET MVC to create dynamic web pages. It provides a compact and expressive syntax for embedding C# code within HTML markup. Here are some of the most commonly used Razor tags and constructs: 1. `@:`: Used for inline code execution without rendering a value. It's often used to execute code blocks within HTML markup.    ```razor    <p>@DateTime.Now</p>    ``` 2. `@model`: Specifies the model type for the view, allowing you to strongly type the view to a specific model class.    ```razor    @model YourNamespace.YourModel    ``` 3. `@{ }`: Used for code blocks within Razor views. You can place C# code within these code blocks.    ```razor    @{        var userName = "John";        var age = 30;    }    ``` 4. `@if { }`, `@else if { }`, `@else { }`: Conditional statements for rendering HTML based on con...

Mvc Routing | .NET

Routing ASP.NET MVC (Model-View-Controller) uses a routing mechanism to map URLs to controller actions. Routing is a fundamental part of building web applications with ASP.NET MVC, and it allows you to define how URLs should be structured and how they correspond to specific controller actions and views. Here's an overview of MVC routing and how it works: 1. Route Configuration:    - Route configuration is typically defined in the `RouteConfig.cs` file within the `App_Start` folder of your ASP.NET MVC application. This file is used to configure the routes for your application. 2. Route Definition:    - A route is defined using the `Route` class and specifies a URL pattern and how it maps to a controller and action method. The URL pattern can include placeholders for parameters that will be passed to the action method. routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", actio...

Data Sanitization

 Sanitization, in the context of software development and data security, refers to the process of cleaning and validating user input to ensure that it is safe, free from malicious code, and conforms to the expected format.  Sanitization is a crucial step in preventing security vulnerabilities such as SQL injection, cross-site scripting (XSS), and other injection attacks. Here are some common types of input sanitization techniques and when to use them: 1. SQL Injection Prevention:    - Use parameterized queries or prepared statements when interacting with a database to ensure that user input is treated as data, not executable SQL code.    - Avoid dynamically constructing SQL queries with user input.    - Escape or sanitize user input to remove or neutralize potentially harmful characters. 2. Cross-Site Scripting (XSS) Prevention:    - Escape HTML, JavaScript, and other potentially dangerous content in user-generated input before rendering...

Stored procedure in SQL that supports filtering, pagination, and sorting

  Creating a stored procedure in SQL that supports filtering, pagination, and sorting involves several steps. Assuming you have a table called `YourTable`, and you want to create a stored procedure that supports filtering on a specific column, pagination, and sorting based on another column: -- Create the stored procedure CREATE PROCEDURE GetFilteredData @FilterColumn VARCHAR(255), @FilterValue VARCHAR(255), @SortColumn VARCHAR(255), @SortDirection VARCHAR(4), @PageNumber INT, @PageSize INT AS BEGIN -- Calculate the offset for pagination DECLARE @Offset INT = (@PageNumber - 1) * @PageSize; -- Dynamic SQL to build the query based on parameters DECLARE @SqlQuery NVARCHAR(MAX); SET @SqlQuery = ' SELECT * FROM YourTable WHERE 1 = 1'; -- Always true condition to build upon -- Add filtering condition if provided IF @FilterColumn IS NOT NULL AND @FilterValue IS NOT NULL BEGIN ...

comma-separated string | SQL Server

`STRING_AGG()` If you have data in a SQL table that you want to concatenate and present as a comma-separated list, you can use the `STRING_AGG()` function in SQL. This function is available in SQL Server and some other database systems. It allows you to concatenate values from multiple rows into a single string with a specified separator, such as a comma. Here's how you can use the `STRING_AGG()` function to comma-separate data in SQL: Assuming you have a table called `MyTable` with a column named `MyColumn`, and you want to concatenate the values in `MyColumn` with commas: SELECT STRING_AGG(MyColumn, ', ') AS CommaSeparatedData FROM MyTable; In this example: - `MyColumn` is the column whose values you want to concatenate. - `', '` is the separator you want to use. You can change it to any character or string you prefer. This query will return a single string that contains the values from `MyColumn` separated by commas. `STUFF` , `COALESCE()` and `FOR XML PATH...

Most commonly used SQL functions

SQL provides a wide range of built-in functions to manipulate and perform operations on data within your database. Here are some of the most commonly used SQL functions: 1. `SELECT` Functions: - `COUNT()`: Counts the number of rows or non-null values in a column. - `SUM()`: Calculates the sum of values in a column. - `AVG()`: Computes the average of values in a column. - `MIN()`: Returns the minimum value in a column. - `MAX()`: Returns the maximum value in a column. 2. `WHERE` Functions : - `LIKE`: Searches for a specified pattern in a column. - `IN()`: Specifies multiple values for comparison. - `BETWEEN`: Filters results within a specified range. - `NULL`: Checks for NULL values. - `IS NULL` / `IS NOT NULL`: Tests for NULL values. 3. String Functions: - `CONCAT()`: Concatenates two or more strings. - `SUBSTRING()`: Extracts a portion of a string. - `LENGTH()` or `LEN()`: Returns the length of a string. - `UPPER()`: Converts a string to uppercase. - `LOWER()`: Converts a string to lo...

CTE and Temp tables

A Common Table Expression (CTE) is a temporary result set that you can reference within a SELECT, INSERT, UPDATE, or DELETE statement. CTEs are defined using the `WITH` keyword and are typically used to simplify complex queries, make queries more readable, or break down a query into smaller, manageable parts. Here's the basic syntax for defining a CTE: WITH cte_name (column1, column2, ...) AS ( -- CTE query here ) - `cte_name`: This is the name of the CTE, which you will use to reference the result set. - `(column1, column2, ...)`: Optional. This specifies the column names for the CTE, making it similar to a temporary table with named columns. - `AS`: This keyword separates the CTE name and the CTE query. - `CTE query here`: This is the SQL query that defines the CTE. It can include SELECT, FROM, WHERE, JOIN, and other clauses. Once you've defined a CTE, you can reference it in the main query, allowing you to use the CTE result set as if it were a table or a subquery...

Correlated subqueries and regular (non-correlated) subqueries

Correlated subqueries and regular (non-correlated) subqueries are two different types of SQL subqueries used for different purposes.  Here's a comparison of correlated and non-correlated subqueries: Correlated Subquery: 1. Definition:    - A correlated subquery is a subquery that depends on values from the outer query. It means that the subquery is executed once for each row processed by the outer query. 2. Usage:    - Correlated subqueries are used when you need to reference values from the outer query within the subquery. This is often necessary when you want to filter or aggregate data based on values in the current row of the outer query. 3. Performance:    - Correlated subqueries can be less efficient because they involve executing the subquery multiple times, once for each row processed by the outer query. This can lead to performance issues with large datasets. 4. Example:    - An example of a correlated subquery is finding all employ...

Median | SQL

Median The median is the middle value in a set of values when they are ordered. To calculate the median in SQL, you can use a subquery with the `ORDER BY` clause and some arithmetic based on the number of rows in the result set.  Calculating the median in SQL can be a bit complex, especially if you're working with a database that doesn't have built-in support for median calculation functions.  Here's a common approach to calculating the median: Assuming you have a table named `YourTable` with a numeric column named `Value`, you can calculate the median like this: SELECT AVG(val) AS Median FROM ( SELECT val FROM YourTable ORDER BY val LIMIT 2 - (SELECT COUNT(*) FROM YourTable) % 2 OFFSET (SELECT (COUNT(*) - 1) / 2 FROM YourTable) ) subquery; Here's a breakdown of how this query works: 1. The inner subquery retrieves the sorted values from the `YourTable` using the `ORDER BY` clause. 2. The `LIMIT` clause ensures that it selects either one o...

SQL interview Questions

SQL Basics 1. What is SQL, and what is its purpose?    - SQL (Structured Query Language) is a domain-specific language used for managing and manipulating relational databases. Its purpose is to query, insert, update, and delete data in databases. 2. Explain the differences between SQL and NoSQL databases.    - SQL databases are relational and use structured tables. NoSQL databases are non-relational and can store data in various formats, like key-value, document, column-family, or graph. SQL Queries: 3. What are the fundamental SQL CRUD operations, and how are they implemented?    - CRUD stands for Create, Read, Update, Delete. These operations are implemented in SQL as INSERT, SELECT, UPDATE, and DELETE statements. 4. Explain the SQL SELECT statement.    - The SELECT statement retrieves data from one or more database tables based on specified criteria. It is used for querying data. 5. What is a SQL JOIN, and how does it work?    - A JOI...

Iteration MS Sql | Cursor | While loop

  CURSOR In SQL Server stored procedures, you can use a `CURSOR` to iterate over the result set row by row. Here's an example of how to use a `CURSOR` in a SQL Server stored procedure to iterate through the result set: ```sql -- Create a temporary table to hold the result set CREATE TABLE #TempTable (     ID INT,     Name NVARCHAR(255) ); -- Insert sample data into the temporary table INSERT INTO #TempTable (ID, Name) VALUES (1, 'John'), (2, 'Jane'), (3, 'Bob'); -- Declare variables to hold values from the result set DECLARE @ID INT; DECLARE @Name NVARCHAR(255); -- Declare a CURSOR for the result set DECLARE myCursor CURSOR FOR SELECT ID, Name FROM #TempTable; -- Open the CURSOR OPEN myCursor; -- Fetch the first row into variables FETCH NEXT FROM myCursor INTO @ID, @Name; -- Loop through the result set WHILE @@FETCH_STATUS = 0 BEGIN     -- Do something with @ID and @Name (process each row)     PRINT 'ID: ' + CAST(@ID AS NVARCHAR(10)) + ', Nam...

Entity Framework | .NET

Entity Framework:    - Entity Framework is an Object-Relational Mapping (ORM) framework in .NET that simplifies database access by allowing you to work with database entities as if they were regular objects. Its purpose is to bridge the gap between object-oriented code and relational databases. What are Code-First, Database-First, and Model-First approaches in Entity Framework?    - Code-First: You define your data model in code first, and Entity Framework generates the database schema.    - Database-First: You have an existing database schema, and Entity Framework generates entity classes based on it.    - Model-First: You design your data model using a visual designer, and Entity Framework generates both the database schema and entity classes. What is the role of `DbContext` in Entity Framework?    - `DbContext` is a key class in Entity Framework that represents a session with the database. It's responsible for managing database connec...

LINQ (Language Integrated Query) | C#

LINQ (Language Integrated Query)  LINQ (Language Integrated Query) allows you to write expressive queries in C# for various data sources, including collections, databases, XML, and more.  LINQ is a set of features in C# that allows you to query data using a SQL-like syntax directly in your code. It simplifies querying and manipulating collections, databases, XML, and more. Example of LINQ queries using a collection of `Person` objects:

Unit of Work (UoW) pattern | design pattern | Database

Unit of Work (UoW) The Unit of Work (UoW) pattern is a design pattern used in software development to manage transactions and the interactions with a data store, typically a database. It helps ensure that all database operations within a certain scope are performed atomically (all succeed or all fail), and it abstracts the complexity of managing database connections and transactions. Here's a high-level explanation of how the Unit of Work pattern works: 1. Define a Unit of Work Interface: Create an interface for the Unit of Work that includes methods to begin, commit, and rollback transactions. This interface should be responsible for managing data transactions across multiple repositories. 2. Implement a Concrete Unit of Work: Create a concrete implementation of the Unit of Work interface. This implementation will be responsible for starting, committing, and rolling back transactions. 3. Create Repository Interfaces: Define interfaces for your data repositories (e.g., `IPersonRepo...

Repository Pattern | Database layer

Repository Pattern  The Repository Pattern is a design pattern that abstracts the data access layer from the rest of the application. It provides a way to encapsulate the logic for interacting with data storage, making the code more maintainable and testable.  Here's an example of how you can implement the CRUD operations using the Repository Pattern: 1. First, create a class for your data model (e.g., `Person.cs`): public class Person {     public int ID { get; set; }     public string FirstName { get; set; }     public string LastName { get; set; } } 2. Next, create an interface for your repository (e.g., `IPersonRepository.cs`): public interface IPersonRepository {     Person GetById(int id);     IEnumerable<Person> GetAll();     void Insert(Person person);     void Update(Person person);     void Delete(int id); } 3. Implement the repository interface (e.g., `PersonRepository.cs`): using ...