0% found this document useful (0 votes)
6 views11 pages

Net SQL Angular Interview Q a 1746080319

The document provides a comprehensive list of interview questions and answers related to .NET, SQL, and Angular. Key topics include API security, authentication and authorization, SQL injection prevention, database normalization, and Angular performance optimization. It also covers practical implementations and examples for various security measures and best practices in software development.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views11 pages

Net SQL Angular Interview Q a 1746080319

The document provides a comprehensive list of interview questions and answers related to .NET, SQL, and Angular. Key topics include API security, authentication and authorization, SQL injection prevention, database normalization, and Angular performance optimization. It also covers practical implementations and examples for various security measures and best practices in software development.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

.

Net & SQL & Angular Interview Q&A


Interview Questions

Sai Reddy 4/27/25 MS SQL


.Net & SQL & Angular Interview Q&A
1. What is API Security?
Answer: API Security refers to the measures and strategies implemented to protect an API from
threats and unauthorized access. This includes ensuring that data exchanged between the client and
server is protected, user identity is authenticated, and sensitive operations are authorized.
Example: Implementing JWT (JSON Web Tokens) for stateless authentication or using HTTPS for
encrypted communication.
2. What is Authentication and Authorization? How are they different?
Answer:
• Authentication verifies the identity of the user or system (e.g., login).
• Authorization determines whether the authenticated user has permission to access a
particular resource or perform an action.
Example:
• Authentication: A user logs in with a username and password.
• Authorization: After authentication, a system checks if the user has the right role to access a
specific API resource.
In .NET Core, authentication can be handled using middleware like JWT Bearer authentication and
authorization can be handled with roles or policies.
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
IssuerSigningKey = new
SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:SecretKey"]))
};
});

services.AddAuthorization(options =>
{
options.AddPolicy("AdminPolicy", policy => policy.RequireRole("Admin"));
});
3. What are JWTs, and how are they used in API security?
Answer: JWT (JSON Web Token) is a compact and self-contained way to represent claims between
two parties. It's commonly used for authentication and authorization in modern APIs.
• How JWT Works: The server generates a token that contains information (claims) about the
user, which is signed using a secret key. The token is sent to the client, and on subsequent
requests, the client includes this token in the Authorization header.
• Structure: JWTs consist of three parts: Header, Payload, and Signature.
Example: In .NET Core, JWT authentication can be set up as follows:
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>

Sai Reddy
saireddy-dotnetfs
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
IssuerSigningKey = new
SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:SecretKey"]))
};
});
4. What is Cross-Origin Resource Sharing (CORS), and how do you implement it in .NET Core?
Answer: CORS is a mechanism that allows web applications running at one origin to request
resources from a different origin. It helps prevent unauthorized access to resources by disallowing
cross-origin requests unless explicitly permitted.
In .NET Core, you can configure CORS using middleware:
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy("AllowSpecificOrigin", builder =>
{
builder.WithOrigins("https://example.com") // specify allowed origin
.AllowAnyHeader()
.AllowAnyMethod();
});
});
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)


{
app.UseCors("AllowSpecificOrigin");
}
5. What are API Rate Limiting and Throttling? How can you implement them in .NET Core?
Answer:
• Rate Limiting: The practice of limiting the number of requests a user can make to an API
within a specified time period (e.g., 100 requests per hour).
• Throttling: Controlling the rate at which an API is accessed, often to ensure that resources
are not exhausted.
Implementation in .NET Core: You can use third-party libraries like AspNetCoreRateLimit to
implement rate limiting:
dotnet add package AspNetCoreRateLimit
public void ConfigureServices(IServiceCollection services)
{
services.AddMemoryCache();
services.Configure<IpRateLimitOptions>(Configuration.GetSection("IpRateLimiting"));
services.AddInMemoryRateLimiting();
services.AddSingleton<IRateLimitCounterStore, MemoryCacheRateLimitCounterStore>();
services.AddSingleton<IRateLimitConfiguration, RateLimitConfiguration>();

Sai Reddy
saireddy-dotnetfs
}
6. What is SQL Injection, and how do you prevent it in .NET Core?
Answer: SQL Injection is a code injection technique where malicious SQL statements are inserted
into an input field to gain unauthorized access to a database.
Prevention:
• Use parameterized queries or ORMs like Entity Framework to prevent SQL injection.
• Avoid constructing SQL queries by concatenating user inputs.
Example:
Using Entity Framework:
var user = dbContext.Users.FirstOrDefault(u => u.Username == username && u.Password ==
password);
This prevents SQL injection because the parameters are passed separately from the SQL query.
7. What is OAuth 2.0, and how is it used in API security?
Answer: OAuth 2.0 is an authorization framework that allows third-party applications to access user
resources without exposing user credentials. It uses access tokens to authenticate and authorize API
requests.
Example: You can integrate OAuth 2.0 in .NET Core with middleware such as OpenID Connect or
OAuth 2.0:
services.AddAuthentication(options =>
{
options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
})
.AddCookie()
.AddOpenIdConnect(options =>
{
options.Authority = "https://login.microsoftonline.com/{tenantId}";
options.ClientId = "client_id";
options.ClientSecret = "client_secret";
options.ResponseType = "code";
options.Scope.Add("api.read");
options.SaveTokens = true;
});
8. What is Cross-Site Request Forgery (CSRF), and how do you prevent it?
Answer: CSRF is an attack where a malicious user sends a request from an authenticated user to
perform an action without their consent.
Prevention:
• Use anti-CSRF tokens in forms and requests.
• For APIs, ensure SameSite cookies are set to Strict or Lax.
Example: In .NET Core, CSRF protection is built into the framework:
services.AddAntiforgery(options => options.HeaderName = "X-XSRF-TOKEN");
9. What is Encryption, and how do you implement it in .NET Core APIs?
Answer: Encryption ensures that data is unreadable by unauthorized users. It’s used to protect
sensitive data in transit (via SSL/TLS) and at rest (using algorithms like AES).
Example:
To encrypt data using AES in .NET Core:
public static string EncryptString(string plainText, string key)
{

Sai Reddy
saireddy-dotnetfs
using (Aes aesAlg = Aes.Create())
{
aesAlg.Key = Encoding.UTF8.GetBytes(key);
aesAlg.IV = new byte[16]; // 16-byte initialization vector

ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);


using (MemoryStream msEncrypt = new MemoryStream())
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor,
CryptoStreamMode.Write))
using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
{
swEncrypt.Write(plainText);
return Convert.ToBase64String(msEncrypt.ToArray());
}
}
}
10. What is a Secure API Gateway, and how do you use it?
Answer: A Secure API Gateway acts as a single entry point for all API requests and can handle
security tasks like authentication, rate limiting, logging, and request routing.
In .NET Core, you can use Ocelot as an API Gateway for routing requests securely:
dotnet add package Ocelot
Configure Ocelot in the ocelot.json file:
{
"ReRoutes": [
{
"DownstreamPathTemplate": "/api/values",
"UpstreamPathTemplate": "/values",
"UpstreamHttpMethod": [ "GET" ]
}
]
}

SQL Server
1. What is SQL Injection and how do you prevent it?
Answer: SQL Injection is a type of attack where an attacker can inject malicious SQL code into a
query, potentially gaining unauthorized access or damaging the database.
Prevention:
• Parameterized Queries or Prepared Statements: This ensures that user inputs are treated as
parameters, not executable code.
• Stored Procedures: Encapsulate SQL logic to limit direct user input in queries.
• ORM (Object-Relational Mapper): Use ORMs like Entity Framework that automatically
handle SQL injection risks.
• Least Privilege Principle: Ensure that database accounts have only the minimum privileges
necessary.
Example (Using Parameterized Query):
DECLARE @Username NVARCHAR(50), @Password NVARCHAR(50);
SET @Username = 'user';
SET @Password = 'password';

Sai Reddy
saireddy-dotnetfs
SELECT * FROM Users WHERE Username = @Username AND Password = @Password;
2. What are the different ways to optimize SQL Server query performance?
Answer: Several methods can be used to improve query performance in SQL Server:
• Indexes: Create indexes on frequently queried columns (but avoid over-indexing, as it can
slow down write operations).
• Query Optimization: Rewrite queries for better performance (e.g., avoid SELECT *, use
WHERE clauses efficiently).
• Execution Plans: Analyze execution plans using SQL Server Management Studio (SSMS) to
identify bottlenecks.
• Stored Procedures: Use stored procedures for frequent operations to reduce overhead.
• Database Normalization: Ensure the database is properly normalized to avoid redundancy,
but also consider de-normalization for read-heavy operations.
• Use of Proper Data Types: Ensure columns are using the most appropriate data types to
minimize memory usage.
Example (Indexing Query):
CREATE INDEX IDX_UserName ON Users (Username);
3. What is database normalization and what are its advantages?
Answer: Normalization is the process of organizing data in a database to minimize redundancy and
dependency by dividing large tables into smaller ones and defining relationships among them.
Advantages:
• Reduces Data Redundancy: Avoids storing duplicate data.
• Improves Data Integrity: Ensures that the data is consistent.
• Saves Space: By eliminating repetitive data, it helps save storage.
Example:
• 1st Normal Form (1NF): Each column contains atomic (indivisible) values.
• 2nd Normal Form (2NF): Achieved by eliminating partial dependency.
• 3rd Normal Form (3NF): Removes transitive dependency.
4. What is the importance of indexing in SQL Server?
Answer: Indexes are critical for improving the performance of SELECT queries by allowing the
database engine to quickly locate the data without scanning the entire table.
Types of Indexes:
• Clustered Index: Defines the physical order of the rows in the table (one per table).
• Non-Clustered Index: A separate structure that points to the table data (multiple non-
clustered indexes can exist).
Best Practices:
• Index frequently queried columns, especially those used in WHERE, JOIN, or ORDER BY
clauses.
• Avoid indexing high cardinality columns (columns with very few distinct values) as they are
inefficient.
Example:
CREATE NONCLUSTERED INDEX IX_Users_Username
ON Users (Username);
5. How do you handle database security in SQL Server?
Answer: Database Security can be managed in several ways:
• Authentication: Use Windows Authentication instead of SQL Authentication, as it’s more
secure.

Sai Reddy
saireddy-dotnetfs
• Encryption: Implement Transparent Data Encryption (TDE) and Always Encrypted to protect
sensitive data.
• Access Control: Use Roles and Permissions to restrict access to sensitive data.
• SQL Server Auditing: Enable auditing to log events like login attempts, schema changes, and
data modifications.
Example (Creating a Role with Permissions):
CREATE ROLE db_data_reader;
GRANT SELECT ON SCHEMA::dbo TO db_data_reader;
6. What is deadlock and how do you resolve it?
Answer: A deadlock occurs when two or more transactions block each other, and none can proceed.
SQL Server automatically detects deadlocks and resolves them by killing one of the transactions.
Prevention/Resolution:
• Ensure proper indexing to reduce the time transactions spend on locked resources.
• Avoid unnecessary transactions or long-running queries.
• Access resources in a consistent order to avoid circular waits.
• Use Query Hints like NOLOCK or READPAST carefully to avoid blocking.
Example:
SELECT * FROM Employees WITH (NOLOCK);
7. What are SQL Server Profiler and Extended Events, and how do you use them?
Answer:
• SQL Server Profiler is a tool used to capture and analyze SQL queries and events in real-time.
It is helpful for identifying performance issues and monitoring SQL Server activities.
• Extended Events is a lightweight alternative to SQL Server Profiler, which provides a more
efficient way to capture data about events happening in SQL Server.
Usage:
• Profiler: Can be used to trace slow queries, analyze blocking, and monitor server activity.
• Extended Events: Used for detailed tracking and can be configured to capture a wider range
of events with less overhead.
Example (Using Profiler):
• Start SQL Server Profiler from SSMS, connect to the server, and create a trace that logs all
queries or events that match a specific pattern.
8. What are the common causes of performance bottlenecks in SQL Server?
Answer: Common causes of performance bottlenecks in SQL Server include:
• Locking and Blocking: Transactions waiting on resources held by other transactions.
• Indexing Issues: Missing or fragmented indexes.
• Inefficient Queries: Queries that scan entire tables instead of using indexes.
• Resource Contention: High CPU or memory usage affecting query performance.
• Large Transactions: Transactions that lock too many resources or take too long to complete.
Solution:
• Optimize queries using EXPLAIN or Execution Plans.
• Regularly rebuild or reorganize indexes.
• Use Query Hints and Stored Procedures for commonly used operations.
Example:
DBCC SHOWCONTIG ('Users'); -- Checks for fragmentation
9. How do you monitor and optimize SQL Server performance?
Answer: You can monitor SQL Server performance by using several tools:
• SQL Server Management Studio (SSMS): Use the Activity Monitor to observe current server
performance.

Sai Reddy
saireddy-dotnetfs
• Dynamic Management Views (DMVs): Query system views like sys.dm_exec_requests to
monitor active queries and sys.dm_db_index_physical_stats to analyze index fragmentation.
• SQL Server Profiler/Extended Events: Capture and analyze SQL queries for performance
issues.
• Performance Counters: Use Windows performance counters to monitor resource usage.
Example (Checking Active Queries):
SELECT * FROM sys.dm_exec_requests WHERE status = 'running';
10. What is SQL Server Always On Availability Groups?
Answer: SQL Server Always On Availability Groups provide high availability and disaster recovery
solutions. It allows for a set of databases to fail over together as a group, ensuring that one or more
secondary replicas are available for failover.
Advantages:
• Automatic failover to secondary replicas.
• Supports synchronous and asynchronous replication.
• Can be used for read-only routing to offload reporting queries.
Example:
• Primary replica: Handles write operations.
• Secondary replica: Used for read-only queries and backup operations.

Angular
1. What are the major differences between Angular 13 and Angular 18?
Answer:
• Angular 13: Introduced Angular Material components updates, better performance, and the
deprecation of View Engine.
• Angular 18: Enhanced TypeScript support, improvements in the CLI, stricter typing, and
improved error handling.
You should also focus on new features that were introduced in each version and how they improve
performance and security.
2. How does Angular handle security concerns like XSS and CSRF?
Answer:
• XSS (Cross-Site Scripting): Angular automatically escapes user input to prevent XSS attacks. It
uses sanitization to protect against malicious content in templates (HTML, CSS, JS).
o Example: Angular sanitizes data binding (e.g., {{ data }}) by default.
• CSRF (Cross-Site Request Forgery): Angular automatically includes the CSRF token (if set on
the server) in HTTP requests via the HttpClient service.
o Example: Ensure that XSRF-TOKEN is set as a cookie, and Angular will send it in the
headers of HTTP requests.
3. How do you optimize the performance of Angular applications?
Answer:
• Lazy Loading: Split large modules into smaller chunks and load them only when needed.
• Change Detection Strategy: Use ChangeDetectionStrategy.OnPush to optimize change
detection cycles.
• Track By: In *ngFor, use trackBy to improve performance when rendering lists.
• Avoid Memory Leaks: Properly unsubscribe from Observables using takeUntil or
ngOnDestroy.
• Ahead-of-Time Compilation (AOT): Pre-compiles the application, resulting in faster
rendering.
• Service Workers: Use service workers for caching and making the application work offline.

Sai Reddy
saireddy-dotnetfs
Example (Lazy Loading):
const routes: Routes = [
{
path: 'feature',
loadChildren: () => import('./feature/feature.module').then(m => m.FeatureModule)
}
];
4. Explain the difference between ngOnInit, ngAfterViewInit, and ngAfterContentInit lifecycle
hooks.
Answer:
• ngOnInit: Called once when the component is initialized, ideal for fetching data or
initialization.
• ngAfterViewInit: Called after the component's view (and child views) are initialized. Use for
post-view manipulations.
• ngAfterContentInit: Called after content (projected into the component) has been initialized.
5. What is the role of the HttpInterceptor in Angular? How can it be used for security-related tasks?
Answer: HttpInterceptor allows you to modify HTTP requests and responses globally. You can use it
for adding authentication tokens, handling errors, logging, etc.
• Authentication: Add an authentication token to request headers.
• Error Handling: Intercept HTTP errors and handle them centrally.
Example:
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const clonedReq = req.clone({
setHeaders: {
Authorization: `Bearer ${this.authService.getToken()}`
}
});
return next.handle(clonedReq);
}
}
6. What is Zone.js in Angular, and how does it affect performance and change detection?
Answer: Zone.js is a library that helps Angular track asynchronous operations (like HTTP requests,
setTimeout, etc.) to know when to run change detection. It automatically triggers change detection
when an asynchronous event occurs.
Impact on Performance:
• Performance Overhead: Since Zone.js tracks all asynchronous events, it can introduce
overhead. To optimize, you can consider using ChangeDetectionStrategy.OnPush.

7. Explain Angular’s SecurityContext and how it’s used to sanitize inputs.


Answer: SecurityContext is used in Angular to specify the context in which an expression is
evaluated for security purposes. It is mainly used in DomSanitizer to sanitize values and prevent
vulnerabilities like XSS.
Example (Sanitizing HTML):
import { DomSanitizer, SecurityContext } from '@angular/platform-browser';

constructor(private sanitizer: DomSanitizer) {}

Sai Reddy
saireddy-dotnetfs
getSafeHtml() {
const unsafeHtml = '<div>Some dangerous <script>alert("XSS")</script> content</div>';
return this.sanitizer.sanitize(SecurityContext.HTML, unsafeHtml);
}
8. How do you manage state in Angular, and what are the best practices?
Answer: State management in Angular can be done using various approaches:
• Services: Use Angular services to store and manage application state.
• NgRx: A reactive state management library based on Redux, useful for large applications.
• BehaviorSubject: An RxJS subject used for managing state in a reactive way.
Best Practices:
• Use NgRx or Akita for larger applications with complex state.
• Keep local state in components when the state is scoped to that component.
• Avoid excessive state in components.
9. What are some common security best practices in Angular applications?
Answer:
• Use HTTPS: Always use HTTPS to encrypt data between the client and server.
• Content Security Policy (CSP): Use CSP to restrict the sources from which content can be
loaded.
• Sanitization: Always sanitize untrusted content using Angular's built-in DomSanitizer to
prevent XSS.
• Authentication: Use JWT tokens for secure user authentication and always store tokens
securely (avoid localStorage for sensitive data).
• Secure APIs: Ensure that APIs are secured and only accessible by authorized users.
10. How can you improve the accessibility (a11y) of an Angular application?
Answer: To make an Angular app more accessible:
• Semantic HTML: Use proper HTML tags (like <button>, <form>, <header>, etc.).
• ARIA Roles: Use ARIA (Accessible Rich Internet Applications) roles and properties for
elements that aren’t naturally accessible.
• Keyboard Navigation: Ensure users can navigate the app via keyboard (e.g., tabindex).
• Focus Management: Manage focus appropriately after interactions (e.g., after opening a
modal).
11. What is Angular Universal, and how does it impact SEO and performance?
Answer: Angular Universal is a technology for server-side rendering (SSR) of Angular applications. It
renders the application on the server and sends the fully rendered HTML to the client, improving the
initial load time and SEO.
SEO Impact:
• SSR ensures that search engines can crawl the rendered HTML, improving visibility in search
engine results.
Performance:
• SSR reduces the time-to-interactive (TTI) by sending pre-rendered content to the client,
resulting in faster loading.
12. What are lazy-loaded modules, and how do they affect application performance?
Answer: Lazy-loaded modules are modules that are not loaded until they are required (i.e., when
the user navigates to a route that uses the module). This improves the initial load time by splitting
the application into smaller chunks.
• Lazy Loading reduces the size of the initial bundle, leading to faster startup times.
Example:

Sai Reddy
saireddy-dotnetfs
const routes: Routes = [
{
path: 'feature',
loadChildren: () => import('./feature/feature.module').then(m => m.FeatureModule)
}
];
13. What is Angular CLI, and how does it help in development and production?
Answer: Angular CLI is a command-line interface tool that helps with scaffolding, building, testing,
and deploying Angular applications.
• Development: ng serve, ng generate, ng test, etc.
• Production: ng build --prod to build optimized production-ready apps.
14. What is Dependency Injection in Angular, and how does it improve testing and scalability?
Answer: Dependency Injection (DI) is a design pattern where objects are provided with their
dependencies instead of being responsible for creating them. In Angular, DI is used to inject services
into components, directives, pipes, etc.
Benefits:
• Testability: Easier to mock dependencies in unit tests.
• Scalability: Promotes reusable and maintainable code.

Sai Reddy
saireddy-dotnetfs

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy