Click here to Skip to main content
15,880,469 members
Articles / Desktop Programming / MFC

Simple File Transfer Using the Network Development Kit 2.0

Rate me:
Please Sign up or sign in to vote.
4.74/5 (14 votes)
29 Dec 20062 min read 91.4K   4.7K   99  
NDK File Transfer is a simple demonstration on how to send and receive a file using the NDK 2.0.
// NDKFileTransferClientDlg.cpp : implementation file
//

#include "stdafx.h"
#include <io.h>
#include <shlwapi.h>
#include "NDKMessage.h"
#include "NDKFileTransferCommon.h"
#include "NDKFileTransferClient.h"
#include "NDKFileTransferClientDlg.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#endif

#pragma warning(disable : 4996)


// CAboutDlg dialog used for App About

class CAboutDlg : public CDialog
{
public:
	CAboutDlg();

// Dialog Data
	enum { IDD = IDD_ABOUTBOX };

	protected:
	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV support

// Implementation
protected:
	DECLARE_MESSAGE_MAP()
};

CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
}

void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
}

BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
END_MESSAGE_MAP()


// CNDKFileTransferClientDlg dialog




CNDKFileTransferClientDlg::CNDKFileTransferClientDlg(CWnd* pParent /*=NULL*/)
	: CDialog(CNDKFileTransferClientDlg::IDD, pParent)
	, m_nServerPort(0)
	, m_strDownloadPath(_T(""))
{
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
	
	m_nServerPort    = 6000;
	m_bIsDownloading = FALSE;
	m_nFileSize      = 0;

	::SHGetSpecialFolderPath(m_hWnd, m_strDownloadPath.GetBuffer(_MAX_PATH), CSIDL_DESKTOPDIRECTORY, FALSE);
	m_strDownloadPath.ReleaseBuffer();
}

void CNDKFileTransferClientDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	DDX_Control(pDX, IDC_IPADDRESS_SERVER, m_IPServer);
	DDX_Control(pDX, IDC_EDIT_SERVER_PORT, m_editServerPort);
	DDX_Text(pDX, IDC_EDIT_SERVER_PORT, m_nServerPort);
	DDV_MinMaxInt(pDX, m_nServerPort, 1, 9999);
	DDX_Control(pDX, IDC_BUTTON_CONNECT, m_buttonConnect);
	DDX_Control(pDX, IDC_BUTTON_DISCONNECT, m_buttonDisconnect);
	DDX_Control(pDX, IDC_EDIT_DOWNLOAD_PATH, m_editDownloadPath);
	DDX_Text(pDX, IDC_EDIT_DOWNLOAD_PATH, m_strDownloadPath);
	DDX_Control(pDX, IDC_BUTTON_BROWSE, m_buttonBrowse);
	DDX_Control(pDX, IDC_LIST_SERVER_FILES, m_listServerFiles);
	DDX_Control(pDX, IDC_BUTTON_DOWNLOAD_FILES, m_buttonDownload);
	DDX_Control(pDX, IDC_PROGRESS1, m_progressDownload);
}

BEGIN_MESSAGE_MAP(CNDKFileTransferClientDlg, CDialog)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	//}}AFX_MSG_MAP
	ON_BN_CLICKED(IDC_BUTTON_CONNECT, &CNDKFileTransferClientDlg::OnBnClickedButtonConnect)
	ON_BN_CLICKED(IDC_BUTTON_DISCONNECT, &CNDKFileTransferClientDlg::OnBnClickedButtonDisconnect)
	ON_BN_CLICKED(IDC_BUTTON_BROWSE, &CNDKFileTransferClientDlg::OnBnClickedButtonBrowse)
	ON_BN_CLICKED(IDC_BUTTON_DOWNLOAD_FILES, &CNDKFileTransferClientDlg::OnBnClickedButtonDownloadFiles)
	ON_BN_CLICKED(IDOK, &CNDKFileTransferClientDlg::OnBnClickedOk)
END_MESSAGE_MAP()


// CNDKFileTransferClientDlg message handlers

BOOL CNDKFileTransferClientDlg::OnInitDialog()
{
	CDialog::OnInitDialog();

	// Add "About..." menu item to system menu.

	// IDM_ABOUTBOX must be in the system command range.
	ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
	ASSERT(IDM_ABOUTBOX < 0xF000);

	CMenu* pSysMenu = GetSystemMenu(FALSE);
	if (pSysMenu != NULL)
	{
		CString strAboutMenu;
		strAboutMenu.LoadString(IDS_ABOUTBOX);
		if (!strAboutMenu.IsEmpty())
		{
			pSysMenu->AppendMenu(MF_SEPARATOR);
			pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
		}
	}

	// Set the icon for this dialog.  The framework does this automatically
	//  when the application's main window is not a dialog
	SetIcon(m_hIcon, TRUE);			// Set big icon
	SetIcon(m_hIcon, FALSE);		// Set small icon

	m_IPServer.SetAddress(128, 0, 0, 1);

	UpdateUI();

	return TRUE;  // return TRUE  unless you set the focus to a control
}

void CNDKFileTransferClientDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
	if ((nID & 0xFFF0) == IDM_ABOUTBOX)
	{
		CAboutDlg dlgAbout;
		dlgAbout.DoModal();
	}
	else
	{
		CDialog::OnSysCommand(nID, lParam);
	}
}

// If you add a minimize button to your dialog, you will need the code below
//  to draw the icon.  For MFC applications using the document/view model,
//  this is automatically done for you by the framework.

void CNDKFileTransferClientDlg::OnPaint()
{
	if (IsIconic())
	{
		CPaintDC dc(this); // device context for painting

		SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);

		// Center icon in client rectangle
		int cxIcon = GetSystemMetrics(SM_CXICON);
		int cyIcon = GetSystemMetrics(SM_CYICON);
		CRect rect;
		GetClientRect(&rect);
		int x = (rect.Width() - cxIcon + 1) / 2;
		int y = (rect.Height() - cyIcon + 1) / 2;

		// Draw the icon
		dc.DrawIcon(x, y, m_hIcon);
	}
	else
	{
		CDialog::OnPaint();
	}
}

// The system calls this function to obtain the cursor to display while the user drags
//  the minimized window.
HCURSOR CNDKFileTransferClientDlg::OnQueryDragIcon()
{
	return static_cast<HCURSOR>(m_hIcon);
}

////////////////////////////////////////////////////////////////////////////////
// NDK: overrides OnMessage, OnDisconnect.

// Called when a message is received.
void CNDKFileTransferClientDlg::OnMessage(CNDKMessage& message)
{
	switch (message.GetId())
	{
	case SERVER_FILES:
		{
			// Add the file name in the list
			for (int nFileIndex = 0; nFileIndex < message.GetNbElements(); nFileIndex++)
			{
				CString strFileName;

				message.GetAt(nFileIndex, strFileName);

				m_listServerFiles.AddString(strFileName);
			}

			UpdateUI();
		}
		break;

	case START_TRANSFERT:
		{
			message.GetAt(0, m_nFileSize);
			
			m_progressDownload.SetRange32(0, m_nFileSize);
			
			// Ask the server for the first file part
			message.SetId(REQUEST_NEXT_FILE_PART);
			SendMessageToServer(message);
		}
		break;

	case NEXT_FILE_PART:
		{
			message.GetAt(0, m_byteBuffer, m_unBufferLength);

			m_fileDownload.Write(m_byteBuffer, m_unBufferLength);

			m_progressDownload.OffsetPos(m_unBufferLength);

			// Ask the server for the first file part
			CNDKMessage requestMessage(REQUEST_NEXT_FILE_PART);
			SendMessageToServer(requestMessage);
		}
		break;

	case TRANSFERT_COMPLETED:
		m_fileDownload.Close();

		AfxMessageBox(IDS_FILE_DOWNLOADED_SUCCESSFULLY);

		UpdateUI();
		break;
	}
}

// Called whenever an unexpected disconnection occurs. The only case when
// this method isn't call is when CloseConnection is used. CloseConnection
// don't need to be called when when OnDisconnect is called.
void CNDKFileTransferClientDlg::OnDisconnect(NDKClientDisconnection disconnectionType)
{
	UINT unResId = 0;

	switch (disconnectionType)
	{
	case NDKClient_NormalDisconnection:
		unResId = IDS_DISCONNECTED;
		break;

    case NDKClient_ServerStop:
		unResId = IDS_SERVER_STOPPED;	
		break;

	case NDKClient_ErrorSendingMessage:
		unResId = IDS_ERROR_SENDING_MESSAGE;	
		break;

	case NDKClient_ErrorReceivingMessage:
		unResId = IDS_ERROR_RECEIVING_MESSAGE;	
		break;

	default:
		break;
	}

	if (unResId != 0)
		AfxMessageBox(unResId, MB_ICONSTOP);

	if (m_bIsDownloading)
	{
		m_fileDownload.Close();

		m_bIsDownloading = FALSE;

		m_progressDownload.SetPos(0);
	}

	m_listServerFiles.ResetContent();

	UpdateUI();
}


void CNDKFileTransferClientDlg::OnBnClickedButtonConnect()
{
	if (UpdateData(TRUE))
	{
		CString strServerIP;
		BYTE nField0 = 0;
		BYTE nField1 = 0;
		BYTE nField2 = 0;
		BYTE nField3 = 0;

		m_IPServer.GetAddress(nField0, nField1, nField2, nField3);
		strServerIP.Format(_T("%d.%d.%d.%d"), nField0, nField1, nField2, nField3);

		if (OpenConnection(strServerIP, m_nServerPort))
			UpdateUI();
		else
			AfxMessageBox(IDS_CANNOT_CONNECT_TO_SERVER, MB_ICONSTOP);
	}
}

void CNDKFileTransferClientDlg::OnBnClickedButtonDisconnect()
{
	if (UpdateData(TRUE))
	{
		if (m_bIsDownloading)
		{
			if (AfxMessageBox(IDS_WANT_TO_DISCONNECT, MB_ICONQUESTION | MB_YESNO) == IDYES)
				CloseConnection();
		}
		else
		{
			CloseConnection();
		}

		m_listServerFiles.ResetContent();

		UpdateUI();
	}
}

void CNDKFileTransferClientDlg::OnBnClickedButtonBrowse()
{
	::CoInitialize(NULL);

	LPMALLOC pMalloc = NULL;
	::SHGetMalloc(&pMalloc);
	
	if (pMalloc != NULL)
	{
		CString    strPath;
		BROWSEINFO browseInfo;	

		::ZeroMemory(&browseInfo, sizeof(browseInfo));

		browseInfo.hwndOwner      = GetSafeHwnd();
		browseInfo.pszDisplayName = CStrBuf(strPath, _MAX_PATH);
		browseInfo.ulFlags        = BIF_DONTGOBELOWDOMAIN | BIF_RETURNONLYFSDIRS | BIF_NEWDIALOGSTYLE;

		LPITEMIDLIST pItemList = ::SHBrowseForFolder(&browseInfo);

		if (pItemList != NULL)
		{
			::SHGetPathFromIDList(pItemList, CStrBuf(m_strDownloadPath, _MAX_PATH));
			pMalloc->Free(pItemList);

			UpdateData(FALSE);
		}
	}

	::CoUninitialize();
}

void CNDKFileTransferClientDlg::OnBnClickedButtonDownloadFiles()
{
	if (UpdateData(TRUE))
	{
		int nCurSel = m_listServerFiles.GetCurSel();

		if (nCurSel != LB_ERR)
		{
			// Get the selected file to download
			CString strFileName;
			m_listServerFiles.GetText(m_listServerFiles.GetCurSel(), strFileName);

			// Create the download directory if it is not created
			if (_access(m_strDownloadPath, 0) != 0)
				CreateDirectory(m_strDownloadPath, NULL);

			// Retrieve the file name with the extension
			char szFileName[_MAX_FNAME];
			char szExtension[_MAX_EXT];

			_splitpath(strFileName, NULL, NULL, szFileName, szExtension);
			
			CString strFileNameToCreate;
			::PathCombine(strFileNameToCreate.GetBuffer(_MAX_PATH), m_strDownloadPath, CString(szFileName) + szExtension);
			strFileNameToCreate.ReleaseBuffer();

			// Open the file
			if (m_fileDownload.Open(strFileNameToCreate, CFile::modeCreate | CFile::modeWrite))
			{
				// Ask the server to start the download
				CNDKMessage message(REQUEST_FILE);
				message.Add(strFileName);

				SendMessageToServer(message);

				m_bIsDownloading = TRUE;

				UpdateUI();
			}
			else
			{
				AfxMessageBox(IDS_ERROR_CREATING_FILE, MB_ICONSTOP);
			}
		}
		else
		{
			AfxMessageBox(IDS_SELECT_FILE);
		}
	}
}

void CNDKFileTransferClientDlg::OnBnClickedOk()
{
	if (m_bIsDownloading)
	{
		if (AfxMessageBox(IDS_WANT_TO_EXIT, MB_ICONQUESTION | MB_YESNO) == IDYES)
		{
			CloseConnection();

			CDialog::OnOK();
		}
	}
	else
	{
		CloseConnection();

		CDialog::OnOK();
	}
}

void CNDKFileTransferClientDlg::UpdateUI()
{
	BOOL bIsConnected = IsConnected();

	m_IPServer.EnableWindow(!bIsConnected);
	m_editServerPort.EnableWindow(!bIsConnected);
	m_buttonConnect.EnableWindow(!bIsConnected);
	m_buttonDisconnect.EnableWindow(bIsConnected);
	m_buttonBrowse.EnableWindow(!bIsConnected);
	m_listServerFiles.EnableWindow(bIsConnected && !m_bIsDownloading);
	m_buttonDownload.EnableWindow(bIsConnected && (m_listServerFiles.GetCount() > 0) && !m_bIsDownloading);
	m_progressDownload.EnableWindow(bIsConnected && m_bIsDownloading);
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Software Developer (Senior) Mirego
Canada Canada
My name is Sébastien Lachance.

I love C# developing Windows Phone and Windows 8 applications.

When I’m not in front of a computer, my hobbies include playing bridge, poker and other card games, biking, reading technology news.

Comments and Discussions