Surendra Sharma

Surendra Sharma

Search This Blog

Thursday, March 20, 2014

How to upload file via SFTP using private key in ASP.NET using C#

In almost all ASP.NET web application, we have to write a code to upload file to secure SFTP servers.

Here is simple and full code to upload file via SFTP.

First you need to download SshNet DLL from http://sshnet.codeplex.com/.

You can connect SFTP by two ways
1.    By using credentials
2.    By using Username and private key. Private Key may be bind with Pass phrase.

This code is specific to connect to SFTP by using private key.

Note:- Your private key must be compatible with SshNet. To convert any private key to SshNet compatible private key, refer my other article How to convert Private key to OpenSSH Key to connect to SFTP server.

It uses SftpClient for creating SFTP connection to server by providing SFTP URL with credentials and private key to connect to specific folder or root folder. Code read the file and uploads the final stream to SFTP server.

using Renci.SshNet;

public static void UploadFileToSFTPServer(string FilePath, string Address, int Port, string UserName, string Password, string FolderName)
{
    SftpClient client = null;

    string sPrivateKeyPath = "PrivateKeyFilePath";
    PrivateKeyFile ObjPrivateKey = null;
    PrivateKeyAuthenticationMethod ObjPrivateKeyAutentication = null;
    using (Stream stream = File.OpenRead(sPrivateKeyPath))
    {
        if (ConfigurationSettings.AppSettings["PassPhraseCode"] != null)
        {
            string sPassPhrase = ConfigurationSettings.AppSettings["PassPhraseCode"];
            ObjPrivateKey = new PrivateKeyFile(stream, sPassPhrase);
            ObjPrivateKeyAutentication = new PrivateKeyAuthenticationMethod(UserName, ObjPrivateKey);
        }
        else
        {
            ObjPrivateKey = new PrivateKeyFile(stream);
            ObjPrivateKeyAutentication = new PrivateKeyAuthenticationMethod(UserName, ObjPrivateKey);
        }

        ConnectionInfo objConnectionInfo = new ConnectionInfo(Address, Port, UserName, ObjPrivateKeyAutentication);
        client = new SftpClient(objConnectionInfo);
    }
SftpClient client = new SftpClient(Address, Port, UserName, Password);


    client.Connect();

    if (!string.IsNullOrEmpty(FolderName))
    {
        client.ChangeDirectory(FolderName + @"/");
    }

    using (var fileStream = new FileStream(FilePath, FileMode.Open))
    {
        client.BufferSize = 4 * 1024;
        client.UploadFile(fileStream, Path.GetFileName(FilePath), null);
    }
    client.Disconnect();
    client.Dispose();


Please leave your comments or share this code if it’s useful for you.

Wednesday, March 19, 2014

How to upload file via secure SFTP using credentials in ASP.NET using C#

In almost all ASP.NET web application, we have to write a code to upload file to secure SFTP servers.

Here is simple and full code to upload file via SFTP.

First you need to download SshNet DLL from http://sshnet.codeplex.com/.

You can connect SFTP by two ways
1.    By using credentials
2.    By using Username and private key

This code is specific to connect to SFTP by using credentials.

It uses SftpClient for creating SFTP connection to server by proving SFTP URL with necessary credentials to any specific folder or root folder. Code read the file and uploads the final stream to SFTP server.

using Renci.SshNet;

public static void UploadFileToSFTPServer(string FilePath, string Address, int Port, string UserName, string Password, string FolderName)
{
    SftpClient client = new SftpClient(Address, Port, UserName, Password);

    client.Connect();

    if (!string.IsNullOrEmpty(FolderName))
    {
        client.ChangeDirectory(FolderName + @"/");
    }

    using (var fileStream = new FileStream(completeFilePath, FileMode.Open))
    {
        client.BufferSize = 4 * 1024;
        client.UploadFile(fileStream, Path.GetFileName(completeFilePath), null);
    }
    client.Disconnect();
    client.Dispose();


Please leave your comments or share this code if it’s useful for you.

Friday, March 14, 2014

How to upload file via FTP with SSL in ASP.NET using C#


In almost all ASP.NET web application, we have to write a code to upload file to FTP servers with SSL for security reasons.

Here is simple and full code to upload file via FTP with SSL.

It uses FtpWebRequest for creating FTP connection to server by proving FTP URL, SSL ceritifcates with necessary credentials. Below code reads the file byte by byte and upload the final stream to FTP server.

RemoteCertificateValidationCallback orgCallback = ServicePointManager.ServerCertificateValidationCallback;
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(OnValidateCertificate);
ServicePointManager.Expect100Continue = true;
Stream requestStream = null;
FtpWebRequest ftpRequest = (FtpWebRequest)FtpWebRequest.Create("FTP URL ADDRESS");
ftpRequest.Method = WebRequestMethods.Ftp.UploadFile;
ftpRequest.Proxy = null;
ftpRequest.UseBinary = true;
ftpRequest.KeepAlive = false;
ftpRequest.EnableSsl = isSSL;
ftpRequest.UsePassive = isUsePassive;
ftpRequest.Credentials = new NetworkCredential(userName, password);
ftpRequest.UsePassive = isUsePassive;

using (requestStream = ftpRequest.GetRequestStream())
{
    const int bufferLength = 2048;
    byte[] buffer = new byte[bufferLength];
    int count = 0;
    int readBytes = 0;
    FileInfo objfileInfo = new FileInfo(completeFilePath);
    FileStream stream = objfileInfo.OpenRead();
    do
    {
        readBytes = stream.Read(buffer, 0, bufferLength);
        requestStream.Write(buffer, 0, readBytes);
        count += readBytes;
    }
    while (readBytes != 0);
}

public static bool OnValidateCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
     return false;
}


Please leave your comments or share this code if it’s useful for you.

Thursday, March 13, 2014

How to upload file via FTP in ASP.NET using C#

In almost all ASP.NET web application, we have to write a code to upload file to FTP servers.

Here is simple and full code to upload file via FTP.

It uses FtpWebRequest for creating FTP connection to server by proving FTP URL with necessary credentials. Code read the file byte by byte and upload the final stream to FTP server.

Stream requestStream = null;
FtpWebRequest ftpRequest = (FtpWebRequest)FtpWebRequest.Create("FTP URL ADDRESS");
ftpRequest.Method = WebRequestMethods.Ftp.UploadFile;
ftpRequest.Proxy = null;
ftpRequest.UseBinary = true;
ftpRequest.KeepAlive = false;
ftpRequest.UsePassive = isUsePassive;
ftpRequest.Credentials = new NetworkCredential(userName, password);
ftpRequest.UsePassive = isUsePassive;

using (requestStream = ftpRequest.GetRequestStream())
{
    const int bufferLength = 2048;
    byte[] buffer = new byte[bufferLength];
    int count = 0;
    int readBytes = 0;
    FileInfo objfileInfo = new FileInfo(completeFilePath);
    FileStream stream = objfileInfo.OpenRead();
    do
    {
        readBytes = stream.Read(buffer, 0, bufferLength);
        requestStream.Write(buffer, 0, readBytes);
        count += readBytes;
    }
    while (readBytes != 0);
}


Please leave your comments or share this code if it’s useful for you.

Wednesday, March 12, 2014

How to convert Private key to OpenSSH Key to connect to SFTP server

When you are trying to connecting SFTP server using Renci SSH DLL using C#, then you have to either provide username and password or username and private key.

Private Key works only with WINSCP tool and the PrivateKeyFile class in Renci SSH DLL does not accept Private Key file, so we need to convert Private key file to OpenSSH key.

After conversion of Private key file to OpenSSH key file, with our code we can able to connect, download and upload to SFTP server.

                                  Steps to convert Private file to OpenSSH Key.

1. Open PuTTY key Generator.








   2.Click on Load button 

 

  
  3. Load PRI key file .

 


   
4. After click on open button a alert pops up, click on Yes to continue.


 


  5. Save dialog comes up, assign name to the file and save it with .ppk extension.

 
  


Please leave your comments or share this tip if it’s useful for you.

Tuesday, March 11, 2014

How to provide hyperlinks in excel sheet using C# or any programming language

If you are writing program to put records in excel file from C# or any programming language.

Sometimes we need to provide hyper links to some data so that when user click on those cells, a link should be opened. This is very tedious works to write a code for hyperlinks in excel cells.

How can you do it in easy way?

Excel comes with their own formulas. So for hyperlink, excel provides HYPERLINK formula with two parameters
1.         Link location i.e. URL address
2.         Friendly name i.e. Display Text and its optional

Example 1:

=HYPERLINK("http://www.techgig.com/", "Click Here")

This should display text "Click Here" in cell. When user click on it, excel opened site "http://www.techgig.com/"

Example 2:
If you have some files in along with excel file in the same folder and you want to open those file from excel file by providing links in excel cells then use below formula

=HYPERLINK(".\File_In_Same_Folder.xlsx", "Open Test File")

Here dot in ".\File_In_Same_Folder.xlsx" indicates that use current directory path as of excel file and open "File_In_Same_Folder.xlsx" file.

Use HYPERLINK formula for excel sheet from programming language.


Please leave your comments or share this tip if it’s useful for you.

Monday, March 10, 2014

My Shayaris

I always believe in sharing knowledge.

From my college days, I always thought that I have to write something, but I never really got any starting point.

First thing who inspire me for writing was blogging. I started to write technical things. Whenever I am working on project and stuck somewhere in coding, I tried to find its solution and then share the problem with its solution with rest of the world.

Second thing I started to write is travelogue. Whenever I travelled to any new location, I tried to share location details, total expense, photos, etc.

Now I am trying to write shayaris. I love shayaris and gazals as they hide some message with them and always indicate one’s feeling at that particular moment in life. Here are some shayaris which I recently compose



1.    dftr ke alava bhi duniya hai hmari,
dftr ke alava bhi duniya hai hmari,
kbhi milo to janoge kuch rishta hai is duniya se tumhara

2.    ishk ki duniya se niklo or hkikt ki baat kro pyare,
ishk ki duniya se niklo or hkikt ki baat kro pyare,
khvabo se jyada paise se duniya chlti hai

3.    teri dil ki hr bimari ki vjh hu mai,
teri dil ki hr bimari ki vjh hu mai,
teri dil ki hr bimari ki ek hi dva hu mai

4.    tere ishq ka mai vo jhr hu jo tujhe jinda nhi rhne dega,
tere ishq ka mai vo jhr hu jo tujhe jinda nhi rhne dega,
tere ishq ka mai vo amrut bhi hu jo tujhe mrne bhi nhi dega

5.    tu apne muat ki aarzoo kre,
tu apne maut ki aarzoo kre,
khuda kre ki mujhe jnnt nsib ho

6.    hm to bs ek dariya hai,
hm to bs ek dariya hai,
tum shayad hmari gahrai naap sko

7.    jis dil-e-dariya ka tum kinara dund rhi ho,
jis dil-e-dariya ka tum kinara dund rhi ho,
e 'Anu' vhi kinara hi to asliyt me teri mnzil hai !!

8.    tnhai me meri aajkl bsi hai teri yaade,
tnhai me meri aajkl bsi hai teri yaade,
e mere khuda bhle hi mujh pe 100 bijliya gira de,
lekin us shkhs se bs mujhe mila de





9.    din me bhi tu, raat me bhi tu,
Jindgi ki hr ghdi me bhi tu,
meri hr ek sans me bsi hai sirf tu hi tu !!!

10.  mai tere haseen khvabo me kho jana chahta hu,
mai tere haseen khvabo me kho jana chahta hu,
pr kmbkht teri judai mujhe sone hi nhi deti !!!

11.  Apne dil ki ghraiyo me chupa lena chahta hu mai tujhe,
Apne dil ki ghraiyo me chupa lena chahta hu mai tujhe,
dr hai khi ye jmana chin na le mujhse tujhe !!!

12.  Meri jindgi ki Kahani ka vo hissa hai tu,
Meri jindgi ki Kahani ka vo hissa hai tu,
bina tere kahani hi meri adhuri hai !!!

13.  mujhe hai tujhse pyar,
yaad krta hu tujhe mai bar bar,
tere bina jindgi hai bekar,
tere liye chod du ghr bar,
ab ki bar modi sarkar !!!

14.  ek nya sher un pe likh rha hu,
ek nya sher un pe likh rha hu,
khuda jane aajkl hmari hr baat shayari kyo bn jati hai !!!

15.  tu meri kismt me hai ya meri teri takdir me,
tu meri kismt me hai ya meri teri takdir me,
ek dusre ko pa hi lenge, agr naam lilha hoga hatho ki lkiro me !!!

16.  unse dil har kar bhi muskura rha hu mai,
unse dil har kar bhi muskura rha hu mai,
unhe kya khbr unki jeet se jyada unse dil haar kr khush hu mai !!!

17.  akeli duniya me meri aana bhle hi teri mrji,
pr ek bar aake vaps jana sirf meri mrji !!!

18.  dil me mere rhte ho tum, tere dil me mai rhti hu,
dil me mere rhte ho tum, tere dil me mai rhti hu,
kbhi kbhi is kdhr ghum ho jati hu,
kbhi kbhi is kdhr ghum ho jati hu,
pr hay re meri kismt akhir me tujhse hi ja tkrati hu !!!

19.  maana ki aaj kuch duriya hai unse hmari,
maana ki aaj kuch duriya hai unse hmari,

jmana ek din dekhega jrur, ruh bhi bsi hai unme hmari !!!

Please let me know which one you like the most.