Few Imp Questions

Difference between Authentication and Authorization?

Authentication is the process of verifying the identity of a user by obtaining some sort of credentials and using those credentials to verify the user's identity. If the credentials are valid, the authorization process starts. Authentication process always proceeds to Authorization process.

Authorization is the process of allowing an authenticated users to access the resources by checking whether the user has access rights to the system. Authorization helps you to control access rights by granting or denying specific permissions to an authenticated user.

How do you protect public methods from non-authenticated users?

Authorize attribute. Assuming that you have some sort of authentication setup in your application (forms authentication, windows authentication or OAuth) a logged in user has a token stored on their browser in the form of a cookie. When a user navigates your application, their token is passed along with them. When the Authorize attribute is applied to one of your controller methods, your application examines their token and if they are an authenticated user with the correct permissions, it allows them in, if not it will redirect them to an action you have specified. The default redirect is to the registration/login page. AllowAnonymous lets users who have not been authenticated access the action or controller.

How to make a Url or Page un-authenticated?

[AllowAnonymous] - Anyone can access view related to the action in controller

[Authorize] - Only registered users or specific set of users can access view related to the action in controller. You can also specify list of users in the attribute to grant access to them

Explain about state management in ASP.NET?

State management means to preserve state of a control, web page, object/data, and user in the application explicitly because all ASP.NET web applications are stateless, 

Client side: Hidden Field, View State, Cookies, Control State, Query Strings

Server side: Session, Application

What are the drawback of using sessions?

ASP.NET Session State advantages

- Sessions are very simple to use. If you have a global variable related to individual visitor, you can place it in session and it will be visible from all pages on website.

- If InProc mode is used, any type of object could be stored. In case that Session State or SQL Server is used, objects must be serialized before saving.

- Separated global data for each visitor. Every visitor has its own collection of session variables.

ASP.NET Session State disadvantages

- Every variable is stored as Object. That means you need to convert Object to certain type when read session variable.

- In addition to this, if session is empty, Object will be null. Before reading session variable, you need to check it for null. Even if variable is initialized before, it could be null because session is expired.

- Variable name is type of string. If you hard code name of the variable, there is an option to make type mistake somewhere. The problem is, if you try to read session variable that doesn't exist, ASP.NET will not return any exception or warning. It will simply create new variable with wrong name which has null value. These types of errors could be hard to find.

- Session data should not be used for storing of sensitive data. There is a possibility that malicious user obtain regular visitor's session id. If session state is used to store information like: "allow access to administration area or not" or something like that, attacker could see website's sensitive data, other's private data, edit database, delete content etc.

- If InProc mode is used, sessions easily exhaust all server resources and thus decrease website performances.

How to manage sessions across multiple tabs in single browser or mutiple instances of browser?

The way I solved it is by using localStorage events. When a user opens a new tab, we first ask any other tab that is opened if he already have the sessionStorage for us. If any other tab is opened it’ll send us the sessionStorage through localStorage event, we’ll duplicate that into the sessionStorage. 

            The sessionStorage data will not stay in the localStorage, not even for 1 millisecond as it being deleted in the same call. The data is shared through the event payload and not the localStorage itself.

Explain session issues on shared computer?

How to manage state in web applications wihtout sessions?

Query String. While sending data using query string, encypt the data and pass it.

What are SOLID principles?

·         S - Single-responsiblity principle

·         O - Open-closed principle

·         L - Liskov substitution principle

·         I - Interface segregation principle

·         D - Dependency Inversion Principle

A class should have one and only one reason to change, meaning that a class should have only one job.

Objects or entities should be open for extension, but closed for modification.

You should be able to use any derived class instead of a parent class and have it behave in the same manner without modification

A client should never be forced to implement an interface that it doesn't use or clients shouldn't be forced to depend on methods they do not use.

Entities must depend on abstractions not on concretions. It states that the high level module must not depend on the low level module, but they should depend on abstractions.

Explain about Interface Seggrgation principle?

This principle states that any client should not be forced to use an interface which is irrelevant to it. Now what does this mean, suppose there is one database for storing data of all types of employees (i.e. Permanent, non-permanent), now what will be the best approach for our interface?

Hide   Copy Code

public interface IEmployee

{

    bool AddEmployeeDetails();

}

And all types of employee class will inherit this interface for saving data. This is fine right? Now suppose that company one day told to you that they want to read only data of permanent employees. What you will do, just add one method to this interface?

Hide   Copy Code

public interface IEmployeeDatabase

{

    bool AddEmployeeDetails();

    bool ShowEmployeeDetails(int employeeId);

}

But now we are breaking something. We are forcing non-permanent employee class to show their details from database. So, the solution is to give this responsibility to another interface.

Hide   Copy Code

public interface IAddOperation

{

    bool AddEmployeeDetails();

}

public interface IGetOperation

{

    bool ShowEmployeeDetails(int employeeId);

}

And non-permanent employee will implement only IAddOperation and permanent employee will implement both the interface.

What IoC Containers have you used?

Castle Windsor based on the Castle MicroKernel.

StructureMap has been around since June 2004

Spring.NET

Autofac intends to be IoC with a C# 3.0 flavor, but also supports 2.0.

Unity

Ninject formerly "Titan"

What is the purpose of using IoC?

 

Is mainly a way to get more loose coupling between disparate parts of your program. the testing is simpler. Unit testing is also easier with DI as you can mock out the database, 

What are different lifetimes options for objects in IoC containers?

 

What is asynchronous programming?

It means that the operation runs independent of main or other process flow. In general c# program starts executing from the Main method and ends when the Main method returns. In between all the operations runs sequentially one after another. One operation must wait until its previous operation finishes.

In asynchronous programming a method is called that runs in the background and the calling thread is not blocked. After calling the method the execution flow immediately backs to calling thread and performs other tasks. Normally it uses Thread or Task

What is the difference between async and parallel programming?

An asynchronous program dispatches tasks to devices that can take care of themselves, leaving the program free do something else until it receives a signal that the results are finished.

Parallel programs distribute their tasks to multiple processors, that actively work on all of them simultaneously.

What is the role of Wait() in async? How OS handles Wait() method?

Task.Run(async () => { await SomeClass.Initiate(new Configuration()); })

Task.Run executes its code on a thread pool thread. So, that async lambda will be run on a thread pool thread. Task.Run returns a Task which represents the execution of the asynclambda. After calling Task.Run, the code calls Task.Wait:

Task.Run(async () => { await SomeClass.Initiate(new Configuration()); }).Wait();

This will block the main console app until the async lambda is completely finished.

If you want to see how it's broken out further, the following is roughly equivalent:

static async Task AnonymousMethodAsync()

{

  await SomeClass.Initiate(new Configuration());

}

 

static void Main(string[] args)

{

  var task = Task.Run(() => AnonymousMethodAsync());

  task.Wait();

  while (true) ;

}

What issues have you observed using async?

Don't Block on Async Code it can Causes the Deadlock.

In your “library” async methods, use ConfigureAwait(false) wherever possible. Don’t block on Tasks; use async all the way down.

What is the relationship between Task and Thread?

Task is a higher level concept than thread...

Thread is a lower-level concept:

The Thread class is used for creating and manipulating a thread in Windows.

A Task represents some asynchronous operation and is part of the Task Parallel Library, a set of APIs for running tasks asynchronously and in parallel.

What quality metrics do you track?

Cyclomatic Complexity is based on loops and various decisions in code. Class Coupling finds the number of dependencies on other classes. More the class coupling, lower is the index. Depth of Inheritance is for inheritance of classes from the Object class. Lines of code is the actual number of executable lines. The index is between the range of 0 to 100. 0 to 9 is low, 10 to 19 is moderate and 20 onwards is high. The higher the maintainability index, the better are chances of maintaining it.

 

What is the drawback of using code coverage as metric?

One drawback of code coverage measurement is that it measures coverage of what has been written, i.e. the code itself; it cannot say anything about the software that has not been written.

If a specified function has not been implemented or a function was omitted from the specification, then structure-based techniques cannot say anything about them it only looks at a structure which is already there.

What is the difference between mocking & stubbing?

Mocks use a framework to generate a "mock" of your dependency. For example if officeClass is a repository for your data then you can use a mock framework (I use MOQ) to generate a mock of your repository. That's why using interfaces for your dependency make it ideal for testing, the mocking framework can easily make a mock of an interface for testing.

With stubs as I understand it, you manually stub out your dependency and create canned responses. For example if you have an interface IOfficeClass and you create a new class that inherits from it, you can inject that class into your service to allow you to use it.

What is TDD?

we start writing tests firsts. Initially these tests fails but as we add more application code these tests pass. This helps us in many ways

·         We write application code based on the tests. This gives a test first environment for development and the generated application code turns out to be bug free.

·         With each iteration we write tests and as a result with each iteration we get an automated regression pack. This turns out to be very helpful because with every iteration we can be sure that earlier features are working.

·         These tests serve as documentation  of application behavior and reference for future iterations.

What is BDD?

Behavior Driven testing is an extension of TDD.

·         Tests are written in plain descriptive English type grammar

·         Tests are explained as behavior of application and are more user focused

·         BDD frameworks such as Cucumber/ SpecFlow

How to manage exception handling in MVC?

·         Web.Config customErrors

·         MVC HandleErrorAttribute

·         Controller.OnException method

·         HttpApplication Application_Error event

·         Collect exceptions via .NET profiling with Retrace

There are two critical things that you need accomplish with error handling:

<system.web>

    <customErrors mode="On" defaultRedirect="~/ErrorHandler/Index">

        <error statusCode="404" redirect="~/ErrorHandler/NotFound"/>

    </customErrors>

<system.web/>

[HandleError(ExceptionType = typeof(SqlException), View = "SqlExceptionView")]

public string GetClientInfo(string username)

{

         return "true";

}

public class UserMvcController : Controller

{

   protected override void OnException(ExceptionContext filterContext)

   {

      filterContext.ExceptionHandled = true;

 

           //Log the error!!

      _Logger.Error(filterContext.Exception);

 

      //Redirect or return a view, but not both.

      filterContext.Result = RedirectToAction("Index", "ErrorHandler");

      // OR 

      filterContext.Result = new ViewResult

      {

         ViewName = "~/Views/ErrorHandler/Index.cshtml"

      };

   }

}

protected void Application_Error()

   {

      var ex = Server.GetLastError();

      //log the error!

      _Logger.Error(ex);

   }

 

1.     Gracefully handling errors and show your users a friendly error page

2.     Logging errors so that you are aware of them and can monitor them

What is XSS (cross site scripting)?

Cross-site Scripting (XSS) is an attack in which malicious scripts is injected via input fields this attack is most common and allows an attacker to steal credentials and valuable data that can lead to a big security breach.

Solution: -

1.     [ValidateInput(false)]

2.     [AllowHtml]

3.     [RegularExpressionAttribute]

What is SQL Injection?

SQL injection attack can give valuable data to the attacker that can lead to a big security breach and can also take full access to the database server. In SQL Injection attacker always try to enter malicious SQL statement which will get executed in the database and return unwanted data to the attacker.

Solution:-  Validate inputs, Use of low-privileged database logins, Use Parameterized queries, Use ORM (e.g. Dapper , Entity framework ), Use Stored Procedures

What is cyclomatic complexity?

 

 

 

 

 

 

             

 

            

 

 

How to implement async programming in MVC controllers?

You can use asynchronous action methods for long-running, non-CPU bound requests. This avoids blocking the Web server from performing work while the request is being processed.

An asynchronous request takes the same amount of time to process as a synchronous request. For example, if a request makes a network call that requires two seconds to complete, the request takes two seconds whether it is performed synchronously or asynchronously. However, during an asynchronous call, the server is not blocked from responding to other requests while it waits for the first request to complete. Therefore, asynchronous requests prevent request queuing when there are many requests that invoke long-running operations.

Async

Async keyword is used to call the function/method as asynchronously.

Await

Await keyword is used when we need to get result of any function/method without blocking that function/method.

Asynchronous Programming 

Asynchronous Programming means parallel programming. By using Asynchronous Programming, the compiler can execute multiple functions / methods at same time without blocking any function / method.

If web.config file is deployed with connection string in plain text, who can access the file?

It may contain all information that requires running your web application. There are often passwords for SQL database connections, SMTP server, API Keys, or other critical information. In addition to this, Web.Config files are usually treated as just another source code file, that means, any developer on the team, or more accurately anyone with access to the source code, can see what information is stored in Web.Config file.

If connection string is not encrypted, any user can access to web.config and can view sensitive information like connection string. Attacker might get access to web.config and they can easily capture connection string which obviously lead serious security threat.

aspnet_regiis.exe example encrypts the <connectionStrings> section using the DPAPI provider with a machine-level key:

ASPNET_REGIIS -PEF "connectionStrings" "F:\Visual Studio\ prjname \EncryptConnectionString" 

ASPNET_REGIIS -PDF "connectionStrings" "F:\Visual Studio\prjname\EncryptConnectionString"

 

How do you decrypt the connection section at the time it is needed in the application?

ASP.NET 2.0 includes a protected configuration system for encrypting and decrypting configuration information. This includes methods in the .NET Framework that can be used to programmatically encrypt or decrypt configuration information. The protected configuration system uses the provider model, which allows developers to choose what cryptographic implementation is used.

The .NET Framework ships with two protected configuration providers:

·         RSAProtectedConfigurationProvider - uses the asymmetric RSA algorithm for encryption and decryption.

·         DPAPIProtectedConfigurationProvider - uses the Windows Data Protection API (DPAPI) for encryption and decryption.

 

What is property based injection? Are there any challenges with it?

Property injection violates the Single Responsibility Principle. The class that uses it has three responsibilities. First, it has taken upon itself the responsibility of choosing your DI software. Second, it must gather its dependencies from the DI container. And what was the third responsibility? (Oops.) Oh yeah -- it also does whatever you conceived as its primary task.

With constructor injection, intellisense and the compiler will both help you out. With property injection, you won't know that you forgot something until your program fails at runtime. On my team, we have found that discoverability is very important. 

How you manage object lifetime with DI?

 

How do you block input text containing script tag or special characters?

Regular expressions, Patterns, Validate inputs, encoding and decoding

What are the order of priority to improve the quality and deploy to production?

Continuous Delivery is a small build cycle with short sprints

1.     Always use a version control system

2.     Automate the build

3.    Your build should be self-testing. Include automated tests in the build process to catch bugs faster and with higher efficiency. 

4.     Commit at least every day. 

5.     Keep the build fast. The whole point of Continuous Integration is to provide rapid feedback. 

6.    Test in a staging environment before deploying software on production

7.    Make it easy for everyone to get the latest executable. 

8.    Prepare environments.

Have you followed TDD in your projects?

In TDD, I develop test cases before I write any code. Once I have test cases in place, then I can build the appropriate functionality to make the tests pass. This is a reverse of the standard coding model, where code is developed first, then tested. But this method has several benefits:

What is authorization and how do you implement?

To perform authorization, we can use Authorize attribute in the action method of the controller. We can authorize users based on their username or role defined in the database.

Authorizing based on username [Authorize(Users = "Ram")]

Authorizing based on role [Authorize(Roles = "Admin, SuperAdmin")]

What is encryption/decryption and hashing?

A hash is a string or number generated from a string of text. The resulting string or number is a fixed length, and will vary widely with small variations in input. The best hashing algorithms are designed so that it's impossible to turn a hash back into its original string.

 When storing a password, hash it with a salt, and then with any future login attempts, hash the password the user enters and compare it with the stored hash.

MD5, SHA

Encryption turns data into a series of unreadable characters, that aren't of a fixed length. The key difference between encryption and hashing is that encrypted strings can be reversed back into their original decrypted form if you have the right key.

There are two primary types of encryption, symmetric key encryption and public key encryption. In symmetric key encryption, the key to both encrypt and decrypt is exactly the same. This is what most people think of when they think of encryption.

Public key encryption by comparison has two different keys, one used to encrypt the string (the public key) and one used to decrypt it (the private key).

AES PGP 

Encryption should only ever be used over hashing when it is a necessity to decrypt the resulting message. For example, if you were trying to send secure messages to someone on the other side of the world, you would need to use encryption rather than hashing, as the message is no use to the receiver if they cannot decrypt it.

Why you use factory pattern for objects creation?

Well, whenever you come across words like kinds or types, watch out for application of factory pattern!! 

private void GetRoomDetails(string roomType)

{

    IRoomType room = null;

 

    switch (roomType)

      {

         case RoomTypes.AC:

                 room = new ACRoom();

                 break;

 

            case RoomTypes.Deluxe:

                 room = new DeluxeRoom();

                 break;

 

            case RoomTypes.NonAC:

                 room = new NonACRoom();

                 break;

      }

      room.GetDetails();

}

Advantages

o    Easy to implement

o    Client application code doesn’t have to change drastically

o    Moreover, the tight coupling between client and product classes is overcome and turned into coupling between factory and product classes. Hence client need not know the instantiation logic of products.

Disadvantages

o    If we add any new product (room), we need a new case statement in GetRoomType method of Factory class. This violates open/closed design principle.

o    We can avoid modifying the Factory class by using sub classing. But sub classing means replacing all the factory class references everywhere through the code.

o    We have tight coupling between Factory class and products

If there is single object to create, do you still follow factory or any other approach?

No, factory pattern does not make sense in this scenario. We can use singleton pattern if the object shared across all the client.

What is dependency injection?

How to block script tags in input text?

You may have to sanitize the all html inputs to block script tags otherwise which leads to XSS attack. You can read about XSS attack for more details

How to permit and execute a script tag in browser?

We can use [ValidateInput(false)] 

We can [AllowHtml] attribute on properties in model or view model to disable request validation

What is lazy loading?

Lazy loading is a concept where we delay the loading of the object until the point where we need it. Putting in simple words, on demand object loading rather than loading objects unnecessarily.

When to use what

If secret config file is used, where to store the secret config file?

The Secret Manager tool abstracts away the implementation details, such as where and how the values are stored. You can use the tool without knowing these implementation details. In the current version, the values are stored in a JSON configuration file in the user profile directory:

·         Windows: %APPDATA%\microsoft\UserSecrets\<userSecretsId>\secrets.json

What is yellow page?

If there is unhandled exception in application iis displays standard yellow page with status code 500. 

What do you mean by application crash?

It means you have an uncaught unhanded exception and it is crashing your application.

If it is working in debug mode you need to look to see what is different about the release version. Are all the libraries present? Do you have your app.config setup?

Check your event viewer under Windows Logs -> Application for more information.

Why do you need exception handling? How will it help?

Implementing these patterns can help insulate your application from changes in the data store and can facilitate automated unit testing or test-driven development (TDD).

The business logic accesses data from data stores such as databases, SharePoint lists, or Web services. Directly accessing the data can result in the following:

Benefits of Repository Pattern

Benefits of Generic Repository Pattern

What is the difference between constant and readonly?

The compile time constants are declared by using the const keyword which value cannot be changed during the execution of the program.

The Run time constants are declared by using the Readonly keyword which value cannot be changed during the execution of the program.

Let us  outline the differences  between const and readonly variables.

Is there any datatype restriction for a constant?

Yes. Object cannot be declared as constant and only immutable types (String, number, null etc) can be declared as constant

Have you used HttpClient any time?

Most likely we use HttpClient in consuming/calling web apis (or) WCF RESTFUL servicies. You can talk about more on HttpClient if you have implemented in any of your previous projects.

What is the status code for OK?

 400 - Bad Request.

404 - Not Found

500 - Internal Server Error

200 – OK

501 Not Implemented.

What are the 4 main pillars/manifesto of Agile?

1.     Individuals and interactions over processes and tools

2.     Working software over comprehensive documentation

3.     Customer collaboration over contract negotiation

4.     Responding to change over following a plan

What is the difference between class and struct. Have you used struct any time?

Class is a reference type which has set of methods, propertes and access specifiers. Struct is value type and can be defined with multiple data types with in it.