Showing posts with label C#.NET. Show all posts
Showing posts with label C#.NET. Show all posts

Tuesday, March 27, 2018

How to create a dropdown-list from an Enum in ASP.NET MVC (5.1 & above)

In ASP.NET MVC 5.1, you can use EnumDropDownListFor() helper, so no need for custom extensions:


Model:
public enum MyEnum
{
    [Display(Name = "First Value - desc..")]
    FirstValue,
    [Display(Name = "Second Value - desc...")]
    SecondValue
}
View:
@Html.EnumDropDownListFor(model => model.MyEnum)
Using Tag Helper (ASP.NET MVC 6):
<select asp-for="@Model.SelectedValue" asp-items="Html.GetEnumSelectList<MyEnum>()">

Tuesday, April 18, 2017

How to use a common class to check user session is still valid in ASP.NET web pages

On a .aspx page load, you may want to check if the session is valid. If valid continue with the page load and if not redirect to login.aspx page.

We write our own class which inherits from System.Web.UI.Page.

 public class CustomClass : System.Web.UI.Page
    {

        public CustomClass()
        {
        }

        protected override void OnInit(EventArgs e)
        {                   
            //Check if the page is no public and the user session is valid
            if (isSessionValid())
            {
                // Continue work.   
            }
            else
            {
                 RedirectToLogin();
            }
            this.Load += new EventHandler(CustomClass_Load);
            base.OnInit(e);
        }


        protected void CustomClass_Load(object sender, EventArgs e)
        {

        }

        public void RedirectToLogin()
        {
            Response.Redirect(this.ResolveUrl("~/Login.aspx"));
        }

    }
Then we can inherit our .aspx.cs class from our custom class.

public partial class Mywebsite_PaymentPage : CustomClass
{

}
This will result in checking the user session validity every time "PaymentPage.aspx" loads. You can inherit all the .aspx.cs page classes, which require session based authentication, from this CustomClass.cs. This will eliminate the trouble of checking the session in each and every page load method individually.

Wednesday, March 15, 2017

How to use interfaces in C#.NET

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;
            }
        }
    }
}