Sunday, September 27, 2020

Dependency Injection ( IoC: Inversion of control)

 

IoC Container

IoC Container (a.k.a. DI Container) is a framework for implementing automatic dependency injection. It manages object creation and it's life-time, and also injects dependencies to the class.

The IoC container creates an object of the specified class and also injects all the dependency objects through a constructor, a property or a method at run time and disposes it at the appropriate time. This is done so that we don't have to create and manage objects manually.

All the containers must provide easy support for the following DI lifecycle.

  • Register: The container must know which dependency to instantiate when it encounters a particular type. This process is called registration. Basically, it must include some way to register type-mapping.
  • Resolve: When using the IoC container, we don't need to create objects manually. The container does it for us. This is called resolution. The container must include some methods to resolve the specified type; the container creates an object of the specified type, injects the required dependencies if any and returns the object.
  • Dispose: The container must manage the lifetime of the dependent objects. Most IoC containers include different lifetimemanagers to manage an object's lifecycle and dispose it.

There are many open source or commercial containers available for .NET. Some are listed below.

  • Unity Container :
  • ===========

I have seen many articles about Dependency Injection in MVC and C# and thought to write an article about using it in ASP.NET MVC5.

Below is short brief of Dependency Injection (DI)

This pattern is an implementation of "Inversion of Control". Inversion of Control (IoC) says that the objects do not create other objects on which they rely to do their work; instead, they get the objects that they need from an outside source (for example, an XML configuration file).

So now, let’s implement the same.

  • Add a new ASP.NET MVC project.

    Dependency Injection In ASP.NET

    Dependency Injection In ASP.NET

    Dependency Injection In ASP.NET
  • Now, install the "Unity.Mvc5" Container using NuGet Package Manager, as shown below.

    Dependency Injection In ASP.NET

    Dependency Injection In ASP.NET

    When it is installed successfully, you will find the following two references added to your project and a UnityConfig.cs class file in App-Start folder.

    Dependency Injection In ASP.NET
  • Now, let’s create the repository that will be accessed by Controller.

    • Add a folder named Repository.
    • Add an interface IUserMasterRepository.
      1. interface IUserMasterRepository  
      2.     {  
      3.         IEnumerable<UserMaster> GetAll();  
      4.         UserMaster Get(int id);  
      5.         UserMaster Add(UserMaster item);  
      6.         bool Update(UserMaster item);  
      7.         bool Delete(int id);  
      8.     }  
  • Now, add the repository which has your data access code.
    1. public class UserMasterRepository : IUserMasterRepository  
    2.     {  
    3.         private List<UserMaster> users = new List<UserMaster>();  
    4.         private int Id = 1;  
    5.   
    6.         public UserMasterRepository()  
    7.         {  
    8.             // Add products for the Demonstration  
    9.             Add(new UserMaster { Name = "User1", EmailID = "user1@test.com", MobileNo="1234567890" });  
    10.             Add(new UserMaster { Name = "User2", EmailID = "user2@test.com", MobileNo = "1234567890" });  
    11.             Add(new UserMaster { Name = "User3", EmailID = "user3@test.com", MobileNo = "1234567890" });  
    12.         }  
    13.   
    14.         public UserMaster Add(UserMaster item)  
    15.         {  
    16.             if (item == null)  
    17.             {  
    18.                 throw new ArgumentNullException("item");  
    19.             }  
    20.   
    21.             item.ID = Id++;  
    22.             users.Add(item);  
    23.             return item;  
    24.         }  
    25.   
    26.         public bool Delete(int id)  
    27.         {  
    28.             users.RemoveAll(p => p.ID  == id);  
    29.             return true;  
    30.         }  
    31.   
    32.         public UserMaster Get(int id)  
    33.         {  
    34.             return  users.FirstOrDefault(x => x.ID == id);  
    35.         }  
    36.   
    37.         public IEnumerable<UserMaster> GetAll()  
    38.         {  
    39.             return users;  
    40.         }  
    41.   
    42.         public bool Update(UserMaster item)  
    43.         {  
    44.             if (item == null)  
    45.             {  
    46.                 throw new ArgumentNullException("item");  
    47.             }  
    48.   
    49.               
    50.             int index = users.FindIndex(p => p.ID == item.ID);  
    51.             if (index == -1)  
    52.             {  
    53.                 return false;  
    54.             }  
    55.             users.RemoveAt(index);  
    56.             users.Add(item);  
    57.             return true;  
    58.         }  
    59.     }  

Note

Here, we have used a repository. You can use services which will consume your Repository.

  • Now, register this repository to container in UnityConfig.cs.
    1. public static void RegisterComponents()  
    2.         {  
    3.             var container = new UnityContainer();  
    4.   
    5.              
    6.             container.RegisterType<IUserMasterRepository, UserMasterRepository>();  
    7.             DependencyResolver.SetResolver(new UnityDependencyResolver(container));  
    8.         }  
  • Add UnityConfiguration in AppStart method of Global.asax
    1. protected void Application_Start()  
    2.         {  
    3.             AreaRegistration.RegisterAllAreas();  
    4.             FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);  
    5.             RouteConfig.RegisterRoutes(RouteTable.Routes);  
    6.             BundleConfig.RegisterBundles(BundleTable.Bundles);  
    7.   
    8.               
    9.             UnityConfig.RegisterComponents();  
    10.         }  
  •  Inject the Dependency in Controller.

    • Create UserController

      Dependency Injection In ASP.NET

      Dependency Injection In ASP.NET

    • Now, in the below code, we have created a constructor of UserContoller, injected the UserMasterRepository, and accessed it in Index action.
      1. public class UserController : Controller  
      2.     {  
      3.         readonly IUserMasterRepository userRepository;  
      4.         public UserController(IUserMasterRepository repository)  
      5.         {  
      6.             this.userRepository = repository;  
      7.         }  
      8.         // GET: User  
      9.         public ActionResult Index()  
      10.         {  
      11.             var data = userRepository.GetAll();  
      12.                 return View(data);  
      13.         }  
      14. }  
  • Add a View for the same.

    • Add User folder in Views folder.
    • Add Index View.

      Dependency Injection In ASP.NET

      Dependency Injection In ASP.NET

Below is the code which needs to be written in Index View file.

  1. @model IEnumerable<MVCWithDI.Repository.UserMaster>  
  2.   
  3. @{  
  4.     ViewBag.Title = "Users";  
  5.     Layout = "~/Views/Shared/_Layout.cshtml";  
  6. }  
  7.   
  8. <h2>Index</h2>  
  9.   
  10. <p>  
  11.     @Html.ActionLink("Create New""Create")  
  12. </p>  
  13. <table class="table">  
  14.     <tr>  
  15.         <th>  
  16.             @Html.DisplayNameFor(model => model.Name)  
  17.         </th>  
  18.         <th>  
  19.             @Html.DisplayNameFor(model => model.EmailID)  
  20.         </th>  
  21.         <th>  
  22.             @Html.DisplayNameFor(model => model.MobileNo)  
  23.         </th>  
  24.         <th></th>  
  25.     </tr>  
  26.   
  27. @foreach (var item in Model) {  
  28.     <tr>  
  29.         <td>  
  30.             @Html.DisplayFor(modelItem => item.Name)  
  31.         </td>  
  32.         <td>  
  33.             @Html.DisplayFor(modelItem => item.EmailID)  
  34.         </td>  
  35.         <td>  
  36.             @Html.DisplayFor(modelItem => item.MobileNo)  
  37.         </td>  
  38.         <td>  
  39.             @Html.ActionLink("Edit""Edit"new { id=item.ID }) |  
  40.             @Html.ActionLink("Details""Details"new { id=item.ID }) |  
  41.             @Html.ActionLink("Delete""Delete"new { id=item.ID })  
  42.         </td>  
  43.     </tr>  
  44. }  
  45.   
  46. </table>  

Now, run the project. Here is the output.

Dependency Injection In ASP.NET

Sunday, September 6, 2020

OOPs Interview Questions !!!

 1) Difference between Abstract class and Interface ?

2) How can we call abstract class ?

3) Is it possible to declare a class as private ? If yes what happens ?

4) can we declare static constructor in abstract class ? If yes when it will be fired ?

5) Difference between Static class and Singleton design pattern class ?

6) Singleton design pattern steps ?

7) Why it is not possible to create an object for a abstract class ?

8) A:B

  B:C

if we create object like this

Class A obj=new Class C():

what heppens in different scenarios ?

1) Override method Implementations 

2) Method Implementation using New keyword.

9) what are the different types of constructors and order of the execution in single class and inherited class and multilevel inheritance ?

10) If a class inherited from two different interfaces(multiple inheritance) and those have same method name then how do it will be implemented ?

11) What is Abstraction with example and Encapsulation ?

13)  Difference between IEnumerable & IQuarable ?

14) Differencce between IEnumarable & IEnumerator ?

15) Threadings, Delegates & Parallel program with exaples ?

16) What is the use of Interfaces ?

17) SOLID Principles with example ?

18) Design patterns like Factory, Singleton, Abstract etc..

19) Entity Framework Interview Questions

20) .NET Core life cycle ( Middleware examples, custom middlewares )

21) Azure :

Functions, LogicApps, ServiceBus, WebLogic, App Service gatway, API Management Gateway, Storages etc...


Keep update the entities if the db modified in entity framework

 public class MyContext : DbContext 

{

    public MyContext() {

        Database.SetInitializer(new DropCreateDatabaseIfModelChanges<MyContext>());
    }
}

If we declare in global.asax then automatically will done.
 Database.SetInitializer(new DropCreateDatabaseIfModelChanges<MyContext>());

AntiForgery in MVC

Prevent Cross-Site Request Forgery (XSRF/CSRF) attacks in ASP.NET Core


AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimsIdentity.DefaultNameClaimType;


[HttpPost, ActionName("Edit")] [ValidateAntiForgeryToken] public ActionResult EditPost(int? id) {

}

Friday, May 15, 2020

What is Interface?

What is Interface?
  1. An interface can contain signatures (declarations) of the Methods, Properties, Indexers and Events.
  2. The implementation of the methods is done in the class that implements the interface.
  3. A Delegate is a type that can't be declared in an interface. You can either use an event (if appropriate) or declare a delegate outside the interface but in the same namespace.
  4. Interfaces in C# provides a way to achieve runtime polymorphism. Using interfaces, we can invoke functions from various classes through the same Interface reference, whereas using virtual functions we can invoke functions from various classes in the same inheritance hierarchy through the same reference.
  5. An interface can inherit from one or more base interfaces.
  6. A class that implements an interface can explicitly implement members of that interface.
  7. An explicitly implemented member cannot be accessed through a class instance, but only through an instance of the interface.
Purposes of Interfaces
  1. Create loosely coupled software.
  2. Support design by contract (an implementer must provide the entire interface).
  3. Allow for pluggable software.
  4. Allow objects to interact easily.
  5. Hide implementation details of classes from each other.
  6. Facilitate reuse of software.

What is the difference between a Local and a Global temporary table?

What is the difference between a Local and a Global temporary table?

Temporary tables are used to allow short term use of data in SQL Server. They are of 2 types:

Local
- Only available to the current Db connection for current user and are cleared when connection is closed.
- Multiple users can’t share a local temporary table.

Global
- Available to any connection once created. They are cleared when the last connection is closed.
- Can be shared by multiple user sessions.

What is the difference between a Local and a Global temporary table?

A local temporary table lives until the connection is valid or until the duration of a compound statement.

A global temporary table is permanently present in the database. However, the rows of the table are present until the connection is existent. Once the connection is closed, the data in the global temporary table disappears. However, the table definition remains with the database for access when database is opened next time.

Thursday, August 1, 2019

.NET Interview Questions !!!

Q) .net vs java
FeatureMS .NetJava/JEE
Operating SystemWindowsMultiple OS
Common Language RuntimeCommon Language RuntimeJava Virtual Machine
XMLSystem XMLJava API for XML Processing
NamingJava Naming and Directory InterfaceActive Directory Service Interfaces
HTTP EngineInternet Information ServicesApplication Servers from various vendors
Server Components.Net, COM+ServicesEnterprise Java Beans

Q1) What is the relation between Classes and Objects?
Class applies to a type or model of a GROUP of itedot-ms, objects, or concepts.
Object applies to a specific material item or concept, a group of which may comprise a class.
Q2) What is an IL?
(IL) Intermediate Language is also known as MSIL is MicroSoft Intermediate Language or Common Language Runtime (CLR) . When we compile .Net applications, its complied to MSIL, which is not machine read language. Hence Common Language Runtime (CLR) with JustIn Time Complier (JIT) , converts this MSIL to native code (binary code) , which is machine language.
Q3) What are the defining traits of an object-oriented language?
The defining traits of an object-oriented language are:
  • Inheritance
  • Abstraction
  • Encapsulation
  • Polymorphism
1. Inheritance: The main class or the root class is called as a Base Class. Any class which is expected to have ALL properties of the base class along with its own is called as a Derived class. The process of deriving such a class is Derived class.
2. Abstraction: Abstraction is creating models or classes of some broad concept. Abstraction can be achieved through Inheritance or even Composition.
3. Encapsulation: Encapsulation is a collection of functions of a class and object. The “Food” class is an encapsulated form. It is achieved by specifying which class can use which members (private, public, protected) of an object.
4. Polymorphism: Polymorphism means existing in different forms. Inheritance is an example of Polymorphism. A base class exists in different forms as derived classes. Operator overloading is an example of Polymorphism in which an operator can be applied in different situations.
Q4) What is the concept of DISPOSE method?
DISPOSE method belongs to IDisposable interface. It is used to free unmanaged resources like files, network connection etc. It manages and handles this by an instance of the class that implements this interface. Dispose methods must be called explicitly and hence the any object using IDisposable must also implement finalizer to free resources in situations wherein Dispose is not called. Multiple calls to dispose method must be ignored when called once. The objects disposable methods must be called in the order of containment.
Q5) What is a CLR?
The Common Language Runtime (CLR) is a core component of .NET framework. It is Microsoft’s implementation of the Common Language Infrastructure (CLI) standard, which defines an execution environment for program code. In the CLR, code is expressed in a form of bytecode called the Common Intermediate Language (CIL) . Developers using the CLR write code in a language such as C# or VB.NET. At compile time, the .NET compiler converts such code into CIL code. At runtime, the CLR’s just-in-time compiler converts the CIL code into code native to the operating system. Alternatively, the CIL code can be compiled to native code in a separate step prior to runtime by using the Native Image Generator (NGEN) . This speeds up all later runs of the software as the CIL-to-native compilation is no longer necessary.
During the execution of the program, the Common Language Runtime (CLR) manages memory, Thread execution, Garbage Collection (GC) , Exception Handling, Common Type System (CTS) , code safety verifications, and other system services. The Common Language Runtime (CLR) environment is also referred to as a managed environment, because during the execution of a program it also controls the interaction with the Operating System.
Q6) What is CTS?
CTS stands for Common Type System. The CTS makes available a common set of data types so that compiled code of one language could easily interoperate with compiled code of another language by understanding each others’ data types. If two languages (c# or vb.net or j# or vc++) want to communicate with each other, they have to convert into some common type (i.e. in COMMON LANGUAGE RUNTIME) . In C# we use int which is converted to Int32 of CLR to communicate with vb.net which uses Integer or vice versa.
Q7) What is a CLS (Common Language Specification)?
CLS is a specification that defines the rules to support language integration. This is done in such a way, that programs written in any language (.NET compliant) can communicate with one another. This also can take full advantage of inheritance, polymorphism, exceptions, and other features. This is a subset of the CTS, which all .NET languages are expected to support.
Q8) Difference between Abstract Classes and Interfaces.
Following are the differences between Abstract Classes and Interfaces:
  1. When a derived class is inherited from an Abstract class, no other class can be extended then. Interface can be used in any scenario.
  2. Abstract class contains abstract method, i.e. actual implementation logic. On the other hand, interfaces have no implementation logic.
  3. Every method in an interface must be abstract. This is not necessary in case of abstract classes.
Q9) What is an Assembly?
In the .NET framework, an assembly is a partially compiled code library for use in deployment, versioning and security. There are two types: process assemblies (EXE) and library assemblies (DLL). A process assembly represents a process which will use classes defined in library assemblies. .NET assemblies contain code in CIL, which is usually generated from a CLI language, and then compiled into machine language at runtime by the CLR just-in-time compiler.
An assembly can consist of one or more files. Code files are called modules. An assembly can contain more than one code module and since it is possible to use different languages to create code modules it is technically possible to use several different languages to create an assembly. Visual Studio however does not support using different languages in one assembly.
Q10) What are the various objects in Dataset?
The DataSet class exists in the System.Data namespace.
The Classes contained in the DataSet class are:
  1. DataTable
  2. DataColumn
  3. DataRow
  4. Constraint
  5. DataRelation
Q11) What is a NameSpace?
Namespace is a group of classes, structures, interfaces, enumerations, and delegates, organized in a logical hierarchy by function, that enable you to access the core functionality you need in your applications.
Namespaces are the way that .NET avoids name clashes between classes. A Namespace is no more than a grouping of data types, but it has the effect that the names of all data types within a namespace automatically get prefixed with the name of the namespace. It is also possible to nest namespaces within each other.
Q12) What is the difference between NameSpace and Assembly?
A Namespace is a logical naming scheme for types in which a simple type name, such as MyType, is preceded with a dot-separated hierarchical name. Such a naming scheme is completely under control of the developer. The .NET Framework uses a hierarchical naming scheme for grouping types into logical categories of related functionality, such as the ASP.NET application framework, or remoting functionality. Design tools can make use of namespaces to make it easier for developers to browse and reference types in their code.
The concept of a namespace is not related to that of an Assembly. A single assembly may contain types whose hierarchical names have different namespace roots, and a logical namespace root may span multiple assemblies. In the .NET Framework, a Namespace is a logical design-time naming convenience, whereas an Assembly establishes the name scope for types at run time.