Showing posts with label MVC. Show all posts
Showing posts with label MVC. Show all posts

Friday, 19 April 2019

Implementation of Dependency Injection in C#.

What is Dependency Injection?


Dependency Injection (DI) is a software design pattern that allows us to develop loosely coupled code. DI is a great way to reduce tight coupling between software components. DI also enables us to better manage future changes and other complexity in our software. The purpose of DI is to make code maintainable.

For example, Suppose your Client class needs to use two service classes, then the best you can do is to make you Client class aware of abstraction i.e. IService interface rather than implementation i.e. Service1 and Service2 classes. In this way, you can change the implementation of the IService interface at any time (and for how many times you want) without changing the client class code.



We have the following different ways to implement DI :

Constructor Injection
  • This is a widely used way to implement DI.
  • Dependency Injection is done by supplying the DEPENDENCY through the class’s constructor when creating the instance of that class.
  • The injected component can be used anywhere within the class.
  • Recommended using when the injected dependency, you are using across the class methods.
  • It addresses the most common scenario where a class requires one or more dependencies.



public interface IService {

 void Serve();

}

public class Service1 : IService {
 public void Serve() { Console.WriteLine("Service1 Called"); }
}
public class Service2 : IService {
 public void Serve() { Console.WriteLine("Service2 Called"); }
}
public class Client {
 private IService _service;
 public Client(IService service) {
 this._service = service;
 }
 public ServeMethod() { this._service.Serve(); }
}


class Program
{
 static void Main(string[] args)
 {
 //creating object
 Service1 s1 = new Service1(); 
 //passing dependency
 Client c1 = new Client(s1);
 //TO DO:
 Service2 s2 = new Service2(); 
 //passing dependency
 c1 = new Client(s2);
 //TO DO:
 }
}

The Injection happens in the constructor, bypassing the Service that implements the IService Interface. The dependencies are assembled by a "Builder" and Builder responsibilities are as follows:
  • Knowing the types of each IService
  • According to the request, feed the abstract IService to the Client

Property/Setter Injection

  • Recommended using when a class has optional dependencies, or where the implementations may need to be swapped.
  • Different logger implementations could be used in this way.
  • Does not require the creation of a new object or modifying the existing one. Without changing the object state, it could work.


public interface IService {

 void Serve();

}

public class Service1 : IService {
 public void Serve() { Console.WriteLine("Service1 Called"); }
}
public class Service2 : IService {
 public void Serve() { Console.WriteLine("Service2 Called"); }
}
public class Client {
 private IService _service;
 public IService Service {
 set { this._service = value; }
 }
 public ServeMethod() { this._service.Serve(); }
}

class Program
{
 static void Main(string[] args)
 {
 //creating object
 Service1 s1 = new Service1(); 
 Client client = new Client();
 client.Service = s1; //passing dependency
 //TO DO:
 Service2 s2 = new Service2(); 
 client.Service = s2; //passing dependency
 //TO DO:
 }
}

Method Injection
  • Inject the dependency into a single method and generally for the use of that method.
  • It could be useful, where the whole class does not need the dependency, only one method having that dependency.
  • This is the way is rarely used.

public interface IService {

 void Serve();

}

public class Service1 : IService {
 public void Serve() { Console.WriteLine("Service1 Called"); }
}
public class Service2 : IService {
 public void Serve() { Console.WriteLine("Service2 Called"); }
}
public class Client {
 private IService _service;
 public void Start(IService service) {
 service.Serve();
 }
}

class Program
{
 static void Main(string[] args)
 {
 //creating object
 Service1 s1 = new Service1(); 
 Client client = new Client(); 
 client.Start(s1); //passing dependency
 //TO DO:
 Service2 s2 = new Service2(); 
 client.Start(s2); //passing dependency
 }
}

Advantages of Dependency Injection
  • Reduces class coupling
  • Increases code reusability
  • Improves code maintainability
  • Make unit testing possible

If you want to implement DI within your ASP.NET MVC application using DI container, please does refer Dependency Injection in ASP.NET MVC5 using Unity IoC Container.

Dependency Injection in ASP.Net MVC5 using Unity Ioc Container.

What is Inversion of Control?

Inversion of Control (IoC) refers to a programming style where a framework controls the program flow with the help of Dependency Injection.

The term Inversion of Control (IoC) refers to a programming style where the flow of a program has been inverted i.e. changed from the normal way. As you have done in the example of Class A and Class B. Here, dependencies are instantiated by a framework or runtime and supplied to the desired class as needed.


Step 1: Create a new ASP.NET MVC Application


Step 2: Install Unity Container


Right click on the project and click on Manage NuGet Packages and search for Unity.mvc5. Click to install Unity. mvc5 package in ASP.NET MVC application.






Note
Make sure you are connected with internet.

When it will be installed successfully, you will find the following two references add to your project and UnityConfig.cs file in App_Start Folder at a project level, as shown below:


Step 3: Register all your components with the container as in the following screenshot;


public static class UnityConfig
    {
        public static void RegisterComponents()
        {
var container = new UnityContainer();

            // register all your components with the container here
            // it is NOT necessary to register your controllers

            // e.g. container.RegisterType<ITestService, TestService>();

            container.RegisterType<IRepositry, Repositry>();

            DependencyResolver.SetResolver(new UnityDependencyResolver(container));
        }
    }


Step 4: Add a new Folder in the project of the name Repository and add the following interface and a class in this folder:

//IRepositry.cs
public interface IRepositry
    {
        string GetName();
    }

//Repositry.cs
public class Repositry: IRepositry
    {
        public string GetName()
        {
            return "Vikash Sah";
        }
    }

Step 5: After this register UnityConfig in Global.asax,



Step 6: Finally, use it in your MVC Controller,






Thursday, 5 April 2018

Encrypt And Decrypt Connection String In Web.Config File Using Command Prompt


Encrypting Web.Config

  1. Open Command Prompt with Administrator privileges
  2. At the Command Prompt, enter: cd C:\Windows\Microsoft.NET\Framework\v4.0.30319
    This command will narrate you to the framework version folder given.
  3. In case your web Config is located in "D:\Articles\EncryptWebConfig" directory path, then enter the following to encrypt the ConnectionStringASPNET_REGIIS -pef "connectionStrings" "D:\Articles\EncryptWebConfig"
    Use Aspnet_regiis.exe tool with the –pef option and specify the application path as shown above.
    Note: The parameter "connectionStrings" is case sensitive.
  4. Once you click the enter. You will get the output as follows.


Decrypt connection string
You can always decrypt the connection string if you want, to decrypt you just need follows the commands as follows at the command prompt.
cd C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319  
Once after you did you the above command you can execute the preceding one.
ASPNET_REGIIS -PDF "connectionStrings" "F:\Visual Studio\EncryptConnectionString\EncryptConnectionString" 
The text ‘connectionString’ is case sensitive as mentioned above 
If the command is correct, you can get an output as follows.



Now if you check your Web config again, you can see the connection string has got encrypted. Have a happy coding!

Encrypt and Decrypt Connection Strings in Web.Config file in ASP.Net Using Visual Studio Command Prompt

In this article, I will provide some example to encrypt and decrypt Connection Strings in Web.Config file in ASP.Net.


The Encryption and Decryption of the Web.Config file’s ConnectionStrings section
will be performed using aspnet_regiis.exe Command Line Utility of the Visual Studio.


The plan text connection string in web.config file.
<configuration>
 <connectionStrings>
   <add name="SqlServices" connectionString="Data Source=localhost;Integrated Security=SSPI;Initial
Catalog=Northwind;" />
 </connectionStrings>
</configuration>


Encrypting the connection string in web.config file


You need to follow the following steps for encrypting the Connection Strings in the Web.Config file
1. Open Visual Studio Command Prompt
You will need to open the Visual Studio Command Prompt from the Start Menu =>
Programs => Microsoft Visual Studio 2010 => Visual Studio Tools => Visual Studio Command Prompt.
Note: You must be login as Administrator and right-click Visual Studio Command Prompt and select.
Note: In this tutorial, I am explaining the process using Microsoft Visual Studio 2015
The same process will be applicable to the other versions. The only difference will be that you
need to open Visual Studio Command Prompt from the
folder of the respective version of Visual Studio installed on your machine.


2. Encrypting the Connection String in Web.Config using aspnet_regiis.exe tool
In order to encrypt the ConnectionString section in the Web.Config file, we will need to
use the aspnet_regiis.exe tool
Parameters
Action - It notifies the action to be performed.&nbsp; In order to perform Encryption, the parameter value is -pef
Section Name - The name of the section of the Web.Config file to be encrypted.
For this case, the value will be connectionStrings
Path of the folder – Here we need to specify the path of the folder containing
the Web.Config file.
Syntax : aspnet_regiis.exe -pef "connectionStrings" "<Path of the Folder containing the Web.Config file>"
Example : aspnet_regiis.exe -pef "connectionStrings" "D:\Mudassar\Projects\MyTestWebsite"



Note: The above command will encrypt all the Connection Strings present in
the ConnectionStrings section of the Web.Config file.



Encrypted Connection String in the Web.Config file
The following screenshot shows the Encrypted Connection String in the Web.Config
file after encryption.
<configuration>
 <connectionStrings configProtectionProvider="RsaProtectedConfigurationProvider">
   <EncryptedData Type="http://www.w3.org/2001/04/xmlenc#Element"

xmlns="http://www.w3.org/2001/04/xmlenc#">
     <EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#tripledes-cbc" />
     <KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#">
       <EncryptedKey xmlns="http://www.w3.org/2001/04/xmlenc#">
         <EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#rsa-1_5" />
         <KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#">
           <KeyName>Rsa Key</KeyName>
         </KeyInfo>
         <CipherData>
           <CipherValue>ZbDTF00MYzUUW5U3w3PU0rfiAH1UKhvuLSNWPmB/YifBKne6HAWfVc3CnKVimy
P8SFyamaR5o AIAxj/xavfpox8EOYXNI+afsksiuA5huSDupCZKNuXq+VCZrdIyn6YOq+W7s3Ojlu7q9VwKco
Kurl28l2hcPvWkBk11KYB7hr0=</CipherValue>
         </CipherData>
       </EncryptedKey>
     </KeyInfo>
     <CipherData>
       <CipherValue>42IPPRUjJxCNDHEBLCAJI4/NyLpLueZSBzUXO69lVdZU8+nLpxO+opnbZNxqddyzNnbCO1
Uk2Da 3ljExkqnLIxT2zs90JAhZvJ5ljIgCipq7ZEp7zHOpvTH9fBGoZJJWhgdddOrHZsLDE9mILjlvBHDhPQrYcMHt
Y6oLIbxJq92it82iBJv0fS7v1S/o0p4hAtfky+6hXCZWSKUJHr88NDrKe2EEK3mazD2QD5Ozf/w=</CipherValue>
     </CipherData>
   </EncryptedData>
 </connectionStrings>
</configuration>


Accessing the Encrypted Connection String value in ASP.Net Code behind
ASP.Net will automatically decrypt the Connection String when it is fetched in the code behind and
hence in code behind you need to access the Connection String in the same way as you would do normally.
string ConnString = ConfigurationManager.ConnectionStrings[SqlServices
].ToString();


Decrypting the Connection String in Web.Config using aspnet_regiis.exe tool
In order to decrypt the ConnectionString section in the Web.Config file, we will need to use the same
aspnet_regiis.exe tool that was used for encryption.
Parameters
Action – It notifies the action to be performed. In order to perform Decryption, the parameter value is -pdf.
Section Name – The name of the section of the Web.Config file to be decrypted. For this case,
the value will be connectionStrings.
Path of the folder – Here we need to specify the path of the folder containing the Web.Config file.
Syntax
aspnet_regiis.exe -pdf "connectionStrings" "<Path of the Folder containing the Web.Config file>"
Example
aspnet_regiis.exe -pdf "connectionStrings" "D:\Mudassar\Projects\MyTestWebsite"


Note: The above command will decrypt all the Connection Strings present in
the ConnectionStrings section of the Web.Config file.


Sitecore Publishing Service 7.0 Installation Guide

  About the Publishing Service module The Publishing Service module is an optional replacement for the existing Sitecore publishing methods....