[2 days left] What’s wrong with your cloud strategy? Learn why multicloud solutions matter with Nimble Storage.Register Now

x
?
Solved

Troublein FTPing with CFtpConnection

Posted on 2001-09-12
4
Medium Priority
?
1,209 Views
Last Modified: 2013-11-20

Hi,

I've developed a class CBatchFtp, as a wrapper for CInternetSession and CFtpConnection. The class has methods to put and get single and multiple files and to check presence of a file in ftp server.

Problem :

A first time call to any of the get/put/seatch methods work fine. Immediately, a call to another method of the CBatchFtp object, fails in CInternetSession->GetFtpConnection API call.

Error Description :

CInternetException->GetErrorMessage = "The handle is invalid" and CInternetException->m_dwError = 6.

Given below is the class and its usage.

// CBatchFTP.h
//

#if !defined(CBatchFTP_h)
#define CBatchFTP_h

#include <afxwin.h>
#include <afxinet.h>

class CBatchFTP
{
public:

      bool ImportFiles(CString FTPServer, CString UserID, CString Password, CString pszLocalPath,  CString pszRemotePath);
      bool ExportFiles(CString FTPServer, CString UserID, CString Password, CString pszFileName,CString pszLocalPath,CString pszRemotePath, bool bDeleteFile = true);
      bool ExportFiles(CString FTPServer, CString UserID, CString Password, CString pszLocalPath,CString pszRemotePath, bool bDeleteFile = true);    
      bool SearchFileInServer(CString FTPServer, CString UserID, CString Password,CString pszFileName, CString pszRemotePath);
      CBatchFTP();
      CBatchFTP(int PortNumber);
    virtual ~CBatchFTP();

protected:


private:

    CInternetSession      m_InetSession;
    CFtpConnection *      m_FTPConnection;
      int                              m_PortNumber;

};

#endif /* CBatchFTP_h */


// CBatchFTP.cpp
//
#include "CBatchFTP.h"

bool CBatchFTP::ImportFiles(CString FTPServer, CString UserID, CString Password, CString pszLocalPath,  CString pszRemotePath)
{
      if (m_FTPConnection)
      {
            delete m_FTPConnection;
            m_FTPConnection = NULL;
      }

      try
      {
            m_FTPConnection = m_InetSession.GetFtpConnection(FTPServer,UserID,Password,m_PortNumber,0);
      }
      catch(CInternetException * eInetException)
      {
            char ErrMsg[2001];
            CString sErrMsg;

            memset(ErrMsg,0,2001);
            eInetException->GetErrorMessage(ErrMsg,2000);
            sErrMsg = ErrMsg;
      }

      if (m_FTPConnection)
      {
            CFtpFileFind RemoteFileFind(m_FTPConnection);
            if (! pszRemotePath.IsEmpty()) // If Remote path is not empty
            {
                  if (FALSE  == m_FTPConnection->SetCurrentDirectory(pszRemotePath))
                  {
                        LPVOID lpMsgBuf;
                        FormatMessage(
                              FORMAT_MESSAGE_ALLOCATE_BUFFER |
                              FORMAT_MESSAGE_FROM_SYSTEM |
                              FORMAT_MESSAGE_IGNORE_INSERTS,
                              NULL,
                              GetLastError(),
                              MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
                              (LPTSTR) &lpMsgBuf,
                              0,
                              NULL
                        );

                        CString ErrorMesg;
                        ErrorMesg.Format("Batch FTP Failed. Error Msg : %s", (LPCTSTR) lpMsgBuf);
                        //oBatchErr.LogBatchError(0, ErrorMesg, "CFTPConnection::SetCurrentDirectory",
                                                            //" ExportFiles");
                        LocalFree( lpMsgBuf );
                        return false;
                  }
            }

            CString RemoteFileName;
            CString LocalFileName;
            BOOL bFileFound = RemoteFileFind.FindFile();
            while (bFileFound)
            {
                  bFileFound = RemoteFileFind.FindNextFile();
                  if (RemoteFileFind.IsDots() || RemoteFileFind.IsDirectory())
                        continue;
                  LocalFileName = pszLocalPath;
                  RemoteFileName = RemoteFileFind.GetFileName();
                  if (LocalFileName[LocalFileName.GetLength() - 1] != '\\')
                  {
                        LocalFileName += "\\";
                  }
                  LocalFileName += RemoteFileName;
                  BOOL bGetDone = m_FTPConnection->GetFile(RemoteFileName, LocalFileName, 0,
                                                FILE_ATTRIBUTE_ARCHIVE, FTP_TRANSFER_TYPE_ASCII, 1);                  
                  if (FALSE == bGetDone)
                  {
                        LPVOID lpMsgBuf;
                        FormatMessage(
                              FORMAT_MESSAGE_ALLOCATE_BUFFER |
                              FORMAT_MESSAGE_FROM_SYSTEM |
                              FORMAT_MESSAGE_IGNORE_INSERTS,
                              NULL,
                              GetLastError(),
                              MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
                              (LPTSTR) &lpMsgBuf,
                              0,
                              NULL
                        );

                        CString ErrorMesg;
                        ErrorMesg.Format("Batch FTP Failed. Error Msg : %s", (LPCTSTR) lpMsgBuf);
                        //oBatchErr.LogBatchError(0, ErrorMesg, "CFTPConnection::GetFile",
                                                            //" ExportFiles");
                        LocalFree( lpMsgBuf );      
                  }
                  else
                  {
                        BOOL bRemoveDone = m_FTPConnection->Remove(RemoteFileName);
                        if (FALSE == bRemoveDone)
                        {
                              LPVOID lpMsgBuf;
                              FormatMessage(
                                    FORMAT_MESSAGE_ALLOCATE_BUFFER |
                                    FORMAT_MESSAGE_FROM_SYSTEM |
                                    FORMAT_MESSAGE_IGNORE_INSERTS,
                                    NULL,
                                    GetLastError(),
                                    MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
                                    (LPTSTR) &lpMsgBuf,
                                    0,
                                    NULL
                              );

                              CString ErrorMesg;
                              ErrorMesg.Format("Batch FTP Failed. Error Msg : %s", (LPCTSTR) lpMsgBuf);
                              //oBatchErr.LogBatchError(0, ErrorMesg, "CFTPConnection::Remove",
                                                                  //" ExportFiles");
                              LocalFree( lpMsgBuf );      
                        }
                  }
            }
      }
      else
      {
            LPVOID lpMsgBuf;
            FormatMessage(
                  FORMAT_MESSAGE_ALLOCATE_BUFFER |
                  FORMAT_MESSAGE_FROM_SYSTEM |
                  FORMAT_MESSAGE_IGNORE_INSERTS,
                  NULL,
                  GetLastError(),
                  MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
                  (LPTSTR) &lpMsgBuf,
                  0,
                  NULL
            );

            CString ErrorMesg;
            ErrorMesg.Format("Batch FTP Failed. Error Msg : %s", (LPCTSTR) lpMsgBuf);
            //oBatchErr.LogBatchError(0, ErrorMesg, "CInternetSession::GetFtpConnection",
                                                //" ExportFiles");
            LocalFree( lpMsgBuf );
            return false;
      }
      
      if (m_FTPConnection)
      {
            m_FTPConnection->Close();
            delete m_FTPConnection;
            m_FTPConnection = NULL;
      }
      m_InetSession.Close();
      return true;
}

bool CBatchFTP::ExportFiles(CString FTPServer, CString UserID, CString Password,  CString pszFileName, CString pszLocalPath,CString pszRemotePath, bool bDeleteFile)
{

      if (m_FTPConnection)
      {
            delete m_FTPConnection;
            m_FTPConnection = NULL;
      }

      try
      {
            m_FTPConnection = m_InetSession.GetFtpConnection( LPCTSTR(FTPServer),
                                                                                      LPCTSTR(UserID),
                                                                                      LPCTSTR(Password),
                                                                                      m_PortNumber,1);
      }
      catch(CInternetException * eInetException)
      {
            char ErrMsg[2001];
            CString sErrMsg;

            memset(ErrMsg,0,2001);
            eInetException->GetErrorMessage(ErrMsg,2000);
            sErrMsg = ErrMsg;
      }

      if (m_FTPConnection)
      {
            if (! pszRemotePath.IsEmpty()) // If Remote path is not empty
            {
                  if (FALSE  == m_FTPConnection->SetCurrentDirectory(pszRemotePath))
                  {
                        LPVOID lpMsgBuf;
                        FormatMessage(
                              FORMAT_MESSAGE_ALLOCATE_BUFFER |
                              FORMAT_MESSAGE_FROM_SYSTEM |
                              FORMAT_MESSAGE_IGNORE_INSERTS,
                              NULL,
                              GetLastError(),
                              MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
                              (LPTSTR) &lpMsgBuf,
                              0,
                              NULL
                        );

                        CString ErrorMesg;
                        ErrorMesg.Format("Batch FTP Failed. Error Msg : %s", (LPCTSTR) lpMsgBuf);
                        //oBatchErr.LogBatchError(0, ErrorMesg, "CFTPConnection::SetCurrentDirectory",
                                                            //" ExportFiles");
                        LocalFree( lpMsgBuf );
                        return false;
                  }
            }
            CString LocalFileName = pszLocalPath;
            if (LocalFileName[LocalFileName.GetLength() - 1] != '\\')
            {
                  LocalFileName += "\\";
            }
            LocalFileName += pszFileName;

            BOOL bGetDone = m_FTPConnection->PutFile(LocalFileName, pszFileName, FTP_TRANSFER_TYPE_ASCII,1);                  
            if (FALSE == bGetDone)
            {
                  LPVOID lpMsgBuf;
                  FormatMessage(
                        FORMAT_MESSAGE_ALLOCATE_BUFFER |
                        FORMAT_MESSAGE_FROM_SYSTEM |
                        FORMAT_MESSAGE_IGNORE_INSERTS,
                        NULL,
                        GetLastError(),
                        MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
                        (LPTSTR) &lpMsgBuf,
                        0,
                        NULL
                  );

                  CString ErrorMesg;
                  ErrorMesg.Format("Batch FTP Failed. Error Msg : %s", (LPCTSTR) lpMsgBuf);
                  //oBatchErr.LogBatchError(0, ErrorMesg, "CFTPConnection::PutFile",
                                                      //" ExportFiles");
                  LocalFree( lpMsgBuf );
                  return false;
            }
            else
            {
                  if (bDeleteFile)
                  {
                        BOOL bDeleteDone = ::DeleteFile(LocalFileName);
                        if (FALSE == bDeleteDone)
                        {
                              CString ErrorMesg;
                              ErrorMesg.Format("DeleteFile Failed for : %s", LocalFileName);
                              //oBatchErr.LogBatchError(0, ErrorMesg, "::DeleteFile",
                                                                  //" ExportFiles");
                        }
                  }
            }
      }
      else
      {
            LPVOID lpMsgBuf;
            FormatMessage(
                  FORMAT_MESSAGE_ALLOCATE_BUFFER |
                  FORMAT_MESSAGE_FROM_SYSTEM |
                  FORMAT_MESSAGE_IGNORE_INSERTS,
                  NULL,
                  GetLastError(),
                  MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
                  (LPTSTR) &lpMsgBuf,
                  0,
                  NULL
            );
            CString ErrorMesg;
            ErrorMesg.Format("Batch FTP Failed. Error Msg : %s", (LPCTSTR) lpMsgBuf);
            //oBatchErr.LogBatchError(0, ErrorMesg, "CInternetSession::GetFtpConnection",
                                                //" ExportFiles");
            LocalFree( lpMsgBuf );
            return false;
      }
      if (m_FTPConnection)
      {
            m_FTPConnection->Close();
            delete m_FTPConnection;
            m_FTPConnection = NULL;
      }
      m_InetSession.Close();
      return true;
}

bool CBatchFTP::ExportFiles(CString FTPServer, CString UserID, CString Password, CString pszLocalPath,CString pszRemotePath, bool bDeleteFile)
{
      if (m_FTPConnection)
      {
            delete m_FTPConnection;
            m_FTPConnection = NULL;
      }

      try
      {
            m_FTPConnection = m_InetSession.GetFtpConnection(FTPServer,UserID,Password,m_PortNumber,1);
      }
      catch(CInternetException * eInetException)
      {
            char ErrMsg[2001];
            CString sErrMsg;

            memset(ErrMsg,0,2001);
            eInetException->GetErrorMessage(ErrMsg,2000);
            sErrMsg = ErrMsg;
      }

      if (m_FTPConnection)
      {
            if (! pszRemotePath.IsEmpty()) // If Remote path is not empty
            {
                  if (FALSE  == m_FTPConnection->SetCurrentDirectory(pszRemotePath))
                  {
                        LPVOID lpMsgBuf;
                        FormatMessage(
                              FORMAT_MESSAGE_ALLOCATE_BUFFER |
                              FORMAT_MESSAGE_FROM_SYSTEM |
                              FORMAT_MESSAGE_IGNORE_INSERTS,
                              NULL,
                              GetLastError(),
                              MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
                              (LPTSTR) &lpMsgBuf,
                              0,
                              NULL
                        );
                        CString ErrorMesg;
                        ErrorMesg.Format("Batch FTP Failed. Error Msg : %s", (LPCTSTR) lpMsgBuf);
                        //oBatchErr.LogBatchError(0, ErrorMesg, "CFTPConnection::SetCurrentDirectory",
                                                            //" ExportFiles");
                        LocalFree( lpMsgBuf );
                        return false;
                  }
            }

            CFileFind      LocalFolderSearch;
            CString LocalFileName, LocalFolderName = pszLocalPath;
            if (LocalFolderName[LocalFolderName.GetLength() - 1] != '\\')
            {
                  LocalFolderName += "\\";
            }
            LocalFolderName += "*.*";

            BOOL bFileFound = LocalFolderSearch.FindFile(LocalFolderName);
            while (bFileFound)
            {
                  bFileFound = LocalFolderSearch.FindNextFile();
                  LocalFileName = LocalFolderSearch.GetFilePath();
                  if (LocalFolderSearch.IsDots() || LocalFolderSearch.IsDirectory())
                        continue;
                  BOOL bGetDone = m_FTPConnection->PutFile(LocalFileName,
                                                                               LocalFolderSearch.GetFileName(),
                                                                               FTP_TRANSFER_TYPE_ASCII,1);
                  if (FALSE == bGetDone)
                  {
                        LPVOID lpMsgBuf;
                        FormatMessage(
                              FORMAT_MESSAGE_ALLOCATE_BUFFER |
                              FORMAT_MESSAGE_FROM_SYSTEM |
                              FORMAT_MESSAGE_IGNORE_INSERTS,
                              NULL,
                              GetLastError(),
                              MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
                              (LPTSTR) &lpMsgBuf,
                              0,
                              NULL
                        );
                        CString ErrorMesg;
                        ErrorMesg.Format("Batch FTP Failed. Error Msg : %s", (LPCTSTR) lpMsgBuf);
                        //oBatchErr.LogBatchError(0, ErrorMesg, "CFTPConnection::PutFile",
                                                            //" ExportFiles");
                        LocalFree( lpMsgBuf );
                        return false;
                  }
                  else
                  {
                        if (bDeleteFile)
                        {
                              BOOL bDeleteDone = ::DeleteFile(LocalFileName);
                              if (FALSE == bDeleteDone)
                              {
                                    CString ErrorMesg;
                                    ErrorMesg.Format("DeleteFile Failed for : %s", LocalFileName);
                                    //oBatchErr.LogBatchError(0, ErrorMesg, "::DeleteFile",
                                                                        //" ExportFiles");
                              }
                        }
                  }

            }
      }
      else
      {
            LPVOID lpMsgBuf;
            FormatMessage(
                  FORMAT_MESSAGE_ALLOCATE_BUFFER |
                  FORMAT_MESSAGE_FROM_SYSTEM |
                  FORMAT_MESSAGE_IGNORE_INSERTS,
                  NULL,
                  GetLastError(),
                  MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
                  (LPTSTR) &lpMsgBuf,
                  0,
                  NULL
            );
            CString ErrorMesg;
            ErrorMesg.Format("Batch FTP Failed. Error Msg : %s", (LPCTSTR) lpMsgBuf);
            //oBatchErr.LogBatchError(0, ErrorMesg, "CInternetSession::GetFtpConnection",
                                                //" ExportFiles");
            LocalFree( lpMsgBuf );
            return false;
      }
      if (m_FTPConnection)
      {
            m_FTPConnection->Close();
            delete m_FTPConnection;
            m_FTPConnection = NULL;
      }
      m_InetSession.Close();
      return true;
}

bool CBatchFTP::SearchFileInServer(CString FTPServer, CString UserID, CString Password,CString pszFileName, CString pszRemotePath)
{

      bool bFoundMyFile = false;
      
      if (m_FTPConnection)
      {
            delete m_FTPConnection;
            m_FTPConnection = NULL;
      }
      try
      {
            m_FTPConnection = m_InetSession.GetFtpConnection(FTPServer,UserID,Password,m_PortNumber,0);
      }
      catch(CInternetException * eInetException)
      {
            char ErrMsg[2001];
            CString sErrMsg;

            unsigned long ErrCode;

            ErrCode = eInetException->m_dwError;

            memset(ErrMsg,0,2001);
            eInetException->GetErrorMessage(ErrMsg,2000);
            sErrMsg = ErrMsg;
      }

      if (m_FTPConnection)
      {
            CFtpFileFind RemoteFileFind(m_FTPConnection);

            if (! pszRemotePath.IsEmpty()) // If Remote path is not empty
            {
                  if (FALSE  == m_FTPConnection->SetCurrentDirectory(pszRemotePath))
                  {
                        LPVOID lpMsgBuf;
                        FormatMessage(
                              FORMAT_MESSAGE_ALLOCATE_BUFFER |
                              FORMAT_MESSAGE_FROM_SYSTEM |
                              FORMAT_MESSAGE_IGNORE_INSERTS,
                              NULL,
                              GetLastError(),
                              MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
                              (LPTSTR) &lpMsgBuf,
                              0,
                              NULL
                        );

                        CString ErrorMesg;
                        ErrorMesg.Format("Batch FTP Failed. Error Msg : %s", (LPCTSTR) lpMsgBuf);
                        //oBatchErr.LogBatchError(0, ErrorMesg, "CFTPConnection::SetCurrentDirectory",
                                                            //" SearchFileInServer");
                        LocalFree( lpMsgBuf );
                        return false;
                  }
            }

            CString RemoteFileName;
            BOOL bAnyFileFound = RemoteFileFind.FindFile();
            while (bAnyFileFound)
            {
                  bAnyFileFound = RemoteFileFind.FindNextFile();
                  if (RemoteFileFind.IsDots() || RemoteFileFind.IsDirectory())
                        continue;
                  RemoteFileName = RemoteFileFind.GetFileName();
                  if (RemoteFileName == pszFileName)                  
                  {
                        bFoundMyFile = true;
                        break;
                  }
            }
      }
      else
      {
            LPVOID lpMsgBuf;
            FormatMessage(
                  FORMAT_MESSAGE_ALLOCATE_BUFFER |
                  FORMAT_MESSAGE_FROM_SYSTEM |
                  FORMAT_MESSAGE_IGNORE_INSERTS,
                  NULL,
                  GetLastError(),
                  MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
                  (LPTSTR) &lpMsgBuf,
                  0,
                  NULL
            );

            CString ErrorMesg;
            ErrorMesg.Format("Batch FTP Failed. Error Msg : %s", (LPCTSTR) lpMsgBuf);
            //oBatchErr.LogBatchError(0, ErrorMesg, "CInternetSession::GetFtpConnection",
                                                //" SearchFileInServer");
            LocalFree( lpMsgBuf );
            return false;
      }
      
      if (m_FTPConnection)
      {
            m_FTPConnection->Close();
            delete m_FTPConnection;
            m_FTPConnection = NULL;
      }
      m_InetSession.Close();
      return bFoundMyFile;
}

CBatchFTP::CBatchFTP() : m_InetSession("My Application",
                                                         1,
                                                         INTERNET_OPEN_TYPE_PRECONFIG,
                                                         NULL,
                                       NULL,
                                                         0), m_FTPConnection(NULL),
                                                         m_PortNumber(21)
{
}

CBatchFTP::CBatchFTP(int PortNumber) : m_InetSession("My Application",
                                                         1,
                                                         INTERNET_OPEN_TYPE_PRECONFIG,
                                                         NULL,
                                       NULL,
                                                         0), m_FTPConnection(NULL),
                                                         m_PortNumber(PortNumber)
{
}

CBatchFTP::~CBatchFTP()
{
      if (m_FTPConnection)
      {
            m_FTPConnection->Close();
            delete m_FTPConnection;
      }
      m_InetSession.Close();
}

Call to the CBatchFtp class is as follows.

CBatchFTP MyFtpClient;
bool bWhatHappened = false;

bWhatHappened = batchFTP.ExportFiles(FTPServer, UserID, Pwd, FileName1, LocalPath, RemotePath,false);

if ( bWhatHappened)
{
    bWhatHappened = batchFTP.SearchFileInServer(FTPServer, UserID, Pwd, FileName1, RemotePath);
}

Your answer will be of great help.

Sindbad


0
Comment
Question by:sindbad
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
4 Comments
 
LVL 1

Expert Comment

by:MRNMurthy
ID: 6482828
Hi,

I will go through ur code & I will try recreate the problem & work that. Pls give me some time.

From

MRN Murthy
0
 
LVL 4

Accepted Solution

by:
mandhjo earned 200 total points
ID: 6482837
This may be really simple, but I see that you are closing the m_InetSession variable after you do an operation.  I think you either (1) only want to close that in the destructor of the object that contains it or (2) open the m_InetSession object every time you try to get an FTP connection.

Look into that and let me know how it goes.
0
 

Author Comment

by:sindbad
ID: 6484118

Yes,

"Not" closing the CInternetSession.Close() at the end of each function, did the trick.

Sindbad
0
 
LVL 4

Expert Comment

by:mandhjo
ID: 6487680
I'm always curious with the criteria people use for grades...why a 'C'?
0

Featured Post

Moving data to the cloud? Find out if you’re ready

Before moving to the cloud, it is important to carefully define your db needs, plan for the migration & understand prod. environment. This wp explains how to define what you need from a cloud provider, plan for the migration & what putting a cloud solution into practice entails.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction: Displaying information on the statusbar.   Continuing from the third article about sudoku.   Open the project in visual studio. Status bar – let’s display the timestamp there.  We need to get the timestamp from the document s…
Introduction: Finishing the grid – keyboard support for arrow keys to manoeuvre, entering the numbers.  The PreTranslateMessage function is to be used to intercept and respond to keyboard events. Continuing from the fourth article about sudoku. …
This video will show you how to get GIT to work in Eclipse.   It will walk you through how to install the EGit plugin in eclipse and how to checkout an existing repository.
We’ve all felt that sense of false security before—locking down external access to a database or component and feeling like we’ve done all we need to do to secure company data. But that feeling is fleeting. Attacks these days can happen in many w…
Suggested Courses

656 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question