Top 10+ Interview questions and answers for dotnet developer experience and fresher

Top 10+ Here are detailed answers to some of the questions you asked:

1. Async Method Execution Time

Question: If MethodA starts at 11:00, when will it return true?

Answer: The time when MethodA returns depends on the execution times of MethodB and MethodC. Since both methods are awaited, MethodA will return true only after both MethodB and MethodC complete. If MethodB and MethodC take 5 seconds each, then MethodA will return true after 10 seconds (i.e., at 11:00:10).





2. LINQ Query to Get Top 3 Salaries Department-wise

SQL Query:

SELECT Department.name, emp.id, emp.name, emp.salary
FROM Employee emp
JOIN Department ON emp.depid = Department.depid
WHERE emp.salary IN (SELECT TOP 3 salary FROM Employee e WHERE e.depid = emp.depid ORDER BY salary DESC)
ORDER BY Department.name, emp.salary DESC;

LINQ Query:

var result = context.Employees
             .GroupBy(e => e.DepartmentId)
             .SelectMany(g => g.OrderByDescending(e => e.Salary).Take(3))
             .Select(e => new { e.Name, e.Salary, Department = e.Department.Name });




3. Authentication and Authorization Lifecycle

Authentication: The process of verifying a user’s identity.

Authorization: Determines whether a user has permission to access a resource.

Lifecycle:

1. Login: User submits credentials.


2. Authentication: Validates credentials (usually via a database or an external service).


3. Token Issuance: If credentials are valid, a token is issued (like JWT or OAuth tokens).


4. Authorization: On each request, the token is validated to check if the user has access to the resource.




4. Sample Code for Token Validation

public bool ValidateToken(string token)
{
    var tokenHandler = new JwtSecurityTokenHandler();
    var validationParameters = new TokenValidationParameters
    {
        ValidateIssuerSigningKey = true,
        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("your_secret_key")),
        ValidateIssuer = false,
        ValidateAudience = false,
        ClockSkew = TimeSpan.Zero
    };

    try
    {
        var principal = tokenHandler.ValidateToken(token, validationParameters, out SecurityToken validatedToken);
        return true;
    }
    catch
    {
        return false;
    }
}


5. CORS (Cross-Origin Resource Sharing)

Concept: CORS allows web applications to interact with resources from different origins. This mechanism ensures secure access across domains.

Sample Code to Enable CORS:

public void Configure(IApplicationBuilder app)
{
    app.UseCors(builder =>
        builder.AllowAnyOrigin()
               .AllowAnyMethod()
               .AllowAnyHeader());
    app.UseMvc();
}

Detailed Explanation: CORS prevents malicious websites from making unauthorized API requests to your server. It's configured on the server side, typically through headers like Access-Control-Allow-Origin.




6. Transaction in API

A transaction in an API ensures a series of operations are treated as a single unit. If one operation fails, all changes made during the transaction are rolled back. In .NET, you can manage transactions using the TransactionScope or the database context.




7. LINQ Query to Count Repeated Words

var input = "i saw a saw in saw";
var wordCounts = input.Split(' ')
                      .GroupBy(w => w)
                      .Select(g => new { Word = g.Key, Count = g.Count() });



8. Dependency Injection (DI)

Explanation: DI is a design pattern where objects are passed their dependencies rather than creating them inside. This promotes loose coupling and enhances testability.

Injecting DI in .NET Core:

1. Register services in Startup.cs:

public void ConfigureServices(IServiceCollection services)
{
    services.AddTransient<IMyService, MyService>();
}


2. Use DI in controllers or services:

public class MyController : Controller
{
    private readonly IMyService _myService;
    public MyController(IMyService myService)
    {
        _myService = myService;
    }
}





9. Is it possible to transfer requests to one middleware to another?

Answer: Yes, middleware in .NET Core is executed in a pipeline. A request can pass from one middleware to another using next() in the Invoke method:

public async Task Invoke(HttpContext context)
{
    await _next(context); // Pass request to the next middleware
}




10. Filters in .NET Core

Filters are used to execute code before or after certain stages in the request pipeline.

Types: Authorization Filters, Resource Filters, Action Filters, Exception Filters, Result Filters.


Example of using a custom action filter:

public class MyActionFilter : IActionFilter
{
    public void OnActionExecuting(ActionExecutingContext context)
    {
        // Code before action executes
    }
    public void OnActionExecuted(ActionExecutedContext context)
    {
        // Code after action executes
    }
}



11. SQL Query to Delete Duplicate Records

WITH CTE AS (
    SELECT *, ROW_NUMBER() OVER (PARTITION BY column1, column2 ORDER BY id) AS rn
    FROM TableName
)
DELETE FROM CTE WHERE rn > 1;



12. Difference Between Temp Table and Temp Variable in SQL

Temp Table:

Stored in tempdb and can have indexes.

Can be used across multiple batches and connections.


Table Variable:

Stored in memory.

Limited scope within the batch or stored procedure.




13. Output of C# Program (Out Parameter Example)

static void Main(string[] args)
{
    int a = 50, b = 80;
    Console.WriteLine(a + " " + b);  // Output: 50 80
    Show(a, out b);
    Console.WriteLine(a + " " + b);  // Output: 50 25
}
public static void Show(int a, out int b)
{
    a = b = 5;
    a *= a;  // a = 25
    b *= b;  // b = 25
    Console.WriteLine(a + " " + b);  // Output: 25 25
}

#dotnettechpro #dotnet #csharp #ado #codelife #dotnetdeveloper

Comments

Popular posts from this blog

Finding 2nd and 3rd Highest and Lowest Salaries Using LINQ

Sonar qube for code scan

Generate 100 records using linq c#