Replace If With Polymorphism With AutoFac DI Container

Abstract

As the title specifies, we will be replacing the conditional If and Switch statement with the help of polymorphism using DI container and will talk about the benefits of doing the same in this article. OOPs provides us with pretty great features which we are aware of theoretically but never implemented practically. Polymorphism is one of the main features provided by Object-Oriented Languages which, in turn, implies that a parent class can have more than one behavior and can point toward its child classes at runtime. If you want to learn more about OOPS features, you can go through the below blog which talks about oops and other features.

There are tons and tons of articles you can read.

Problem statement

I have been using dynamic Polymorphism where parent class can point towards child class and call the child method at runtime and solving the problem that way. But I found I can also use it to replace our Switch and if statement with the help of Polymorphism. I was aware of this concept when more technically sound people talk about this topic but the implementation is not so concrete and nor are  practical demos easy to find onthe internet. So let’s try to solve this problem with a practical use case and how we can avoid using Switch and if statement via Polymorphism. 

“Let’s get started”

I wish I was aware of the concept  before or that someone would have told me to do it this way. Fellas, it’s still in production but I have not yet replaced it as Client requirements have been frozen. So in one of our user stories, there was a requirement of saving FTP details of the customer and using these ftp details for File Processing etc. I am talking about this requirement on the overall focus on the FTP details part because there is where actual if else problem exists. So the requirement says Client wants support for FTP and SFTP which logs in to the application and will save the FTP details and if there is no permission of reading and writing we should tell the user at that time only.

As a passionate developer, I started working on this story and created a simple use case and short diagram without using polymorphism allowing him to save the FTP or SFTP details.

So I created a ENUM to handle the problem as shown below,

  1. public enum EFtpTypes  
  2.     {  
  3.         FTP=1,  
  4.         SFTP=2  
  5.     }  

Here I have both the two supported FTP protocols.

I have my services function ready for these two protocols separately with the two separate interfaces.

So my IFTP interface contains the following method and other methods which I am assuming are not required for this article.

  1. public interface IFTP  
  2.     {  
  3. bool IsSFTPLoginFileCreationSuccessful(string host, string ftpPort, string ftpUsername, string ftpPassword, string folder);  
  4. }  

Now the implementation Class FTPManager to manage FTP things:

  1. public class FtpManager : IFTP  
  2.     {  
  3.   public bool IsFtpLoginFileCreationSuccessful(string host, string ftpUsername, string ftpPassword, string folder)  
  4.         {  
  5.   
  6.             var folders = string.IsNullOrEmpty(folder) ? new string[] { "" } : folder.Split('/');  
  7.             StringBuilder directoryMaker = new StringBuilder("/");  
  8.             for (int i = 0; i < folders.Length; i++)  
  9.             {  
  10.   
  11.                 if (i >= 1) directoryMaker.Append(folders[i - 1] + "/");  
  12.                 host = host + directoryMaker.ToString();  
  13.                 FtpWebRequest request;  
  14.                 if (host.StartsWith("ftp") && !host.StartsWith("ftps"))  
  15.                 {  
  16.                     request = (FtpWebRequest)WebRequest.Create(new Uri(host));  
  17.                 }  
  18.                 else  
  19.                 {  
  20.                     host = "ftp://" + host;  
  21.                     request = (FtpWebRequest)WebRequest.Create(new Uri(host));  
  22.                 }  
  23.                 request.Method = WebRequestMethods.Ftp.ListDirectory;  
  24.                 request.Credentials = new NetworkCredential(ftpUsername, ftpPassword);  
  25.                 request.KeepAlive = false;  
  26.         var response = (FtpWebResponse)request.GetResponse();  
  27.                 if (!(response.StatusCode == FtpStatusCode.CommandOK || response.StatusCode == FtpStatusCode.FileActionOK || response.StatusCode ==                   FtpStatusCode.DataAlreadyOpen || response.StatusCode == FtpStatusCode.OpeningData)) return false;  
  28.                 Stream responseStream = response.GetResponseStream();  
  29.                 StreamReader reader = new StreamReader(responseStream);  
  30.                 string names = reader.ReadToEnd();  
  31.                 var Directories = names.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries).ToList();  
  32.                 if (Directories.Where(x => x.ToString().ToLower() == folders[i].Trim().ToLower()).Any())  
  33.                 {  
  34.                     if (i == folders.Length - 1)  
  35.                     {  
  36.                         CreateFile(request, folders[i], ftpUsername, ftpPassword);  
  37.                         directoryMaker.Append(folders[i]);  
  38.                         host = host + folders[i];  
  39.                         Delete(request, folder, host, ftpUsername, ftpPassword);  
  40.                     }  
  41.                 }  
  42.                 else  
  43.                 {  
  44.                     if (!string.IsNullOrEmpty(folder)) CreateDirectory(request, folders[i], host, ftpUsername, ftpPassword);  
  45.                     if (i == folders.Length - 1)  
  46.                     {  
  47.                         CreateFile(request, folders[i], ftpUsername, ftpPassword);  
  48.                         if (!string.IsNullOrEmpty(folder)) directoryMaker.Append(folders[i]);  
  49.                         if (!string.IsNullOrEmpty(folder)) host = host + folders[i];  
  50.                         Delete(request, folder, host, ftpUsername, ftpPassword);  
  51.                    }  
  52.                 }  
  53.             }  
  54.   
  55.             return true;  
  56.   
  57.         }  
  58.   
  59.   
  60. public bool CreateFile(WebRequest request, string folder, string userName, string password)  
  61.         {  
  62.             try  
  63.             {  
  64.                 int buffLength = 2048;  
  65.                 byte[] buff = new byte[buffLength];  
  66.                 byte[] bytes = Encoding.UTF8.GetBytes("Test Export");  
  67.                 request = (FtpWebRequest)FtpWebRequest.Create(new Uri(request.RequestUri + "/" + folder + "/" + "Sample.txt"));  
  68.                 request.Credentials = new NetworkCredential(userName, password);  
  69.                 request.Method = WebRequestMethods.Ftp.UploadFile;  
  70.                 request.ContentLength = bytes.Length;  
  71.                 Stream requestStream = request.GetRequestStream();  
  72.                 requestStream.Write(bytes, 0, bytes.Length);  
  73.                 requestStream.Close();                
  74.                 FtpWebResponse response = (FtpWebResponse)request.GetResponse();  
  75.                 return true;  
  76.             }  
  77.             catch (Exception)  
  78.             {  
  79.                 throw;  
  80.             }  
  81.   
  82.         }  
  83.   
  84. private bool Delete(WebRequest request, string folder, string host, string userName, string password)  
  85.         {  
  86.             try  
  87.             {  
  88.                 if (host.StartsWith("ftp") && !host.StartsWith("ftps"))  
  89.                 {  
  90.                     request = (FtpWebRequest)WebRequest.Create(new Uri(host + "//" + "Sample.txt"));  
  91.                 }  
  92.                 else  
  93.                 {  
  94.                     host = "ftp://" + host;  
  95.                     request = (FtpWebRequest)WebRequest.Create(new Uri(host + "//" + "Sample.txt"));  
  96.                 }     
  97.   request.Method = WebRequestMethods.Ftp.DeleteFile;  
  98.                 request.Credentials = new NetworkCredential(userName, password);  
  99.                 FtpWebResponse response = (FtpWebResponse)request.GetResponse();  
  100.                 return true;  
  101.             }  
  102.             catch (Exception ex)  
  103.             {  
  104.                 throw;  
  105.             }  
  106.   
  107.         }  
  108. private bool CreateDirectory(WebRequest request, string folder, string Host, string userName, string password)  
  109.         {  
  110.             try  
  111.             {  
  112.                 var getFolders = folder.Split('/');  
  113.                 StringBuilder directoriesToBeCreated = new StringBuilder("/");  
  114.                 for (int i = 0; i < getFolders.Length; i++)  
  115.                 {  
  116.                     directoriesToBeCreated.Append(getFolders[i] + "/");  
  117.                     if (Host.StartsWith("ftp") && !Host.StartsWith("ftps"))  
  118.                     {  
  119.                         request = (FtpWebRequest)WebRequest.Create(new Uri(Host + directoriesToBeCreated.ToString()));  
  120.                     }  
  121.                     else  
  122.                     {  
  123.                         Host = "ftp://" + Host;  
  124.                         request = (FtpWebRequest)WebRequest.Create(new Uri(Host + directoriesToBeCreated.ToString()));  
  125.                     }  
  126.                     // request = WebRequest.Create(new Uri("ftp://" + Host + directoriesToBeCreated.ToString()));  
  127.                     request.Credentials = new NetworkCredential(userName, password);  
  128.                     request.Method = WebRequestMethods.Ftp.MakeDirectory;  
  129.                     FtpWebResponse responses = (FtpWebResponse)request.GetResponse();  
  130.   
  131.                 }  
  132.                 return true;  
  133.             }  
  134.             catch (Exception ex)  
  135.             {  
  136.                 throw ex;  
  137.             }  
  138. }  

So this API is totally responsible for creating and checking whether the user has rights to the FTP server or not.

Now my SFTP service comes into the picture.

  1. public class SftpManager: ISFTP  
  2.     {  
  3.         public bool IsSFTPLoginFileCreationSuccessful(string host, string ftpPort, string ftpUsername, string ftpPassword, string folder)  
  4.         {  
  5.             try  
  6.             {  
  7.                 var folders = string.IsNullOrEmpty(folder) ? new string[] { "" } : folder.Split('/');  
  8.                 StringBuilder directoryMaker = new StringBuilder("");  
  9.                 int defaultSFtpPort = 115;  
  10.                 int port = (Convert.ToInt32(ftpPort) == 0) ? defaultSFtpPort : Convert.ToInt32(ftpPort);  
  11.                 using (var ftpClient = new SftpClient(host, port, ftpUsername, ftpPassword))  
  12.                 {  
  13.                     ftpClient.Connect();  
  14.                     for (int i = 0; i < folders.Length; i++)  
  15.                     {  
  16.                         var directories = ftpClient.ListDirectory(directoryMaker.ToString());  
  17.                         List<string> lstDirectory = new List<string>();  
  18.                         foreach (var directory in directories)  
  19.                         {  
  20.                             lstDirectory.Add(directory.Name);  
  21.                         }  
  22.                         if (lstDirectory.Where(x => x.ToString().ToLower() == folders[i].ToLower()).Any())  
  23.                         {  
  24.                             directoryMaker.Append(folders[i] + "/");  
  25.   
  26.                             if (i == folders.Length - 1)  
  27.                             {  
  28.                                 UploadFileAndDeleteFromSFTPServer(directoryMaker, ftpClient);  
  29.                             }  
  30.   
  31.                         }  
  32.                         else  
  33.                         {  
  34.                             if (!string.IsNullOrEmpty(folder)) directoryMaker.Append(folders[i] + "/");  
  35.                             if (!string.IsNullOrEmpty(folder)) ftpClient.CreateDirectory(directoryMaker.ToString());  
  36.                             if (i == folders.Length - 1)  
  37.                             {  
  38.                                 UploadFileAndDeleteFromSFTPServer(directoryMaker, ftpClient);  
  39.                             }  
  40.                         }  
  41.                     }  
  42.                     ftpClient.Disconnect();  
  43.                 }  
  44.                 return true;  
  45.   
  46.             }  
  47.   
  48.             catch (Exception EX)  
  49.             {  
  50.                 throw;  
  51.             }  
  52.         }  
  53.   
  54.         private void UploadFileAndDeleteFromSFTPServer(StringBuilder directoryMaker, SftpClient ftpClient)  
  55.         {  
  56.             if (!string.IsNullOrEmpty(directoryMaker.ToString())) ftpClient.ChangeDirectory(directoryMaker.ToString());  
  57.             using (Stream s = GenerateStreamFromString("TestFile"))  
  58.             {  
  59.                 ftpClient.BufferSize = 4 * 1024;  
  60.                 ftpClient.UploadFile(s, "Sample.txt");  
  61.             }  
  62.             ftpClient.Delete("Sample.txt");  
  63.         }  
  64.   
  65.         private static Stream GenerateStreamFromString(string s)  
  66.         {  
  67.             MemoryStream stream = new MemoryStream();  
  68.             StreamWriter writer = new StreamWriter(stream);  
  69.             writer.Write(s);  
  70.             writer.Flush();  
  71.             stream.Position = 0;  
  72.             return stream;  
  73.   
  74.   
  75.         }  
  76.     }  

I have the below dummy UI which shows User Interface to enter FTP details,

OOP

It’s a simple UI which I have created for demonstration purposes. FTP Type 1 here means normal FTP and 2 stands for SFTP. Just for demonstration purposes, I have left this like 1,2  andthis should be in radio button in the appropriate UI.

Controller code to save the FTP Details entered by User.

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6. using WebApplication1.Models;  
  7. using WebInterfaces;  
  8.   
  9. namespace WebApplication1.Controllers  
  10. {  
  11.     public class FileProcessingController : Controller  
  12.     {  
  13.         private readonly IFTP _ftpservice;  
  14.         private readonly ISFTP _sftpservice;  
  15.         public FileProcessingController(IFTP ftpservice, ISFTP sftpservice)  
  16.         {  
  17.             _ftpservice = ftpservice;  
  18.             _sftpservice = sftpservice;  
  19.   
  20.         }  
  21.   
  22.   
  23.         // GET: FileProcessing  
  24.         public ActionResult Index()  
  25.         {  
  26.             return View("FTPDetails",new FtpDetailsViewModels());  
  27.         }  
  28.   
  29.         [HttpPost]  
  30.         public ActionResult UpdateSetting(FtpDetailsViewModels ftpDetails)  
  31.         {  
  32.   
  33.             if (ModelState.IsValid)  
  34.             {  
  35.                 try  
  36.                 {  
  37.   
  38.                     if (ftpDetails.FtpType.Equals((int)EFtpTypes.FTP))  
  39.                     {  
  40.                         if (!_ftpservice.IsFtpLoginFileCreationSuccessful(ftpDetails.FtpHost.Trim(), ftpDetails.FtpUserName, ftpDetails.FtpPassword.Trim(), ftpDetails.Directory)) ModelState.AddModelError("FTPDetail.FtpHost""Invalid FTP Details");  
  41.                     }  
  42.                     else if (ftpDetails.FtpType.Equals((int)EFtpTypes.SFTP))  
  43.                     {  
  44.                         _sftpservice.IsSFTPLoginFileCreationSuccessful(ftpDetails.FtpHost.Trim(), ftpDetails.FtpPort.Trim(), ftpDetails.FtpUserName.Trim(), ftpDetails.FtpPassword.Trim(), ftpDetails.Directory.Trim());  
  45.   
  46.                     }  
  47.   
  48.                 }  
  49.                 catch (Exception ex)  
  50.                 {  
  51.   
  52.                     ModelState.AddModelError("FTPDetail.FtpHost", ex.Message);  
  53.   
  54.                 }  
  55.   
  56.                 return View("FTPDetails", ftpDetails);  
  57.             }  
  58.             else  
  59.             {  
  60.                 return View("FTPDetails", ftpDetails);  
  61.             }  
  62.               
  63.   
  64.             //save ftp details in db with the help of Repository  
  65.         }  
  66.   
  67.     }  
  68. }  

I have used Constructor Injection DI to get all the services instance like FTPManager, SFTPManager which otherwise I would have to create based on selected ftp type by User.

So this design when I started was working fine and I was happy that I was done with this user story. But as we all know that, 

““The Only Thing That Is Constant Is Change -”

So the client tested the User Story, it worked great and does all the functionality and then they came up and said we want support for FTPS as FTP over SSL. One of our clients uses the FTPS. So I started it again and created one more enum with 3 which stands for FTPS and then there was one more else if condition in Controller for FTPS. 

Problems

  1. The Old code has to be changed again in order to handle new ftp protocol.
    1. if (ftpDetails.FtpType.Equals((int)EFtpTypes.FTP))  
    2. {  
    3.     if (!_ftpservice.IsFtpLoginFileCreationSuccessful(ftpDetails.FtpHost.Trim(), ftpDetails.FtpUserName, ftpDetails.FtpPassword.Trim(), ftpDetails.Directory)) ModelState.AddModelError("FTPDetail.FtpHost""Invalid FTP Details");  
    4. }  
    5. else if (ftpDetails.FtpType.Equals((int)EFtpTypes.SFTP))  
    6. {  
    7.     _sftpservice.IsSFTPLoginFileCreationSuccessful(ftpDetails.FtpHost.Trim(), ftpDetails.FtpPort.Trim(), ftpDetails.FtpUserName.Trim(), ftpDetails.FtpPassword.Trim(), ftpDetails.Directory.Trim());  
    8.   
    If a new network protocol is added, we have to add another else if statement to satisfy the requirement.
  1. The services and web project has to be deployed again for the new change.
  2. Prone to error because this change will force me to test FTP and SFTP which are totally independent of FTPS,

    OOP

Source: Google

Solution - Replace If with Polymorphism Refactoring

So when I think of Polymorphism Dynamic Polymorphism comes into my mind; i.e. parent class can call its child classes at run time; i.e. parent class has more than one form. So with respect to our User story the Dynamic Polymorphism will look like as shown below:

OOP

So now, I have an Abstract Class named NetworkProtocol which has abstract method IsFtpLoginFileCreationSuccessful or other methods you want to other protocol to implement. Now let’s get started with the new design and learn how it helps us in removing unnecessary if else conditions. 

Abstract class 

  1. public abstract class FileTransferProtocol:IProtocol  
  2.     {  
  3.        public abstract bool IsFtpLoginFileCreationSuccessful(string host, string ftpPort, string ftpUsername, string ftpPassword, string folder);  
  4.     }  

Child Class which implement Network Protocol

New class FTPS that is to be supported now as per the new change.

  1. public class FTPS : FileTransferProtocol  
  2.   {  
  3.       private FtpClient _client;  
  4.       private int _ftpReadTimeout = 0;  
  5.   
  6.       public object ConfigurationManager { get; private set; }  
  7.   
  8.       private void Connect(string Username, string Password, string HostName)  
  9.       {  
  10.           if (string.IsNullOrEmpty(Username)) throw new ArgumentNullException();  
  11.           if (string.IsNullOrEmpty(Password)) throw new ArgumentNullException();  
  12.           if (string.IsNullOrEmpty(HostName)) throw new ArgumentNullException();  
  13.   
  14.           _client = new FtpClient(HostName);  
  15.           _client.Credentials = new NetworkCredential(Username, Password);  
  16.           _client.Connect();  
  17.       }  
  18.   
  19.       private void CreateSetDirectory(string DirectoryName)  
  20.       {  
  21.           if (string.IsNullOrEmpty(DirectoryName)) throw new ArgumentNullException();  
  22.           _client.CreateDirectory(DirectoryName);  
  23.           _client.SetWorkingDirectory(DirectoryName);  
  24.       }  
  25.   
  26.       private void Upload(byte[] data, string FileName)  
  27.       {  
  28.           _client.Upload(data, FileName);  
  29.       }  
  30.   
  31.   
  32.       public void CreateFile(string UserName, string Password, string HostName, string FileName, byte[] data, string Directory)  
  33.       {  
  34.           Connect(UserName, Password, HostName);  
  35.           if (!string.IsNullOrEmpty(Directory)) CreateSetDirectory(Directory);  
  36.           Upload(data, FileName);  
  37.           Disconnect();  
  38.       }  
  39.   
  40.       public void DeleteFile(string FileName)  
  41.       {  
  42.           _client.DeleteFile(FileName);  
  43.       }  
  44.   
  45.       public string ReadFile(string UserName, string Password, string HostName, string FileName, string Directory)  
  46.       {  
  47.           Connect(UserName, Password, HostName);  
  48.           string filePath = Directory + "/" + FileName;  
  49.   
  50.           var _ftpStream = _client.OpenRead(filePath);  
  51.           using (var reader = new StreamReader(_ftpStream))  
  52.           {  
  53.               var Output = reader.ReadToEnd();  
  54.               Disconnect();  
  55.               return Output;  
  56.   
  57.           }  
  58.   
  59.       }  
  60.   
  61.       private void Disconnect()  
  62.       {  
  63.           _client.Disconnect();  
  64.           _client.Dispose();  
  65.       }  
  66.   
  67.       public override bool IsFtpLoginFileCreationSuccessful(string host, string ftpPort, string ftpUsername, string ftpPassword, string folder)  
  68.       {  
  69.           this.Connect(ftpUsername, ftpPassword, host);  
  70.           if (!string.IsNullOrEmpty(folder)) this.CreateSetDirectory(folder);  
  71.           byte[] bytes = Encoding.UTF8.GetBytes("Test");  
  72.           this.Upload(bytes, "sample.txt");  
  73.           this.DeleteFile("sample.txt");  
  74.           this.Disconnect();  
  75.           return true;  
  76.       }  
  77.   }  
  78.   
  79.   
  80. blic class SFTP : FileTransferProtocol  
  81.   {  
  82.       public override bool IsFtpLoginFileCreationSuccessful( string host, string ftpPort, string ftpUsername, string ftpPassword, string folder)  
  83.       {  
  84.           try  
  85.           {  
  86.               var folders = string.IsNullOrEmpty(folder) ? new string[] { "" } : folder.Split('/');  
  87.               StringBuilder directoryMaker = new StringBuilder("");  
  88.               int defaultSFtpPort = 115;  
  89.               int port = (Convert.ToInt32(ftpPort) == 0) ? defaultSFtpPort : Convert.ToInt32(ftpPort);  
  90.               using (var ftpClient = new SftpClient(host, port, ftpUsername, ftpPassword))  
  91.               {  
  92.                   ftpClient.Connect();  
  93.                   for (int i = 0; i < folders.Length; i++)  
  94.                   {  
  95.                       var directories = ftpClient.ListDirectory(directoryMaker.ToString());  
  96.                       List<string> lstDirectory = new List<string>();  
  97.                       foreach (var directory in directories)  
  98.                       {  
  99.                           lstDirectory.Add(directory.Name);  
  100.                       }  
  101.                       if (lstDirectory.Where(x => x.ToString().ToLower() == folders[i].ToLower()).Any())  
  102.                       {  
  103.                           directoryMaker.Append(folders[i] + "/");  
  104.   
  105.                           if (i == folders.Length - 1)  
  106.                           {  
  107.                               UploadFileAndDeleteFromSFTPServer(directoryMaker, ftpClient);  
  108.                           }  
  109.   
  110.                       }  
  111.                       else  
  112.                       {  
  113.                           if (!string.IsNullOrEmpty(folder)) directoryMaker.Append(folders[i] + "/");  
  114.                           if (!string.IsNullOrEmpty(folder)) ftpClient.CreateDirectory(directoryMaker.ToString());  
  115.                           if (i == folders.Length - 1)  
  116.                           {  
  117.                               UploadFileAndDeleteFromSFTPServer(directoryMaker, ftpClient);  
  118.                           }  
  119.                       }  
  120.                   }  
  121.                   ftpClient.Disconnect();  
  122.               }  
  123.               return true;  
  124.   
  125.           }  
  126.   
  127.           catch (Exception EX)  
  128.           {  
  129.               throw;  
  130.           }  
  131.       }  
  132.       private void UploadFileAndDeleteFromSFTPServer(StringBuilder directoryMaker, SftpClient ftpClient)  
  133.       {  
  134.           if (!string.IsNullOrEmpty(directoryMaker.ToString())) ftpClient.ChangeDirectory(directoryMaker.ToString());  
  135.           using (Stream s = GenerateStreamFromString("TestFile"))  
  136.           {  
  137.               ftpClient.BufferSize = 4 * 1024;  
  138.               ftpClient.UploadFile(s, "Sample.txt");  
  139.           }  
  140.           ftpClient.Delete("Sample.txt");  
  141.       }  
  142.   
  143.       private static Stream GenerateStreamFromString(string s)  
  144.       {  
  145.           MemoryStream stream = new MemoryStream();  
  146.           StreamWriter writer = new StreamWriter(stream);  
  147.           writer.Write(s);  
  148.           writer.Flush();  
  149.           stream.Position = 0;  
  150.           return stream;  
  151.   
  152.   
  153.       }  
  154.   }  
  155.   
  156. blic class FTP : FileTransferProtocol  
  157.   {  
  158.       public override bool IsFtpLoginFileCreationSuccessful(string host,string ftpPort,  string ftpUsername, string ftpPassword, string folder)  
  159.       {  
  160.           var folders = string.IsNullOrEmpty(folder) ? new string[] { "" } : folder.Split('/');  
  161.           StringBuilder directoryMaker = new StringBuilder("/");  
  162.           for (int i = 0; i < folders.Length; i++)  
  163.           {  
  164.   
  165.               if (i >= 1) directoryMaker.Append(folders[i - 1] + "/");  
  166.               host = host + directoryMaker.ToString();  
  167.               FtpWebRequest request;  
  168.               if (host.StartsWith("ftp") && !host.StartsWith("ftps"))  
  169.               {  
  170.                   request = (FtpWebRequest)WebRequest.Create(new Uri(host));  
  171.               }  
  172.               else  
  173.               {  
  174.                   host = "ftp://" + host;  
  175.                   request = (FtpWebRequest)WebRequest.Create(new Uri(host));  
  176.               }  
  177.               request.Method = WebRequestMethods.Ftp.ListDirectory;  
  178.               request.Credentials = new NetworkCredential(ftpUsername, ftpPassword);  
  179.               request.KeepAlive = false;  
  180.               var response = (FtpWebResponse)request.GetResponse();  
  181.               if (!(response.StatusCode == FtpStatusCode.CommandOK || response.StatusCode == FtpStatusCode.FileActionOK || response.StatusCode == FtpStatusCode.DataAlreadyOpen || response.StatusCode == FtpStatusCode.OpeningData)) return false;  
  182.               Stream responseStream = response.GetResponseStream();  
  183.               StreamReader reader = new StreamReader(responseStream);  
  184.               string names = reader.ReadToEnd();  
  185.               var Directories = names.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries).ToList();  
  186.               if (Directories.Where(x => x.ToString().ToLower() == folders[i].Trim().ToLower()).Any())  
  187.               {  
  188.                   if (i == folders.Length - 1)  
  189.                   {  
  190.                       CreateFile(request, folders[i], ftpUsername, ftpPassword);  
  191.                       directoryMaker.Append(folders[i]);  
  192.                       host = host + folders[i];  
  193.                       Delete(request, folder, host, ftpUsername, ftpPassword);  
  194.   
  195.                   }  
  196.   
  197.               }  
  198.               else  
  199.               {  
  200.                   if (!string.IsNullOrEmpty(folder)) CreateDirectory(request, folders[i], host, ftpUsername, ftpPassword);  
  201.                   if (i == folders.Length - 1)  
  202.                   {  
  203.                       CreateFile(request, folders[i], ftpUsername, ftpPassword);  
  204.                       if (!string.IsNullOrEmpty(folder)) directoryMaker.Append(folders[i]);  
  205.                       if (!string.IsNullOrEmpty(folder)) host = host + folders[i];  
  206.                       Delete(request, folder, host, ftpUsername, ftpPassword);  
  207.                   }  
  208.               }  
  209.           }  
  210.   
  211.           return true;  
  212.       }  
  213.   
  214.       private bool CreateFile(WebRequest request, string folder, string userName, string password)  
  215.       {  
  216.           try  
  217.           {  
  218.               int buffLength = 2048;  
  219.               byte[] buff = new byte[buffLength];  
  220.               byte[] bytes = Encoding.UTF8.GetBytes("Test Export");  
  221.               request = (FtpWebRequest)FtpWebRequest.Create(new Uri(request.RequestUri + "/" + folder + "/" + "Sample.txt"));  
  222.               request.Credentials = new NetworkCredential(userName, password);  
  223.               request.Method = WebRequestMethods.Ftp.UploadFile;  
  224.               request.ContentLength = bytes.Length;  
  225.               Stream requestStream = request.GetRequestStream();  
  226.               requestStream.Write(bytes, 0, bytes.Length);  
  227.               requestStream.Close();  
  228.               FtpWebResponse response = (FtpWebResponse)request.GetResponse();  
  229.               return true;  
  230.           }  
  231.           catch (Exception)  
  232.           {  
  233.               throw;  
  234.           }  
  235.   
  236.       }  
  237.       private bool CreateDirectory(WebRequest request, string folder, string Host, string userName, string password)  
  238.       {  
  239.           try  
  240.           {  
  241.               var getFolders = folder.Split('/');  
  242.               StringBuilder directoriesToBeCreated = new StringBuilder("/");  
  243.               for (int i = 0; i < getFolders.Length; i++)  
  244.               {  
  245.                   directoriesToBeCreated.Append(getFolders[i] + "/");  
  246.                   if (Host.StartsWith("ftp") && !Host.StartsWith("ftps"))  
  247.                   {  
  248.                       request = (FtpWebRequest)WebRequest.Create(new Uri(Host + directoriesToBeCreated.ToString()));  
  249.                   }  
  250.                   else  
  251.                   {  
  252.                       Host = "ftp://" + Host;  
  253.                       request = (FtpWebRequest)WebRequest.Create(new Uri(Host + directoriesToBeCreated.ToString()));  
  254.                   }  
  255.                   // request = WebRequest.Create(new Uri("ftp://" + Host + directoriesToBeCreated.ToString()));  
  256.                   request.Credentials = new NetworkCredential(userName, password);  
  257.                   request.Method = WebRequestMethods.Ftp.MakeDirectory;  
  258.                   FtpWebResponse responses = (FtpWebResponse)request.GetResponse();  
  259.   
  260.               }  
  261.               return true;  
  262.           }  
  263.           catch (Exception ex)  
  264.           {  
  265.               throw ex;  
  266.           }  
  267.       }  
  268.       private bool Delete(WebRequest request, string folder, string host, string userName, string password)  
  269.       {  
  270.           try  
  271.           {  
  272.               if (host.StartsWith("ftp") && !host.StartsWith("ftps"))  
  273.               {  
  274.                   request = (FtpWebRequest)WebRequest.Create(new Uri(host + "//" + "Sample.txt"));  
  275.               }  
  276.               else  
  277.               {  
  278.                   host = "ftp://" + host;  
  279.                   request = (FtpWebRequest)WebRequest.Create(new Uri(host + "//" + "Sample.txt"));  
  280.               }  
  281.               request.Method = WebRequestMethods.Ftp.DeleteFile;  
  282.               request.Credentials = new NetworkCredential(userName, password);  
  283.               FtpWebResponse response = (FtpWebResponse)request.GetResponse();  
  284.               return true;  
  285.           }  
  286.           catch (Exception ex)  
  287.           {  
  288.               throw;  
  289.           }  
  290.   
  291.       }  
  292.   }  

So now in the  future when the client comes and says we want another ftp to be supported we will create a new class and inherit our base class NetworkProtocol and implement the same to use in our application.

This is just the first phase of design. Now, the important thing is pending, that is, getting the instance of a class based on selected Network protocol in UI by which we will be able to call correct Protocol and check if username and password are correct or not.

As I mentioned I will be using Dependency injection container to get the appropriate instance based on type of Protocol; i.e. in DB we have set protocol details as shown below,

ID Protocol
1 FTP
2 SFTP
3 FTPS

I will not be explaining Dependency injection thoroughly here. But fwhenever we create an instance of a class in our controller our controller is dependent on that class if anything on that class changes, the compiler has to go through all desired changes and also has to recompile the controller due to change in Class itself. So in order to remove the use of new in our classes, we inject the required instance via Interface constructor.

For IOC (inversion of control) container which is responsible for giving me the instance, I am using AutoFac. I will configure the above dependency as shown below in di configuration.

  1. public static IContainer Build()  
  2.         {  
  3.             var builder = new ContainerBuilder();  
  4.             builder.RegisterControllers(Assembly.GetExecutingAssembly());  
  5.             //builder.RegisterType<FtpManager>().As<IFTP>();  
  6.             //builder.RegisterType<SftpManager>().As<ISFTP>();  
  7.             builder.RegisterType<FileTransferProtocol>().As<IProtocol>().InstancePerLifetimeScope();  
  8.             builder.RegisterType<FTP>().Named<NetworkProtocol>("1").InstancePerLifetimeScope();  
  9.             builder.RegisterType<SFTP>().Named<NetworkProtocol>("2").InstancePerLifetimeScope();  
  10.             builder.RegisterType<FTPS>().Named<NetworkProtocol>("3").InstancePerLifetimeScope();  
  11.             Container = builder.Build();  
  12.             DependencyResolver.SetResolver(new AutofacDependencyResolver(Container));  
  13.             Registry.Container = Container;  
  14.             return Container;  
  15.         }  

So I have created named dependency with 1,2,3 which I will get in controller action method while saving these details and based on received ftp type I will get the required instance of Protocol by resolving the same with the help of DI Container. Let’s get started.

Now, in my action method, I will just resolve the instance by FTP type -- it's as simple as that.

  1. [HttpPost]  
  2.      public ActionResult UpdateSetting(FtpDetailsViewModels ftpDetails)  
  3.      {  
  4.         if (ModelState.IsValid)  
  5.          {  
  6.              try  
  7.              {  
  8.                  var reportSubject = _container.ResolveOptionalNamed<IProtocol>(ftpDetails.FtpType.ToString());  
  9.                 var status= reportSubject.IsFtpLoginFileCreationSuccessful(ftpDetails.FtpHost.Trim(),ftpDetails.FtpPort, ftpDetails.FtpUserName, ftpDetails.FtpPassword.Trim(), ftpDetails.Directory);  
  10.                  if(status)  
  11.                  {  
  12.                      saveDetails();  
  13.                  }else  
  14.                  {  
  15.                      ModelState.AddModelError("FTPDetail.FtpHost""Invalid FTP Details"); ;  
  16.                  }                 
  17.              }  
  18.              catch (Exception ex)  
  19.              {  
  20.                  ModelState.AddModelError("FTPDetail.FtpHost", ex.Message);  
  21.           }  
  22.   
  23.              return View("FTPDetails", ftpDetails);  
  24.          }  
  25.          else  
  26.          {  
  27.              return View("FTPDetails", ftpDetails);  
  28.          }  
  29.            //save ftp details in db with the help of Repository  
  30.      }  

Now when I save the detail in UI:

OOP

Now, in my controller, I can see the user entered ftp details in my Model.

OOP

Now we can see the FTPtype is 1 i.e. FTP which means the user has selected FTP protocol. Now, when we resolve the dependency, let’s see which instance we get.

OOP

We can clearly see the instance is pointing to FTP service which will call FTP service IsFtpLoginFileCreationSuccessful method to check ftp detail.

OOP

We are able to successfully check the rights and username and password for ftp protocol and the same can be done for other protocol.

Now you can clearly see there is no if else statement it’s purely a one liner to resolve the dependency. We have seen the power of Polymorphism to “Remove if with Polymorphism”

Conclusion

Here we learned how easily we can get rid of our common if else condition and make it cleaner with the help of Polymorphism. With the help of DI, we are able to decouple the controller from the service layer.

In future, if we need to support  any more protocols we have to just create a new respective protocol service and add this in DI container to register it and it will be ready to go.

I hope this article was helpful to understand RIP.


Similar Articles