Tuesday, July 4, 2017

SQL Server IF condition to check table exists in the database

-- If 'tmp_processedLogs' table doesn't exists, then create it.
IF NOT EXISTS (SELECT * FROM sysobjects WHERE NAME = 'tmp_processedLogs' AND xtype='U')
CREATE TABLE tmp_processedLogs(LogFileName VARCHAR(MAX),Message VARCHAR(MAX),ProcessedOn DATETIME);

Sunday, July 2, 2017

Kill Active Sessions On a Server Using Command Prompt

First rule is you need to have proper permissions to access the server to which you are trying to reset the connections.

If you do not know the server IP address you can find it using the following CMD command.
ping yourservername

Then run the following command to get the sessions on the server.
qwinsta /server:203.0.156.203

Get the ID of the session you want to kill.
rwinsta [SessionID] /server:203.0.156.203

Monday, June 5, 2017

JavaScript file caching issue in Internet Explorer

Internet Explorer caches the JavaScript file for purpose of fast rendering but sometimes it's problematic for the developers. When you do a new change in a JavaScript file, IE doesn't recognize that there has been a change straightaway unless you do a page refresh and it loads the old file which could cause the application to crash. 

So the solution is we need to force the browser to get the newer version of the JavaScript file but we also may don't won't to do this every time the page loads. 

You can append a version number at the end of the JavaScript file link as follows so that, IE recognizes that there has been a change and will reload the JavaScript file. 

<script language="javascript" type="text/javascript" src="Media/JavaScript/quoteandbilling.js?v=1.2"></script>


Wednesday, April 26, 2017

How to reset user settings in Visual Studio

  1. Close Visual Studio
  2. Start the Developer Command prompt installed with Visual Studio as an administrator.
  3. type 'devenv /resetuserdata' ('wdexpress /resetuserdata' for Express SKUs)
  4. Start Visual Studio Normally.

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.

Monday, April 17, 2017

Things to keep in mind when creating a "CLUSTERED" index in SQL Server

You should use extreme care when picking a clustering key - it should be:
  1. narrow (4 bytes ideal)
  2. unique (it's the "row pointer" after all. If you don't make it unique SQL Server will do it for you in the background, costing you a couple of bytes for each entry times the number of rows and the number of nonclustered indices you have - this can be very costly!)
  3. static (never change - if possible)
  4. ideally ever-increasing so you won't end up with horrible index fragmentation (a GUID is the total opposite of a good clustering key - for that particular reason)
  5. it should be non-nullable and ideally also fixed width - a varchar(250) makes a very poor clustering key

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