Wednesday, March 15, 2017

How to use C# interface

Following is a simple interface with just a one method declaration.

public interface IRobot
{
    bool ValidateRobot(string robotId);
}

Now you can write a class and then inherit it from the interface. This class needs to implement the interface. At this point we write the actual implementation of the method declared in the interface.

public class RobotProvider : IRobot
{
    public bool ValidateRobot(string robotId)
    {
        return robotId == "CorrectRobot" ? true : false;
    }
}

Finally, we can call the interface method in our main programme.

    static void Main(string[] args)
    {
        IRobot robot = new RobotProvider();
        bool robotResult = robot.ValidateRobot("CorrectRobot");
        Console.WriteLine(robotResult);
        Console.ReadKey();
    }
Result


Tuesday, March 7, 2017

C# FTP file processing helper class

 
Following class contains a few helpful methods to process files using FTP.

using System;
using System.Data.Common;
using System.IO;
using System.Linq;
using System.Net;

namespace Helper
{
    public class LogFileHelper
    {
        private readonly string _connectionType;
        private readonly string _host;
        private readonly string _port;
        private readonly string _username;
        private readonly string _password;
        private readonly string _fileLocation;
        private readonly string _processedDir;
        private readonly string _pendingDir;

        public LogFileHelper()
        {
        }

        public LogFileHelper(LogFile logFile, string pendingDir, string processedDir)
        {
            _connectionType = logFile.ConnectionType;
            _host = logFile.Host;
            _port = logFile.Port;
            _username = logFile.Username;
            _password = logFile.Password;
            _fileLocation = logFile.FileLocation;
            _pendingDir = pendingDir;
            _processedDir = processedDir;
        }

        public List<string> GetFilesFromServer()
        {
            var fileNames = new List<string>();
            WebResponse response = null;
            StreamReader reader = null;
            try
            {
                var host = string.IsNullOrEmpty(_port) ? _host : _host + ":" + _port;
                host = host + "/" + _fileLocation;
                FtpWebRequest reqFTP;
                reqFTP = (FtpWebRequest)WebRequest.Create(new Uri("ftp://" + host + "/"));
                reqFTP.UseBinary = true;
                reqFTP.Credentials = new NetworkCredential(_username, _password);
                reqFTP.Method = WebRequestMethods.Ftp.ListDirectory;
                reqFTP.Proxy = null;
                reqFTP.KeepAlive = false;
                reqFTP.UsePassive = false;
                response = reqFTP.GetResponse();
                reader = new StreamReader(response.GetResponseStream());
                string line = reader.ReadLine();
                while (line != null)
                {
                    fileNames.Add(line);
                    line = reader.ReadLine();
                }
                return fileNames;
            }
            catch (Exception ex)
            {
                if (reader != null)
                {
                    reader.Close();
                }
                if (response != null)
                {
                    response.Close();
                }
                return null;
            }
        }

        public string DownloadFTP(string fileName)
        {
            try
            {
                var host = string.IsNullOrEmpty(_port) ? _host : _host + ":" + _port;
                string uri = "ftp://" + host + "/" + _fileLocation + "/" + fileName;
                Uri serverUri = new Uri(uri);
                if (serverUri.Scheme != Uri.UriSchemeFtp)
                {
                    return null;
                }
                var reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
                reqFTP.Credentials = new NetworkCredential(_username, _password);
                reqFTP.KeepAlive = false;
                reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
                reqFTP.UseBinary = true;
                reqFTP.Proxy = null;
                reqFTP.UsePassive = false;
                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                Stream responseStream = response.GetResponseStream();
                FileStream writeStream = new FileStream(_pendingDir + "\\" + fileName, FileMode.Create);
                int Length = 2048;
                Byte[] buffer = new Byte[Length];
                int bytesRead = responseStream.Read(buffer, 0, Length);
                while (bytesRead > 0)
                {
                    writeStream.Write(buffer, 0, bytesRead);
                    bytesRead = responseStream.Read(buffer, 0, Length);
                }
                writeStream.Close();
                response.Close();
                Console.WriteLine("Download successfuly");
                return _pendingDir + "\\" + fileName;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message, "Download error");
                return null;
            }
        }

        public List<string> GetProcessedFiles(DbConnection stagingConnection)
        {
            var fileNames = new List<string>();
            using (var uow = new StagingUnitOfWork(stagingConnection))
            {
                var files = uow.SessionProcessedFileRepository.GetAll();
                if (files.Count() > 0)
                {
                    foreach (var file in files)
                    {
                        if (!fileNames.Contains(file.FileName))
                        {
                            fileNames.Add(file.FileName);
                        }
                    }
                }

            }
            return fileNames;
        }


        public List<string> GetPendingFiles()
        {
            DirectoryInfo d = new DirectoryInfo(_pendingDir);
            FileInfo[] files = d.GetFiles("*.*");
            var fileNames = new List<string>();
            foreach (FileInfo file in files)
            {
                fileNames.Add(file.Name);
            }
            return fileNames;
        }

        public bool MoveFileToProcessedDir(string fileName)
        {
            try
            {
                var from = Path.Combine(_pendingDir, fileName);
                var to = Path.Combine(_processedDir, fileName);
                File.Move(from, to);
                return true;
            }
            catch (Exception e)
            {
                return false;
            }
        }
    }
}