Tag: .Net

Download/Upload files using FTP in C#

 

 

 

 

What is FTP? 

FTP(File transfer protocol)  is a client-server protocol that relies on two communications channels between client and server: a command channel for controlling the conversation and a data channel for transmitting file content. Clients initiate conversations with servers by requesting to download a file. Using FTP, a client can upload, download, delete, rename, move and copy files on a server. A user typically needs to log on to the FTP server, although some servers make some or all of their content available without login, also known as anonymous FTP. FTP server can access by CMD in the windows environment. FileZilla is an open source freely available tool for both FTP server and client.

Ftp Service class for FTP operations

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Threading.Tasks;

namespace betechnical.FTP
{
    ///

    ///
    public class FtpService : IDisposable
    {
        #region Member declaration

        private readonly Queue<string> _downloadlist = new Queue<string>();
        private readonly NetworkCredential _networkCredential;
        private readonly object _sync = new object();
        private readonly FtpUserInfoVo _ftpUserInfo;

        #endregion

        ///

        ///     Constructor with FTP Credential
        ///
        ///
        public FtpService(FtpUserInfoVo ftpUserInfo)
        {
            _ftpUserInfo = ftpUserInfo;
            _networkCredential = new NetworkCredential(ftpUserInfo.UserName, ftpUserInfo.Password);

        }

        ///

        ///
        public string HostUrl
        {
            get { return string.Format("ftp://{0}", _ftpUserInfo.Host); }
        }

        ///

        /// 
        ///
        /// 
        public IList<string> ListDirectories(string directory)
        {
            var url = string.IsNullOrEmpty(directory) ? HostUrl : HostUrl + "/" + directory;
            var dirlist = new List<string>();
            var ftprequest = WebRequest.Create(url);
            ftprequest.Method = WebRequestMethods.Ftp.ListDirectory;
            ftprequest.Credentials = _networkCredential;
            ftprequest.Timeout = 1200000;
            using (var ftpresponse = (FtpWebResponse) ftprequest.GetResponse())
            {
                var responcestream = ftpresponse.GetResponseStream();
                if (responcestream == null) return dirlist;
                using (var streamreader = new StreamReader(responcestream))
                {
                    while (!streamreader.EndOfStream)
                    {
                        var file = streamreader.ReadLine();
                        if (file != null)
                        {
                            dirlist.Add(file);
                        }
                    }
                }
            }
            return dirlist;
        }

        ///

        /// 
        ///
        ///
        ///
        public void UploadFile(string directory, string filepath)
        {
            try
            {
                var fs = new FileStream(filepath,FileMode.Open);
                var filename = Path.GetFileName(filepath);
                var url = string.IsNullOrEmpty(directory) ? HostUrl : HostUrl + "/" + directory + "/" + filename;
                var ftprequest = WebRequest.Create(url);
                ftprequest.Method = WebRequestMethods.Ftp.UploadFile;
                ftprequest.Credentials = _networkCredential;
                ftprequest.Timeout = 1200000;
                using (var ftpstream = ftprequest.GetRequestStream())
                {
                    var buffer = new byte[fs.Length];
                    fs.Read(buffer, 0, buffer.Length);
                    fs.Close();
                    ftpstream.Write(buffer, 0, buffer.Length);
                    ftpstream.Close();
                }
            }
            catch (Exception ex)
            {

                Console.WriteLine(string.Format("Ftp Host : {0} with username : {1}",
                    _ftpUserInfo.Host, _networkCredential.UserName));
                Console.WriteLine(ex);
            }
        }

        ///

        ///
        public void DownloadFiles(string directory)
        {
            try
            {
                var url = string.IsNullOrEmpty(directory) ? HostUrl : HostUrl + "/" + directory;
                var ftprequest = WebRequest.Create(url);
                ftprequest.Method = WebRequestMethods.Ftp.ListDirectory;
                ftprequest.Credentials = _networkCredential;
                ftprequest.Timeout = 1200000;
                using (var ftpresponse = (FtpWebResponse) ftprequest.GetResponse())
                {
                    var responcestream = ftpresponse.GetResponseStream();
                  
                    if (responcestream != null)
                    {
                        using (var streamreader = new StreamReader(responcestream))
                        {
                            while (!streamreader.EndOfStream)
                            {
                                var file = streamreader.ReadLine();
                                if (file == null) continue;
                                var filename = file.Split('/').Last();
                                if (!file.Contains("."))
                                {
                                    DownloadFiles(directory + "/" + filename);
                                }
                                file = url + "/" + filename;
                                _downloadlist.Enqueue(file);
                            }
                        }
                    }
                }
                if (_downloadlist.Count > 0 && _downloadlist.ElementAt(0).Equals("access.log"))
                {
                    _downloadlist.Dequeue();
                }
                StartDownloading();
            }
            catch (Exception ex)
            {
                Console.WriteLine(string.Format("Connecting to Ftp Host : {0} with username : {1}",
                    _ftpUserInfo.Host, _networkCredential.UserName));
                Console.WriteLine(ex);
            }
        }

        ///

        ///
        private async void StartDownloading()
        {
            while (_downloadlist.Count > 0)
            {
                try
                {
                    #region File Path Configuration

                    var sourcefilepath = _downloadlist.Dequeue();
                    var destinationfilepath = string.Format("{0}\\{1}", _ftpUserInfo.DownloadPath,
                        Path.GetFileName(sourcefilepath));
                    #endregion
                    var request = WebRequest.Create(sourcefilepath) as FtpWebRequest;
                    if (request == null) continue;
                    request.UseBinary = true;
                    request.Timeout = 1200000;
                    request.ReadWriteTimeout = 1200000;
                    request.UsePassive = true;
                    request.KeepAlive = false;
                    request.EnableSsl = false;
                    request.Headers["User-Agent"] = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.1.5) Gecko/20091102 Firefox/3.5.5";
                    request.Credentials = _networkCredential;
                    request.Method = WebRequestMethods.Ftp.DownloadFile;
                    using (var response = (FtpWebResponse) await request.GetResponseAsync())
                    {
                        lock (_sync)
                        {
                            Console.WriteLine("Downloading file " + sourcefilepath);
                            if (response.ContentLength <= 0) continue;
                            using (var file = File.Create(destinationfilepath))
                            {
                                var responseStream = response.GetResponseStream();
                                if (responseStream == null) continue;
                                responseStream.CopyTo(file);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(string.Format("Ftp Host : {0}", _ftpUserInfo.Host));
                   Console.WriteLine(ex);
                }
            }
        }

      

        ///

        ///
        ///
        /// 
        protected virtual async Task FtpFileCreationTime(Uri url)
        {
            try
            {
                var creationtime = WebRequest.Create(url) as FtpWebRequest;
                if (creationtime != null)
                {
                    creationtime.UsePassive = false;
                    creationtime.UseBinary = true;
                    creationtime.Headers["User-Agent"] = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.1.5) Gecko/20091102 Firefox/3.5.5"; 
                    creationtime.Credentials = _networkCredential;
                    creationtime.Method = WebRequestMethods.Ftp.GetDateTimestamp;
                    using (var filecreationtime = await creationtime.GetResponseAsync() as FtpWebResponse)
                    {
                        return filecreationtime != null ? filecreationtime.LastModified : DateTime.Now;
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
            return DateTime.Now;
        }

        public void Dispose()
        {
            throw new NotImplementedException();
        }
    }
}

FtpInfo class for passing the credential

namespace betechnical.FTP
{
    ///

    /// 
    ///
    public class FtpUserInfoVo
    {
        public string Host { get; set; }
        public string DownloadPath { get; set; }
        public string Password { get; set; }
        public string Port { get; set; }
        public string UserName { get; set; }
    }
}
Advertisements

Swap two variable without using the third variable

using System;

namespace Swap
{
    class Program
    {
        private static void Main(string[] args)
        {
            int a = 1000;
            int b = 999;
            Console.WriteLine("Before Swap");
            Console.WriteLine("Value of A :{0} ", a);
            Console.WriteLine("Value of B :{0} ", b);
            a = a + b;
            b = a - b;
            a = a - b;
            Console.WriteLine("After Swap");
            Console.WriteLine("Value of A :{0} ", a);
            Console.WriteLine("Value of B :{0} ", b);
            Console.ReadLine();
        }

    }
}

Singleton thread-safe class in c#

Introduction

The singleton pattern is one of the best-known patterns in software engineering. Essentially, a singleton is a class which only allows a single instance of itself to be created, and usually gives simple access to that instance. Most commonly, singletons don’t allow any parameters to be specified when creating the instance – as otherwise, the second request for an instance but with a different parameter could be problematic! (If the same instance should be accessed for all requests with the same parameter, the factory pattern is more appropriate.) This article deals only with the situation where no parameters are required. Typically a requirement of singletons is that they are created lazily – i.e. that the instance isn’t created until it is first needed.

There are various ways of implementing the singleton pattern in C#. I shall present them here in reverse order of elegance, starting with the most commonly seen, which is not thread-safe, and working up to an entirely lazily-loaded, thread-safe, simple and highly performant version.

All these implementations share four common characteristics, however:

  • A single constructor, which is private and parameterless. This prevents other classes from instantiating it (which would be a violation of the pattern). Note that it also prevents subclassing – if a singleton can be subclassed once, it can be subclassed twice, and if each of those subclasses can create an instance, the pattern is violated. The factory pattern can be used if you need a single instance of a base type, but the exact type isn’t known until runtime.
  • A static variable which holds a reference to the single created instance, if any.
  • A public static means of getting the reference to the single created instance, creating one if necessary.

Let’s start with a quick example of a singleton class.

namespace betechnical
{
    
    public class Singleton
    {
        ///
        /// Private constructor to protect the instance of class
        ///
        private Singleton(){ }
        private static Singleton _instance;
        private static readonly object Sync=new object();

        public static Singleton Instance()
        {
            //Check if instance is null then only enter to the block
            if (_instance == null)
            {
                //Check if another thread is alreayd accessing
                lock (Sync)
                {
                    //Check if instance is already created by previous thread
                    if (_instance == null)
                    {
                        _instance = new Singleton();
                    }
                }
            }
            return _instance;
        }

    }
}

Handle CreatedDate,ModifiedDate,CreatedBy and ModifiedBy in Entity Framework

What is created date and Modified date and when we use this?
Keeping CreatedDate, ModifiedDate,  CreatedBy, and ModifiedBy or auditing columns in the database tables is part of good practices for database design. these columns help in many scenarios like select all the record by created date,Modified date.

If you have any transaction table like customer info, Order Details,EmployeeInfor then you can use CreatedDate and ModifiedDate.

If you have any tables which have user action like Order is placed by this user and modified by this user in this scenario you can use all four columns CreatedDate, ModifiedDate,  CreatedBy, and ModifiedBy
Let’s start with some coding part.

Public class Employee
{
  public int ID{get;set;}

  public String Name {get;set;}

  public String CreatedDate {get;set;}
  public String ModifiedDate{get;set;}
  public String CreatedBy{get;set;}
  public String ModifiedBy{get;set;}
}

While adding or modifying the employee class you have to take care of these two properties because we can not provide these properties in the user form as input.

Note: If you have one or two classes then you can manage to add additional code without any issue but if you have thousands of classes then obviously you will think of some generic code which can handle these two properties automatically while doing all add or edit operation.

As we discussed earlier auditing information is not required in all the tables.

public class BaseClass
{

  public String CreatedDate {get;set;}
  public String ModifiedDate{get;set;}
  public String CreatedBy{get;set;}
  public String ModifiedBy{get;set;}
}

There are two advantages of using BaseClass here

  • No need to write auditing columns properties in all the entity classes
  • It will be easy to differentiate between the Auditing entity vs normal entity class

If you are using entity framework then we can override the SaveChanges method inside the DbContext class and perform our auditing columns logic.

  public override int SaveChanges()
       {
    var entities = ChangeTracker.Entries().Where(x =&gt; x.Entity is BaseEntity &amp;&amp; (x.State == EntityState.Added || x.State == EntityState.Modified));
           var currentUsername = HttpContext.Current != null &amp;&amp; HttpContext.Current.User != null
                ? HttpContext.Current.User.Identity.Name
                : "Anonymous";
 foreach (var entity in entities)
        {
           if (entity.State == EntityState.Added)
              {
                    ((BaseEntity)entity.Entity).CreatedDate = DateTime.Now;
                    ((BaseEntity)entity.Entity).CreatedBy = currentUsername;
                }

                ((BaseEntity)entity.Entity).ModifiedDate = DateTime.Now;
                ((BaseEntity)entity.Entity).ModifiedBy = currentUsername;
            }
 return base.SaveChanges();
      }

Dot Net Interview questions for Experience

  • What is connection pooling?
  • When should we use connection pooling?
  • What is strong Dll?
  • What is bucketing in the database?
  • Do we need a certificate in client machine for HTTPS?
  • What is two-factor authentication?
  • Can we use singleton in reservation system?
  • What is ref keyword in C#?
  •  Can we determine when an object goes out of the reference?
  • What is a conditional and unconditional update in Ajax?
  • What is message lever security?
  • Can we use the function in where clause?
  • What is Order in the Func Input or return type?
  • What is the difference between ref and out keyword?
  • How to thread safe Singleton class?
  • The difference between interface and  abstract class?
  • When to use interface and Abstract class.
  • What are Extension methods in C#?
  • What is anonymous  function and how to use this?