WinINet


WinINet (Windows Internet)

This API is a collection of high-level functions to use: FTP, HTTP and Gopher.
Esta API es una colección de funciones de alto nivel para usar: FTP, HTTP y Gopher.

Problem 1
Create a Wintempla Dialog application called Netest to test WinINet.
Cree una aplicación de Diálogo de Wintempla llamada Netest para probar WinINet.

Step A
Edit the stdafx.h by including the "Wininet.h" header file and by linking with "Wininet.lib" as shown. Do NOT activate sockets for this exercise.

stdafx.h
...
//_________________________________________ Sockets
//#define WIN_SOCKETS_SUPPORT
...
#include "Wintempla.h"
#include "WintemplaWin.h"
using namespace std;

#include "Wininet.h"
#pragma comment(lib, "Wininet.lib")
...


Step B
Edit the Netext.cpp file as shown.

Netest.cpp
...

void Netest::Window_Open(Win::Event& e)
{
     HINTERNET hInternetSession = ::InternetOpen(L"Netest", INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, 0);
     if (hInternetSession == NULL)
     {
          Sys::DisplayLastError(hWnd, L"InternetOpen");
          return;
     }

     HINTERNET hHttpSession = ::InternetConnect(hInternetSession, L"www.google.com", 80, 0, 0, INTERNET_SERVICE_HTTP, 0, NULL);
     if (hHttpSession == NULL)
     {
          Sys::DisplayLastError(hWnd, L"InternetConnect");
          ::InternetCloseHandle(hInternetSession);
          return;
     }

     //____________________________________________________________________________________ HTTP REQUEST
     const wchar_t* acceptTypes[] ={L"text/*", NULL};
     HINTERNET hHttpRequest = ::HttpOpenRequest(hHttpSession, L"GET", L"\\", 0, 0, acceptTypes, INTERNET_FLAG_RELOAD, 0);
     if (hHttpRequest == NULL)
     {
          Sys::DisplayLastError(hWnd, L"HttpOpenRequest");
          ::InternetCloseHandle(hHttpSession);
          ::InternetCloseHandle(hInternetSession);
          return;
     }
     wchar_t* headers = L"Content-Type: text/html";
     char requestBody[1024];
     requestBody[0] = '\0';
     DWORD bodySize = 0;
     if (::HttpSendRequest(hHttpRequest, headers, (DWORD)wcslen(headers), requestBody, bodySize) == NULL)
     {
          Sys::DisplayLastError(hWnd, L"HttpSendRequest");
          ::InternetCloseHandle(hHttpSession);
          ::InternetCloseHandle(hInternetSession);
          return;
     }
     //____________________________________________________________________________________ AUTHENTICATION METHOD 1
     //DWORD errorCode = hHttpRequest ? ERROR_SUCCESS : GetLastError();
     //DWORD dwError = ::InternetErrorDlg(hWnd, hHttpRequest, errorCode,
     //     FLAGS_ERROR_UI_FILTER_FOR_ERRORS | FLAGS_ERROR_UI_FLAGS_CHANGE_OPTIONS |
     //     FLAGS_ERROR_UI_FLAGS_GENERATE_DATA, NULL);
     //if (dwError == ERROR_INTERNET_FORCE_RETRY) // resend >>
     //____________________________________________________________________________________ AUTHENTICATION METHOD 2
     //DWORD status;
     //DWORD statusSize = sizeof(DWORD);
     //::HttpQueryInfo(hHttpRequest, HTTP_QUERY_FLAG_NUMBER | HTTP_QUERY_STATUS_CODE, &status, &statusSize, NULL);
     //switch (status)
     //{
     //case HTTP_STATUS_PROXY_AUTH_REQ: // PROXY AUTHENTICATION
     //     ::InternetSetOption(hHttpRequest, INTERNET_OPTION_PROXY_USERNAME, username, wcslen(username)+1);
     //     ::InternetSetOption(hHttpRequest, INTERNET_OPTION_PROXY_PASSWORD, password, wcslen(password)+1);
     //     // resend >>
     //     break;
     //case HTTP_STATUS_DENIED: // SERVER AUTHENTICATION
     //     InternetSetOption(hHttpRequest, INTERNET_OPTION_USERNAME, username, (DWORD)(wcslen(username)+1));
     //     InternetSetOption(hHttpRequest, INTERNET_OPTION_PASSWORD, password, (DWORD)(wcslen(password)+1));
     //     // resend >>
     //     break;
     //}
     //____________________________________________________________________________________ HTTP RESPONSE
     DWORD dwRead=0;
     char responseBody[1024];
     string response;
     while (::InternetReadFile(hHttpRequest, responseBody, sizeof(responseBody)-1, &dwRead) && dwRead != 0)
     {
          response.append(responseBody, dwRead);
     }
     wstring wresponse;
     Sys::Convert::StringToWstring(response, wresponse);
     tbxOutput.Text = wresponse;
     //__________________________________________________________________________________ CLEAN UP
     if (hHttpRequest != NULL) ::InternetCloseHandle(hHttpRequest);
     if (hHttpSession != NULL) ::InternetCloseHandle(hHttpSession);
     if (hInternetSession != NULL) ::InternetCloseHandle(hInternetSession);
}


NetestRun

Tip
You may select the text from the output textbox to copy it to the clipboard. You may paste this text in notepad and save the file as main.htm (when saving the file please select the UNICODE encoding). As you can see, Wininet handles all HTTP details including redirection.
Usted puede seleccionar el texto desde la caja de texto de salida para copiarlo al portapapeles. Usted puede pegar este texto en el block de notas para guardar el archivo como main.htm (cuando guarde el archivo seleccione la codificación de UNICODE). Como usted puede ver, Wininet se encarga de todos los detalles de HTTP incluyendo la redirección.

MainHtm

Tip
In the previous problem, it is necessary to call ::InternetCloseHandle when the handle is not longer necessary. It is possible to call automatically this function from the class destructor, if a class is created.
En el problema previo, es necesario llamar ::InternetCloseHandle cuando el handle ya no se necesita. Es posible llamar está función automáticamente desde el destructor de la clase, si se crea una clase.

Problem 2
Repeat the previous problem using the Wintempla classes to simplify the code. Called your project NetestX.
Repita el problema anterior usando las clases de Wintempla para simplicar el código. Llamé a su proyecto NetestX.

Step A
Edit the stdafx.h file by removing the comments from the definition from WIN_WININET. Do NOT activate sockets for this exercise.
Edite el archivo stdafx.h removiendo los comentarios de la definición de WIN_WININET. NO active los sockets para este ejercicio.

stdafx.h
...
//_________________________________________ Sockets & Cryptography
//#define WIN_SOCKETS_SUPPORT
//_________________________________________ DirectX
//#define WIN_DIRECTX
//_________________________________________ Cryptography
//#define WIN_CRYPTOGRAPHY
//_________________________________________ WinHTTP
//#define WIN_WINHTTP
//_________________________________________ WinINet
#define WIN_WININET
...


Step B
Edit the NetestX.cpp file as shown.

NetestX.cpp
...
void NetestX::Window_Open(Win::Event& e)
{
     Sys::InternetConnection internetConnection;
     if (internetConnection.Open() == false)
     {
          Sys::DisplayLastError(hWnd, L"Sys::InternetConnection::Open");
          return;
     }
     Sys::HttpConnection httpConnection;
     if (httpConnection.Open(internetConnection, L"www.google.com", 80, 0, 0) == false)
     {
          Sys::DisplayLastError(hWnd, L"Sys::HttpConnection::Open");
          return;
     }
     //____________________________________________________________________________________ HTTP REQUEST
     const wchar_t* acceptTypes[] ={L"text/*", NULL};
     if (httpConnection.RequestSetup(L"GET", L"\\", L"HTTP/1.1", NULL, acceptTypes, INTERNET_FLAG_RELOAD, 0) == false)
     {
          Sys::DisplayLastError(hWnd, L"httpConnection.RequestSetup");
          return;
     }
     wchar_t* headers = L"Content-Type: text/html";
     char requestBody[1024];
     requestBody[0] = '\0';
     DWORD bodySize = 0;
     if (httpConnection.SendRequest(headers, wcslen(headers), requestBody, bodySize) == false)
     {
          Sys::DisplayLastError(hWnd, L"httpConnection.SendRequest");
          return;
     }
     //____________________________________________________________________________________ HTTP RESPONSE
     DWORD dwRead=0;
     char responseBody[1024];
     string response;
     while (httpConnection.Read(responseBody, sizeof(responseBody)-1, dwRead) && dwRead != 0)
     {
          response.append(responseBody, dwRead);
     }
     wstring wresponse;
     Sys::Convert::StringToWstring(response, wresponse);
     tbxOutput.Text = wresponse;
}


Problem 3
Create a Wintempla Dialog Application called ClientCalcINet to create the Client Calculator from Wintempla > Web > Web Services . In this case, we will use WinINet instead of sockets.
Cree una Aplicación de Diálogo de Wintempla llamada ClientCalcINet para crear la Client Calculator de Wintempla > Web > Web Services . En este caso, se usará WinINet en lugar de sockets.

ClientCalcINetRun

Step A
Edit the stdafx.h file by removing the comments from the definition from WIN_WININET. Do NOT activate sockets for this exercise.
Edite el archivo stdafx.h removiendo los comentarios de la definición de WIN_WININET. NO active los sockets para este ejercicio.

stdafx.h
...
//_________________________________________ Sockets & Cryptography
//#define WIN_SOCKETS_SUPPORT
//_________________________________________ DirectX
//#define WIN_DIRECTX
//_________________________________________ Cryptography
//#define WIN_CRYPTOGRAPHY
//_________________________________________ WinHTTP
//#define WIN_WINHTTP
//_________________________________________ WinINet
#define WIN_WININET
...


Step B
Edit the ClientCalcINet.h file as shown.
Edite el archivo ClientCalcINet.h como se muestra.

ClientCalcINet.h
#pragma once //______________________________________ ClientCalcINet.h
#include "Resource.h"
class ClientCalcINet: public Win::Dialog
{
public:
     ClientCalcINet()
     {
     }
     ~ClientCalcINet()
     {
     }
     Sys::SoapEnvelope soapEnvelope;
     ...
};


Step C
Edit the ClientCalcINet.cpp file as shown.
Edite el archivo ClientCalcINet.cpp como se muestra.

ClientCalcINet.cpp
...

void ClientCalcINet::Window_Open(Win::Event& e)
{
     //______________________________________________________________ Soap Envelope setup
     soapEnvelope.ActionXmlns = L"http://www.ugto.mx/MathServer";
     soapEnvelope.ActionName = L"Addition";
     soapEnvelope.AddParameter(L"x", L"0");
     soapEnvelope.AddParameter(L"y", L"0");
     //
     radioAddition.Checked = true;
}

void ClientCalcINet::btCalculate_Click(Win::Event& e)
{
     Win::BusyCursor busyCursor(true);
     //______________________________________________________________ 1. Prepare SOAP Envelope
     soapEnvelope.SetParameterValue(L"x", tbxX.Text);
     soapEnvelope.SetParameterValue(L"y", tbxY.Text);
     soapEnvelope.ActionName = (radioAddition.Checked == true) ? L"Addition" : L"Subtraction";
     //______________________________________________________________ 2. Internet Session
     Sys::InternetConnection internetConnection;
     if (internetConnection.Open() == false)
     {
          Sys::DisplayLastError(hWnd, L"internetConnection.Open");
          return;
     }
     //______________________________________________________________ 3. HTTP Session
     Sys::HttpConnection httpConnection;
     if (httpConnection.Open(internetConnection, L"localhost", 80, NULL, NULL) == false) // Microsoft IIS
     //if (httpConnection.Open(internetConnection, L"localhost", 8080, NULL, NULL) == false) // Microsoft Visual Studio
     {
          Sys::DisplayLastError(hWnd, L"httpConnection.Open");
          return;
     }
     //______________________________________________________________ 4. HTTP REQUEST
     const wchar_t* acceptTypes[] ={L"application/soap+xml", L"text/*", NULL};
     if (httpConnection.RequestSetup(L"POST", L"/MathServer/MathServer.dll", L"HTTP/1.1", NULL, acceptTypes,INTERNET_FLAG_RELOAD, 0) == false) // Microsoft IIS
     //if (httpConnection.RequestSetup(L"POST", L"/MathServer.dll", L"HTTP/1.1", NULL, acceptTypes, INTERNET_FLAG_RELOAD, 0) == false) // // Microsoft Visual Studio
     {
          Sys::DisplayLastError(hWnd, L"HttpOpenRequest");
          return;
     }
     //httpConnection.SetOption(INTERNET_OPTION_USERNAME, username, (DWORD)(wcslen(username)+1));
     //httpConnection.SetOption(INTERNET_OPTION_PASSWORD, password, (DWORD)(wcslen(password)+1));
     wchar_t* header = L"Content-Type: application/soap+xml;charset=utf-8\r\nHost: localhost";
     string body;
     soapEnvelope.GetXmlText(body);
     if (httpConnection.SendRequest(header, (DWORD)wcslen(header), (LPVOID)body.c_str(), (DWORD)body.length()) == FALSE)
     {
          Sys::DisplayLastError(hWnd, L"HttpSendRequest");
          return;
     }
     //_______________________________________________________________ 5. HTTP RESPONSE
     DWORD dwRead = 0;
     char responseBody[1024];
     string response;
     while (httpConnection.Read(responseBody, sizeof(responseBody)-1, dwRead) && dwRead != 0)
     {
          response.append(responseBody, dwRead);
     }
     if (response.empty())
     {
          this->MessageBox(L"The HTTP response is empty", L"ClientCalcINet", MB_OK | MB_ICONERROR);
     }
     //________________________________________________________________ 6. Extract Soap Envelope
     Sys::SoapEnvelope soapResult;
     const wchar_t* error = soapResult.CreateFromUtf8String(response.c_str());
     if (error != NULL)
     {
          this->MessageBox(error, L"Error Extract Soap Envelop", MB_OK | MB_ICONERROR);
          return;
     }
     //_________________________________________________________________ 7. Display result
     wstring result;
     soapResult.GetParameterValue(L"result", result);
     tbxResult.Text = result;
}


FTP

The File Transfer Protocol is used to move files from a FTP Server and a client. Microsoft IIS is the Web Server Software provided by Microsoft. Additionally, Microsoft IIS can be configured to work as an FTP Server, you may search YouTube to learn how to setup Microsoft IIS as an FTP Server. FTP provides commands to manipulate folders and files in the client and the server. There are many public FTP site, see: http://www.ftp-sites.org/. The following is a list of some FTP functions provided by WinINet:
  • FtpCreateDirectoy
  • FtpRemoveDirectoy
  • FtpSetCurrentDirectoy
  • FtpGetCurrentDirectoy
  • FtpDeleteFile
  • FtpRenameFile
  • FtpFindFirstFile
  • InternetFindNextFile

El Protocolo de Transferencia de Archivos es usado para mover archivos desde un Servidor de FTP y un client. Microsoft IIS es el Software para hacer un Servidor Web de Microsoft. Adicionalmente, Microsoft IIS se puede configurar para trabajar como un Servidor de FTP, usted puede buscar en YouTube para aprender a como configurar un Servidor de FTP usando Microsoft IIS. FTP proporciona comandos para manipular carpetas y archivos en el cliente y en el servidor. Hay muchos sitios FTP públicos, sea: http://www.ftp-sites.org/. La siguiente es una lista de algunas de las funciones de FTP proporcionadas por WinINet:
  • FtpCreateDirectory
  • FtpRemoveDirectory
  • FtpSetCurrentDirectory
  • FtpGetCurrentDirectory
  • FtpDeleteFile
  • FtpRenameFile
  • FtpFindFirstFile
  • InternetFindNextFile

Problem 4
Create a Wintempla Dialog Application called DownClient to display the list of files in a FTP server specific folder. The application will download the first file in the list. You will need a textbox (with the multiline property) to display the list of files.
Cree una Aplicación de Diálogo de Wintempla llamada DownClient para mostrar la lista de archivos de un Servidor de FTP en una carpeta específica. La aplicación descargará el primer archivo en la lista. Usted necesitará una caja de texto (con la propiedad de multilinea) para mostrar la lista de archivos.

DownClientRun

DownClientFolder

stdafx.h
...
//_________________________________________ Sockets & Cryptography
//#define WIN_SOCKETS_SUPPORT
//_________________________________________ DirectX
//#define WIN_DIRECTX
//_________________________________________ Cryptography
//#define WIN_CRYPTOGRAPHY
//_________________________________________ WinHTTP
//#define WIN_WINHTTP
//_________________________________________ WinINet
#define WIN_WININET
...


Step B
Edit the DownClient.cpp file as shown.
Edite el archivo DownClient.cpp como se muestra.

DownClient.cpp
...
void DownClient::Window_Open(Win::Event& e)
{
     const wchar_t* ftp_server = L"ctan.tug.org";
     const wchar_t* remote_folder = L"tex-archive/macros/latex/";
     const wchar_t* username = NULL;
     const wchar_t* password = NULL;

     //__________________________________________________________________________ 1. InternetOpen
     Sys::InternetConnection internetConnection;
     if (internetConnection.Open() == false)
     {
          Sys::DisplayLastError(hWnd, L"internetConnection.Open");
          return;
     }
     //___________________________________________________________________________ 2. FtpSession
     Sys::FtpConnection ftpConnection;
     if (ftpConnection.Open(internetConnection, ftp_server, 21, username, password) == false)
     {
          Sys::DisplayLastError(hWnd, L"ftpConnection.Open");
          return;
     }
     //___________________________________________________________________________ 3. Change Remote Directory
     if (ftpConnection.SetCurrentDir(remote_folder) == false)
     {
          Sys::DisplayLastError(hWnd, L"ftpConnection.SetCurrentDir");
          return;
     }
     //___________________________________________________________________________ 4. Get and Display File List
     WIN32_FIND_DATA win32FindData;
     if (ftpConnection.FindFirstFILE(L"*.*", win32FindData, 0, 0) == false)
     {
          Sys::DisplayLastError(hWnd, L"ftpConnection.FindFirstFILE");
          return;
     }
     bool download = false;

     do
     {
          tbxOutput.Text += win32FindData.cFileName;
          tbxOutput.Text += L"\r\n";
          //
          if ((win32FindData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0 && download == false)
          {
               ftpConnection.GetFILE(win32FindData.cFileName, win32FindData.cFileName, true, FILE_ATTRIBUTE_NORMAL, FTP_TRANSFER_TYPE_BINARY, 0);
               download = true;
          }
     }
     while(ftpConnection.FindNextFILE(win32FindData) == true);
}


© Copyright 2000-2019 Wintempla selo. All Rights Reserved. Sep 05 2019. Home