Completed all unit tests and function changes for all functions in WinInet.dll

pull/83/head
David Hall 2019-09-20 13:04:38 -06:00
parent 3537b1f8f2
commit a7af7ccbd4
4 changed files with 8516 additions and 165 deletions

View File

@ -8979,5 +8979,153 @@ namespace Vanara.PInvoke
/// <summary>An error occurred while accessing the WBEM data store.</summary>
public const int PDH_WBEM_ERROR = unchecked((int)0xC0000BDA);
/// <summary>Returned by WinHttpGetProxyForUrl when a proxy for the specified URL cannot be located.</summary>
public const int ERROR_WINHTTP_AUTO_PROXY_SERVICE_ERROR = 12178;
/// <summary>Returned by WinHttpDetectAutoProxyConfigUrl if WinHTTP was unable to discover the URL of the Proxy Auto-Configuration (PAC) file.</summary>
public const int ERROR_WINHTTP_AUTODETECTION_FAILED = 12180;
/// <summary>An error occurred executing the script code in the Proxy Auto-Configuration (PAC) file.</summary>
public const int ERROR_WINHTTP_BAD_AUTO_PROXY_SCRIPT = 12166;
/// <summary>Returned by the HttpRequest object if a specified option cannot be requested after the Open method has been called.</summary>
public const int ERROR_WINHTTP_CANNOT_CALL_AFTER_OPEN = 12103;
/// <summary>Returned by the HttpRequest object if a requested operation cannot be performed after calling the Send method.</summary>
public const int ERROR_WINHTTP_CANNOT_CALL_AFTER_SEND = 12102;
/// <summary>Returned by the HttpRequest object if a requested operation cannot be performed before calling the Open method.</summary>
public const int ERROR_WINHTTP_CANNOT_CALL_BEFORE_OPEN = 12100;
/// <summary>Returned by the HttpRequest object if a requested operation cannot be performed before calling the Send method.</summary>
public const int ERROR_WINHTTP_CANNOT_CALL_BEFORE_SEND = 12101;
/// <summary>Returned if connection to the server failed.</summary>
public const int ERROR_WINHTTP_CANNOT_CONNECT = 12029;
/// <summary>The server requires SSL client Authentication. The application retrieves the list of certificate issuers by calling WinHttpQueryOption with the WINHTTP_OPTION_CLIENT_CERT_ISSUER_LIST option. For more information, see the WINHTTP_OPTION_CLIENT_CERT_ISSUER_LIST option.
/// <para>If the server requests the client certificate, but does not require it, the application can alternately call WinHttpSetOption with the WINHTTP_OPTION_CLIENT_CERT_CONTEXT option. In this case, the application specifies the WINHTTP_NO_CLIENT_CERT_CONTEXT macro in the lpBuffer parameter of WinHttpSetOption. For more information, see the WINHTTP_OPTION_CLIENT_CERT_CONTEXT option.</para>
/// <para>Windows Server 2003 with SP1 and Windows XP with SP2: This error is not supported.</para></summary>
public const int ERROR_WINHTTP_CLIENT_AUTH_CERT_NEEDED = 12044;
/// <summary>The application does not have the required privileges to access the private key associated with the client certificate.
/// <para>Windows Server 2003 with SP1 and Windows XP with SP2: This error is not supported.</para></summary>
public const int ERROR_WINHTTP_CLIENT_CERT_NO_ACCESS_PRIVATE_KEY = 12186;
/// <summary>The context for the SSL client certificate does not have a private key associated with it. The client certificate may have been imported to the computer without the private key.
/// <para>Windows Server 2003 with SP1 and Windows XP with SP2: This error is not supported.</para></summary>
public const int ERROR_WINHTTP_CLIENT_CERT_NO_PRIVATE_KEY = 12185;
/// <summary>Returned by WinHttpReceiveResponse when an overflow condition is encountered in the course of parsing chunked encoding.</summary>
public const int ERROR_WINHTTP_CHUNKED_ENCODING_HEADER_SIZE_OVERFLOW = 12183;
/// <summary>The connection with the server has been reset or terminated, or an incompatible SSL protocol was encountered. For example, WinHTTP version 5.1 does not support SSL2 unless the client specifically enables it.</summary>
public const int ERROR_WINHTTP_CONNECTION_ERROR = 12030;
/// <summary>Obsolete; no longer used.</summary>
public const int ERROR_WINHTTP_HEADER_ALREADY_EXISTS = 12155;
/// <summary>Returned by WinHttpReceiveResponse when a larger number of headers were present in a response than WinHTTP could receive.</summary>
public const int ERROR_WINHTTP_HEADER_COUNT_EXCEEDED = 12181;
/// <summary>The requested header cannot be located.</summary>
public const int ERROR_WINHTTP_HEADER_NOT_FOUND = 12150;
/// <summary>Returned by WinHttpReceiveResponse when the size of headers received exceeds the limit for the request handle.</summary>
public const int ERROR_WINHTTP_HEADER_SIZE_OVERFLOW = 12182;
/// <summary>The requested operation cannot be carried out because the handle supplied is not in the correct state.</summary>
public const int ERROR_WINHTTP_INCORRECT_HANDLE_STATE = 12019;
/// <summary>The type of handle supplied is incorrect for this operation.</summary>
public const int ERROR_WINHTTP_INCORRECT_HANDLE_TYPE = 12018;
/// <summary>An internal error has occurred.</summary>
public const int ERROR_WINHTTP_INTERNAL_ERROR = 12004;
/// <summary>A request to WinHttpQueryOption or WinHttpSetOption specified an invalid option value.</summary>
public const int ERROR_WINHTTP_INVALID_OPTION = 12009;
/// <summary>Obsolete; no longer used.</summary>
public const int ERROR_WINHTTP_INVALID_QUERY_REQUEST = 12154;
/// <summary>The server response cannot be parsed.</summary>
public const int ERROR_WINHTTP_INVALID_SERVER_RESPONSE = 12152;
/// <summary>The URL is not valid.</summary>
public const int ERROR_WINHTTP_INVALID_URL = 12005;
/// <summary>The login attempt failed. When this error is encountered, the request handle should be closed with WinHttpCloseHandle. A new request handle must be created before retrying the function that originally produced this error.</summary>
public const int ERROR_WINHTTP_LOGIN_FAILURE = 12015;
/// <summary>The server name cannot be resolved.</summary>
public const int ERROR_WINHTTP_NAME_NOT_RESOLVED = 12007;
/// <summary>Obsolete; no longer used.</summary>
public const int ERROR_WINHTTP_NOT_INITIALIZED = 12172;
/// <summary>The operation was canceled, usually because the handle on which the request was operating was closed before the operation completed.</summary>
public const int ERROR_WINHTTP_OPERATION_CANCELLED = 12017;
/// <summary>The requested option cannot be set, only queried.</summary>
public const int ERROR_WINHTTP_OPTION_NOT_SETTABLE = 12011;
/// <summary>Obsolete; no longer used.</summary>
public const int ERROR_WINHTTP_OUT_OF_HANDLES = 12001;
/// <summary>The redirection failed because either the scheme changed or all attempts made to redirect failed (default is five attempts).</summary>
public const int ERROR_WINHTTP_REDIRECT_FAILED = 12156;
/// <summary>The WinHTTP function failed. The desired function can be retried on the same request handle.</summary>
public const int ERROR_WINHTTP_RESEND_REQUEST = 12032;
/// <summary>Returned when an incoming response exceeds an internal WinHTTP size limit.</summary>
public const int ERROR_WINHTTP_RESPONSE_DRAIN_OVERFLOW = 12184;
/// <summary>An error was encountered while executing a script.</summary>
public const int ERROR_WINHTTP_SCRIPT_EXECUTION_ERROR = 12177;
/// <summary>Returned when a certificate CN name does not match the passed value (equivalent to a CERT_E_CN_NO_MATCH error).</summary>
public const int ERROR_WINHTTP_SECURE_CERT_CN_INVALID = 12038;
/// <summary>Indicates that a required certificate is not within its validity period when verifying against the current system clock or the timestamp in the signed file, or that the validity periods of the certification chain do not nest correctly (equivalent to a CERT_E_EXPIRED or a CERT_E_VALIDITYPERIODNESTING error).</summary>
public const int ERROR_WINHTTP_SECURE_CERT_DATE_INVALID = 12037;
/// <summary>Indicates that revocation cannot be checked because the revocation server was offline (equivalent to CRYPT_E_REVOCATION_OFFLINE).</summary>
public const int ERROR_WINHTTP_SECURE_CERT_REV_FAILED = 12057;
/// <summary>Indicates that a certificate has been revoked (equivalent to CRYPT_E_REVOKED).</summary>
public const int ERROR_WINHTTP_SECURE_CERT_REVOKED = 12170;
/// <summary>Indicates that a certificate is not valid for the requested usage (equivalent to CERT_E_WRONG_USAGE).</summary>
public const int ERROR_WINHTTP_SECURE_CERT_WRONG_USAGE = 12179;
/// <summary>Indicates that an error occurred having to do with a secure channel (equivalent to error codes that begin with "SEC_E_" and "SEC_I_" listed in the "winerror.h" header file).</summary>
public const int ERROR_WINHTTP_SECURE_CHANNEL_ERROR = 12157;
/// <summary>One or more errors were found in the Secure Sockets Layer (SSL) certificate sent by the server. To determine what type of error was encountered, check for a WINHTTP_CALLBACK_STATUS_SECURE_FAILURE notification in a status callback function. For more information, see WINHTTP_STATUS_CALLBACK.</summary>
public const int ERROR_WINHTTP_SECURE_FAILURE = 12175;
/// <summary>Indicates that a certificate chain was processed, but terminated in a root certificate that is not trusted by the trust provider (equivalent to CERT_E_UNTRUSTEDROOT).</summary>
public const int ERROR_WINHTTP_SECURE_INVALID_CA = 12045;
/// <summary>Indicates that a certificate is invalid (equivalent to errors such as CERT_E_ROLE, CERT_E_PATHLENCONST, CERT_E_CRITICAL, CERT_E_PURPOSE, CERT_E_ISSUERCHAINING, CERT_E_MALFORMED and CERT_E_CHAINING).</summary>
public const int ERROR_WINHTTP_SECURE_INVALID_CERT = 12169;
/// <summary>The WinHTTP function support is being shut down or unloaded.</summary>
public const int ERROR_WINHTTP_SHUTDOWN = 12012;
/// <summary>The request has timed out.
/// <para>This error can be returned as a result of TCP/IP time-out behavior, regardless of time-out values set in Windows HTTP Services.</para></summary>
public const int ERROR_WINHTTP_TIMEOUT = 12002;
/// <summary>The PAC file cannot be downloaded. For example, the server referenced by the PAC URL may not have been reachable, or the server returned a 404 NOT FOUND response.</summary>
public const int ERROR_WINHTTP_UNABLE_TO_DOWNLOAD_SCRIPT = 12167;
/// <summary>The script type is not supported.</summary>
public const int ERROR_WINHTTP_UNHANDLED_SCRIPT_TYPE = 12176;
/// <summary>The URL specified a scheme other than "http:" or "https:".</summary>
public const int ERROR_WINHTTP_UNRECOGNIZED_SCHEME = 12006;
}
}

File diff suppressed because it is too large Load Diff

View File

@ -9,9 +9,10 @@
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>Vanara.PInvoke.Tests</RootNamespace>
<AssemblyName>UnitTest.PInvoke.WinINet</AssemblyName>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
<TargetFrameworkVersion>v4.7.2</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<LangVersion>latest</LangVersion>
<TargetFrameworkProfile />
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
@ -57,6 +58,10 @@
<Project>{e8a0c4df-541c-4435-937b-2865cd61bb17}</Project>
<Name>Vanara.PInvoke.WinINet</Name>
</ProjectReference>
<ProjectReference Include="..\..\CSharpRunner\Shared.csproj">
<Project>{a96cff10-0967-429a-8700-4a86c97c5603}</Project>
<Name>Shared</Name>
</ProjectReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.

View File

@ -1,5 +1,9 @@
using NUnit.Framework;
using System;
using System.IO;
using System.Linq;
using System.Text;
using Vanara.Extensions;
using Vanara.InteropServices;
using static Vanara.PInvoke.WinINet;
@ -8,91 +12,524 @@ namespace Vanara.PInvoke.Tests
[TestFixture()]
public class WinInetTests
{
[Test()]
public void InternetOpenTest()
private const string exturl = "https://microsoft.com";
private const string host = "localhost";
private const string url = "http://" + host;
private static readonly SafeHINTERNET hOpen = InternetOpen("Test");
[Test]
public void CreateMD5SSOHashTest()
{
var hOpen = InternetOpen("Test", InternetOpenType.INTERNET_OPEN_TYPE_DIRECT, null, null, 0);
Assert.That(hOpen.IsInvalid, Is.False);
hOpen.Dispose();
Assert.That(hOpen.IsInvalid, Is.True);
var hash = new byte[35];
Assert.That(CreateMD5SSOHash("IAMACHALLENGE", null, null, hash), ResultIs.Successful); // not supported
}
[Test]
public void CreateUrlCacheContainerTest()
{
var icci = INTERNET_CACHE_CONFIG_INFO.Default;
var flags = CACHE_CONFIG_FC.CACHE_CONFIG_CONTENT_PATHS_FC | CACHE_CONFIG_FC.CACHE_CONFIG_COOKIES_PATHS_FC | CACHE_CONFIG_FC.CACHE_CONFIG_HISTORY_PATHS_FC |
CACHE_CONFIG_FC.CACHE_CONFIG_QUOTA_FC | CACHE_CONFIG_FC.CACHE_CONFIG_STICKY_CONTENT_USAGE_FC;
Assert.That(GetUrlCacheConfigInfo(ref icci, default, flags), ResultIs.Successful);
icci.WriteValues();
var path = icci.CachePaths[0].CachePath;
Assert.That(CreateUrlCacheContainer("Log", "Log:", path, 0, INTERNET_CACHE_CONTAINER.INTERNET_CACHE_CONTAINER_NOSUBDIRS), ResultIs.Successful);
Assert.That(DeleteUrlCacheContainer("Log"), ResultIs.Successful);
}
[Test]
public void CreateUrlCacheEntryTest()
{
using (var tmp = new TempFile())
{
var url = "temp://" + Guid.NewGuid().ToString("N");
var sb = new StringBuilder(512);
Assert.That(CreateUrlCacheEntry(url, 0, "tmp", sb), ResultIs.Successful);
try
{
System.IO.File.Copy(tmp.FullName, sb.ToString(), true);
Assert.That(CommitUrlCacheEntry(url, sb.ToString()), ResultIs.Successful);
Assert.That(FindUrlCacheEntries().Where(e => e.lpszSourceUrlName == url), Is.Not.Empty);
using (var mem = new SafeHGlobalHandle(4096))
{
uint sz = mem.Size;
Assert.That(GetUrlCacheEntryInfo(url, mem, ref sz), ResultIs.Successful);
var ei = mem.ToStructure<INTERNET_CACHE_ENTRY_INFO>();
new INTERNET_CACHE_ENTRY_INFO_MGD(ei).WriteValues();
ei.LastModifiedTime = DateTime.Now.ToFileTimeStruct();
Assert.That(SetUrlCacheEntryInfo(url, ei, CACHE_ENTRY_FC.CACHE_ENTRY_MODTIME_FC), ResultIs.Successful);
sz = mem.Size;
Assert.That(GetUrlCacheEntryInfoEx(url, mem, ref sz), ResultIs.Successful);
new INTERNET_CACHE_ENTRY_INFO_MGD(mem.ToStructure<INTERNET_CACHE_ENTRY_INFO>()).WriteValues();
sz = 0;
Assert.That(RetrieveUrlCacheEntryStream(url, default, ref sz, false), ResultIs.Not.ValidHandle);
using (var infomem = new SafeHGlobalHandle(sz))
{
using (var hStr = RetrieveUrlCacheEntryStream(url, infomem, ref sz, false))
{
Assert.That(hStr, ResultIs.ValidHandle);
var info = new INTERNET_CACHE_ENTRY_INFO_MGD(infomem.ToStructure<INTERNET_CACHE_ENTRY_INFO>());
info.WriteValues();
using (var buf = new SafeHGlobalHandle(info.dwSize))
{
uint bufSz = buf.Size;
Assert.That(ReadUrlCacheEntryStream(hStr, 0, buf, ref bufSz), ResultIs.Successful);
TestContext.WriteLine(buf.DangerousGetHandle().ToHexDumpString(buf.Size));
}
}
}
sz = 0;
Assert.That(RetrieveUrlCacheEntryFile(url, default, ref sz), ResultIs.Failure);
using (var infomem = new SafeHGlobalHandle(sz))
{
Assert.That(RetrieveUrlCacheEntryFile(url, infomem, ref sz), ResultIs.Successful);
new INTERNET_CACHE_ENTRY_INFO_MGD(infomem.ToStructure<INTERNET_CACHE_ENTRY_INFO>()).WriteValues();
Assert.That(UnlockUrlCacheEntryFile(url), ResultIs.Successful);
}
}
}
finally
{
Assert.That(DeleteUrlCacheEntry(url), ResultIs.Successful);
}
}
}
[Test]
public void CreateUrlCacheGroupTest()
{
long grp;
Assert.That(grp = CreateUrlCacheGroup(), ResultIs.Not.Value(0L));
try
{
Assert.That(FindUrlCacheGroups(), Contains.Item(grp));
}
finally
{
Assert.That(DeleteUrlCacheGroup(grp, CACHEGROUP_FLAG.CACHEGROUP_FLAG_FLUSHURL_ONDELETE), ResultIs.Successful);
}
}
[Test]
public void DetectAutoProxyUrlTest()
{
var sb = new StringBuilder(4096);
var sz = (uint)sb.Capacity;
Assert.That(() => DetectAutoProxyUrl(sb, sz, (PROXY_AUTO_DETECT_TYPE)3), Throws.Nothing);
}
[TestCaseSource(typeof(TestCaseSources), nameof(TestCaseSources.RemoteConnections), new object[] { true, 0b00111 })]
public void FtpCommandTest(string host, string ip, string user, string domain, string pwd)
{
Assert.That(hOpen, ResultIs.ValidHandle);
using (var hCon = InternetConnect(hOpen, ip, INTERNET_PORT.INTERNET_DEFAULT_FTP_PORT, user, pwd, InternetService.INTERNET_SERVICE_FTP, InternetApiFlags.INTERNET_FLAG_PASSIVE))
{
Assert.That(hCon, ResultIs.ValidHandle);
Assert.That(FtpCommand(hCon, true, FTP_TRANSER_TYPE.FTP_TRANSER_TYPE_BINARY, "SYST", default, out var hFtp), ResultIs.Successful);
hFtp.Dispose();
}
}
[TestCaseSource(typeof(TestCaseSources), nameof(TestCaseSources.RemoteConnections), new object[] { true, 0b00111 })]
public void FtpTest(string host, string ip, string user, string domain, string pwd)
{
const string dirName = "Temp";
const string newName = "File.bin";
Assert.That(InternetSetStatusCallback(hOpen, Callback), ResultIs.Not.Value(INTERNET_INVALID_STATUS_CALLBACK));
try
{
Assert.That(hOpen, ResultIs.ValidHandle);
using (var hCon = InternetConnect(hOpen, ip, INTERNET_PORT.INTERNET_DEFAULT_FTP_PORT, user, pwd, InternetService.INTERNET_SERVICE_FTP, InternetApiFlags.INTERNET_FLAG_PASSIVE))
{
Assert.That(hCon, ResultIs.ValidHandle);
var sb = new StringBuilder(1024);
var sz = (uint)sb.Capacity;
Assert.That(FtpGetCurrentDirectory(hCon, sb, ref sz), ResultIs.Successful);
Assert.That(FtpCreateDirectory(hCon, dirName), ResultIs.Successful);
Assert.That(FtpSetCurrentDirectory(hCon, dirName), ResultIs.Successful);
Assert.That(FtpPutFile(hCon, TestCaseSources.SmallFile, System.IO.Path.GetFileName(TestCaseSources.SmallFile), INTERNET_FLAG.INTERNET_FLAG_TRANSFER_BINARY), ResultIs.Successful);
var hFile = SafeHINTERNET.Null;
Assert.That(hFile = FtpFindFirstFile(hCon, System.IO.Path.GetFileName(TestCaseSources.SmallFile), out var fd, 0), ResultIs.ValidHandle);
Assert.That(InternetFindNextFile(hFile, out fd), ResultIs.Failure);
hFile.Dispose();
Assert.That(hFile = FtpOpenFile(hCon, System.IO.Path.GetFileName(TestCaseSources.SmallFile), ACCESS_MASK.GENERIC_READ, FTP_TRANSER_TYPE.FTP_TRANSER_TYPE_BINARY), ResultIs.ValidHandle);
uint low;
Assert.That(low = FtpGetFileSize(hFile, out var high), ResultIs.Not.Value(0U));
var fileContent = File.ReadAllBytes(TestCaseSources.ImageFile);
Assert.That(InternetWriteFile(hFile, fileContent, fileContent.Length, out var written), ResultIs.Failure);
hFile.Dispose();
Assert.That(FtpRenameFile(hCon, Path.GetFileName(TestCaseSources.SmallFile), newName), ResultIs.Successful);
using (var tmpFile = new TempFile(null))
Assert.That(FtpGetFile(hCon, newName, tmpFile.FullName, true, 0, INTERNET_FLAG.INTERNET_FLAG_TRANSFER_BINARY), ResultIs.Successful);
Assert.That(FtpDeleteFile(hCon, newName), ResultIs.Successful);
Assert.That(FtpSetCurrentDirectory(hCon, sb.ToString()), ResultIs.Successful);
Assert.That(FtpRemoveDirectory(hCon, dirName), ResultIs.Successful);
}
}
finally
{
InternetSetStatusCallback(hOpen, null);
}
void Callback(HINTERNET hInternet, IntPtr dwContext, InternetStatus dwInternetStatus, IntPtr lpvStatusInformation, uint dwStatusInformationLength)
{
System.Diagnostics.Debug.WriteLine(dwInternetStatus);
}
}
[Test]
public void HttpSendRequestExTest()
{
using (var hCon = InternetConnect(hOpen, host, dwService: InternetService.INTERNET_SERVICE_HTTP))
{
Assert.That(hCon, ResultIs.ValidHandle);
using (var hReq = HttpOpenRequest(hCon, null, "", null, ""))
{
Assert.That(hReq, ResultIs.ValidHandle);
var ibuf = INTERNET_BUFFERS.Default;
ibuf.dwBufferTotal = 4096;
Assert.That(HttpSendRequestEx(hReq, ibuf, dwContext: new IntPtr(1)), ResultIs.Successful);
Assert.That(HttpEndRequest(hReq), ResultIs.Successful);
}
}
}
[Test]
public void HttpSendRequestTest()
{
using (var hCon = InternetConnect(hOpen, host, dwService: InternetService.INTERNET_SERVICE_HTTP))
{
Assert.That(hCon, ResultIs.ValidHandle);
using (var hReq = HttpOpenRequest(hCon, null, "", null, ""))
{
Assert.That(hReq, ResultIs.ValidHandle);
Assert.That(HttpAddRequestHeaders(hReq, "Accept: text/html, application/xhtml+xml, */*\r\n", -1, HTTP_ADDREQ_FLAG.HTTP_ADDREQ_FLAG_ADD | HTTP_ADDREQ_FLAG.HTTP_ADDREQ_FLAG_REPLACE), ResultIs.Successful);
Assert.That(HttpSendRequest(hReq), ResultIs.Successful);
foreach (var e in Enum.GetValues(typeof(HTTP_QUERY)).OfType<HTTP_QUERY>().Where(v => (int)v < 0x10000000))
{
uint idx = 0;
try
{
var mem = HttpQueryInfo(hReq, e, ref idx);
TestContext.WriteLine($"{e} = {HttpQueryInfo<string>(hReq, e, ref idx)}");
}
catch (Exception ex)
{
TestContext.WriteLine($"{e} caused exception {ex.Message}");
}
}
Assert.That(InternetSetFilePointer(hReq, 0, 0, SeekOrigin.Begin), ResultIs.Successful);
using (var mem = new SafeHGlobalHandle(1024))
Assert.That(InternetReadFile(hReq, mem, mem.Size, out var read), ResultIs.Successful);
}
}
}
[Test]
public void InternetAttemptConnectTest()
{
Assert.That(InternetAttemptConnect(), ResultIs.Successful);
}
[Test]
public void InternetAutodialTest()
{
Assert.That(InternetAutodial(INTERNET_AUTODIAL.INTERNET_AUTODIAL_FORCE_ONLINE, HWND.NULL), ResultIs.Successful);
Assert.That(InternetAutodialHangup(), ResultIs.Successful);
}
[Test]
public void InternetCanonicalizeUrlTest()
{
var sb = new StringBuilder(1024);
var sz = (uint)sb.Capacity;
Assert.That(InternetCanonicalizeUrl(url + "/issstart.htm", sb, ref sz, ICU.ICU_BROWSER_MODE), ResultIs.Successful);
TestContext.Write(sb);
}
[Test]
public void InternetCheckConnectionTest()
{
Assert.That(InternetCheckConnection(exturl, FLAG_ICC.FLAG_ICC_FORCE_CONNECTION), ResultIs.Successful);
Assert.That(InternetCheckConnection(), ResultIs.Successful);
}
[Test]
public void InternetClearAllPerSiteCookieDecisionsTest()
{
Assert.That(InternetClearAllPerSiteCookieDecisions(), ResultIs.Successful);
}
[Test]
public void InternetConfirmZoneCrossingTest()
{
Assert.That(InternetConfirmZoneCrossing(HWND.NULL, url, "http://microsoft.com"), ResultIs.Successful);
}
[Test]
public void InternetConnectTest()
{
using (var hOpen = InternetOpen("Test", InternetOpenType.INTERNET_OPEN_TYPE_DIRECT, null, null, 0))
using (var hCon = InternetConnect(hOpen, host, dwService: InternetService.INTERNET_SERVICE_HTTP))
Assert.That(hCon, ResultIs.ValidHandle);
}
[Test]
public void InternetCrackUrlTest()
{
const string crkUrl = "https://docs.microsoft.com:443/en-us/windows/win32/api/wininet/ns-wininet-url_componentsa#remarks";
var comp = new URL_COMPONENTS_MGD();
Assert.That(InternetCrackUrl(crkUrl, (uint)crkUrl.Length + 1, ICU.ICU_DECODE, ref comp.GetRef()), ResultIs.Successful);
comp.WriteValues();
comp.GetRef().WriteValues();
}
[Test]
public void InternetCreateUrlTest()
{
var comps = new URL_COMPONENTS_MGD("https", "docs.microsoft.com", "/en-us/windows/win32/api/wininet/ns-wininet-url_componentsa", "#remarks", INTERNET_PORT.INTERNET_DEFAULT_HTTPS_PORT);
var sb = new StringBuilder(1024);
var sz = (uint)sb.Capacity;
Assert.That(InternetCreateUrl(ref comps.GetRef(), 0, sb, ref sz), ResultIs.Successful);
TestContext.WriteLine(sb);
}
[Test]
public void InternetDialTest()
{
Assert.That(InternetDial(HWND.NULL, null, INTERNET_DIAL.INTERNET_DIAL_UNATTENDED, out var id), ResultIs.Successful);
Assert.That(InternetHangUp(id), ResultIs.Successful);
}
[Test]
public void InternetEnumPerSiteCookieDecisionTest()
{
Assert.That(InternetSetPerSiteCookieDecision("hpe.com", InternetCookieState.COOKIE_STATE_ACCEPT), ResultIs.Successful);
Assert.That(InternetGetPerSiteCookieDecision("hpe.com", out var state), ResultIs.Successful);
Assert.That(state, Is.EqualTo(InternetCookieState.COOKIE_STATE_ACCEPT));
var sb = new StringBuilder(1024);
uint i = 0;
do
{
var hCon = InternetConnect(hOpen, "hallan-svr", 32400, null, null, InternetService.INTERNET_SERVICE_HTTP, 0, IntPtr.Zero);
Assert.That(hCon.IsInvalid, Is.False);
hCon.Dispose();
Assert.That(hCon.IsInvalid, Is.True);
var sz = (uint)sb.Capacity;
if (!InternetEnumPerSiteCookieDecision(sb, ref sz, out var dec, i))
Assert.That(Win32Error.GetLastError(), Is.EqualTo((Win32Error)Win32Error.ERROR_NO_MORE_ITEMS));
TestContext.Write($"{i}: {sb}; {dec}");
} while (i++ < 50);
}
[Test]
public void InternetErrorDlgTest()
{
using (var hCon = InternetConnect(hOpen, host, dwService: InternetService.INTERNET_SERVICE_HTTP))
{
Assert.That(hCon, ResultIs.ValidHandle);
using (var hReq = HttpOpenRequest(hCon, null, "", null, ""))
{
Assert.That(hReq, ResultIs.ValidHandle);
Assert.That(HttpSendRequest(hReq), ResultIs.Successful);
Assert.That(InternetErrorDlg(HWND.NULL, hReq, Win32Error.ERROR_INTERNET_INCORRECT_PASSWORD, FLAGS_ERROR_UI.FLAGS_ERROR_UI_FLAGS_NO_UI, IntPtr.Zero), ResultIs.Successful);
}
}
}
[Test]
public void InternetGetConnectedStateExTest()
{
var sb = new StringBuilder(1024);
Assert.That(InternetGetConnectedStateEx(out var flags, sb, (uint)sb.Capacity), ResultIs.Successful);
TestContext.Write($"{flags}; {sb}");
}
[Test]
public void InternetGetConnectedStateTest()
{
Assert.That(InternetGetConnectedState(out var flags), ResultIs.Successful);
TestContext.Write(flags);
}
[Test]
public void InternetGetCookieExTest()
{
var sb = new StringBuilder(1024);
var sz = (uint)sb.Capacity;
Assert.That(InternetGetCookieEx(exturl, null, sb, ref sz, 0), ResultIs.Successful);
TestContext.Write(sb);
Assert.That(InternetSetCookieEx(exturl, "TestOnly", "blahblahblah", 0), ResultIs.Not.Value(InternetCookieState.COOKIE_STATE_UNKNOWN));
}
[Test]
public void InternetGetCookieTest()
{
var sb = new StringBuilder(1024);
var sz = (uint)sb.Capacity;
Assert.That(InternetGetCookie(exturl, null, sb, ref sz), ResultIs.Successful);
TestContext.Write(sb);
Assert.That(InternetSetCookie(exturl, "TestOnly", "blahblahblah"), ResultIs.Successful);
}
[Test]
public void InternetGetLastResponseInfoTest()
{
var sb = new StringBuilder(1024);
var sz = (uint)sb.Capacity;
Assert.That(InternetGetLastResponseInfo(out var err, sb, ref sz), ResultIs.Successful);
}
[Test]
public void InternetGoOnlineTest()
{
Assert.That(InternetGoOnline(url, HWND.NULL), ResultIs.Successful);
}
[Test]
public void InternetInitializeAutoProxyDllTest()
{
Assert.That(InternetInitializeAutoProxyDll(), ResultIs.Successful);
}
[Test]
public void InternetLockRequestFileTest()
{
using (var hFile = InternetOpenUrl(hOpen, url, null, 0, 0))
{
Assert.That(hFile, ResultIs.ValidHandle);
Assert.That(InternetQueryDataAvailable(hFile, out var num), ResultIs.Successful);
TestContext.Write(num);
Assert.That(InternetLockRequestFile(hFile, out var hLock), ResultIs.Successful);
using (var mem = new SafeHGlobalHandle(1024))
{
var ib = INTERNET_BUFFERS.Default;
ib.dwBufferLength = mem.Size;
ib.lpvBuffer = mem;
Assert.That(InternetReadFileEx(hFile, ref ib, IRF.IRF_SYNC), ResultIs.Successful);
}
Assert.That(InternetUnlockRequestFile(hLock), ResultIs.Successful);
}
}
[Test()]
public void InternetOpenTest()
{
var hOpen2 = InternetOpen("Test", InternetOpenType.INTERNET_OPEN_TYPE_DIRECT, null, null, 0);
Assert.That(hOpen2, ResultIs.ValidHandle);
hOpen2.Dispose();
Assert.That(hOpen2.IsInvalid, Is.True);
}
[Test]
public void InternetQueryOptionTest()
{
using (var hOpen = InternetOpen("Test", InternetOpenType.INTERNET_OPEN_TYPE_DIRECT, null, null, 0))
{
var sz = sizeof(int);
var hMem = new SafeCoTaskMemHandle(sz);
var ret = InternetQueryOption(hOpen, InternetOptionFlags.INTERNET_OPTION_HANDLE_TYPE, (IntPtr) hMem, ref sz);
Assert.That(ret, Is.True);
var hType = (InternetOptionHandleType)hMem.ToStructure<int>();
Assert.That(hType, Is.Not.Zero);
TestContext.WriteLine($"Handle is {hType}");
var sz = sizeof(int);
var hMem = new SafeCoTaskMemHandle(sz);
var ret = InternetQueryOption(hOpen, InternetOptionFlags.INTERNET_OPTION_HANDLE_TYPE, hMem, ref sz);
Assert.That(ret, Is.True);
var hType = (InternetOptionHandleType)hMem.ToStructure<int>();
Assert.That(hType, Is.Not.Zero);
TestContext.WriteLine($"Handle is {hType}");
hType = hOpen.InternetQueryOption<InternetOptionHandleType>(InternetOptionFlags.INTERNET_OPTION_HANDLE_TYPE);
Assert.That(hType, Is.Not.Zero);
TestContext.WriteLine($"Handle is {hType}");
hType = InternetQueryOption<InternetOptionHandleType>(hOpen, InternetOptionFlags.INTERNET_OPTION_HANDLE_TYPE);
Assert.That(hType, Is.Not.Zero);
TestContext.WriteLine($"Handle is {hType}");
var str = hOpen.InternetQueryOption<string>(InternetOptionFlags.INTERNET_OPTION_USER_AGENT);
Assert.That(str, Is.EqualTo("Test"));
var str = InternetQueryOption<string>(hOpen, InternetOptionFlags.INTERNET_OPTION_USER_AGENT);
Assert.That(str, Is.EqualTo("Test"));
var b = hOpen.InternetQueryOption<bool>(InternetOptionFlags.INTERNET_OPTION_ENCODE_EXTRA);
Assert.That(b, Is.False);
var b = InternetQueryOption<bool>(hOpen, InternetOptionFlags.INTERNET_OPTION_ENCODE_EXTRA);
Assert.That(b, Is.False);
var hParent = new SafeInternetHandle(hOpen.InternetQueryOption<IntPtr>(InternetOptionFlags.INTERNET_OPTION_PARENT_HANDLE));
Assert.That(hParent.IsClosed, Is.False);
var hParent = new SafeHINTERNET(InternetQueryOption<IntPtr>(hOpen, InternetOptionFlags.INTERNET_OPTION_PARENT_HANDLE));
Assert.That(hParent.IsClosed, Is.False);
Assert.That(() => hOpen.InternetQueryOption<uint>(InternetOptionFlags.INTERNET_OPTION_ENCODE_EXTRA), Throws.Exception);
Assert.That(() => InternetQueryOption<uint>(hOpen, InternetOptionFlags.INTERNET_OPTION_ENCODE_EXTRA), Throws.Exception);
Assert.That(() => hOpen.InternetQueryOption<IntPtr>(InternetOptionFlags.INTERNET_OPTION_CACHE_STREAM_HANDLE), Throws.Exception);
Assert.That(() => InternetQueryOption<IntPtr>(hOpen, InternetOptionFlags.INTERNET_OPTION_CACHE_STREAM_HANDLE), Throws.Exception);
var ver = hOpen.InternetQueryOption<INTERNET_VERSION_INFO>(InternetOptionFlags.INTERNET_OPTION_VERSION);
Assert.That(ver.dwMajorVersion, Is.Not.Zero);
TestContext.WriteLine($"Ver is {ver.dwMajorVersion}.{ver.dwMinorVersion}");
}
var ver = InternetQueryOption<INTERNET_VERSION_INFO>(hOpen, InternetOptionFlags.INTERNET_OPTION_VERSION);
Assert.That(ver.dwMajorVersion, Is.Not.Zero);
TestContext.WriteLine($"Ver is {ver.dwMajorVersion}.{ver.dwMinorVersion}");
var pi = SafeInternetHandle.Null.InternetQueryOption<INTERNET_PROXY_INFO>(InternetOptionFlags.INTERNET_OPTION_PROXY);
var pi = InternetQueryOption<INTERNET_PROXY_INFO>(HINTERNET.NULL, InternetOptionFlags.INTERNET_OPTION_PROXY);
Assert.That(pi.dwAccessType, Is.Not.Zero);
TestContext.WriteLine($"Proxy is {pi.dwAccessType}={pi.lpszProxy}");
//var ci = SafeInternetHandle.Null.InternetQueryOption<INTERNET_CERTIFICATE_INFO>(InternetOptionFlags.INTERNET_OPTION_SECURITY_CERTIFICATE_STRUCT);
//TestContext.WriteLine($"Cert is {ci.ftStart}, {ci.ftExpiry}, {ci.lpszSubjectInfo}, {ci.lpszProtocolName}");
}
[Test]
public void InternetSetOptionTest()
{
using (var hOpen = InternetOpen("Test", InternetOpenType.INTERNET_OPEN_TYPE_DIRECT, null, null, 0))
InternetSetOption(hOpen, InternetOptionFlags.INTERNET_OPTION_USER_AGENT, Environment.UserName);
var un = InternetQueryOption<string>(hOpen, InternetOptionFlags.INTERNET_OPTION_USER_AGENT);
Assert.That(un, Is.EqualTo(Environment.UserName));
InternetSetOption(hOpen, InternetOptionFlags.INTERNET_OPTION_CONNECT_RETRIES, 3U);
var r = InternetQueryOption<uint>(hOpen, InternetOptionFlags.INTERNET_OPTION_CONNECT_RETRIES);
Assert.That(r, Is.EqualTo(3U));
Assert.That(InternetSetOption(hOpen, InternetOptionFlags.INTERNET_OPTION_DIGEST_AUTH_UNLOAD), ResultIs.Successful);
Assert.That(() => InternetSetOption(hOpen, InternetOptionFlags.INTERNET_OPTION_HANDLE_TYPE), Throws.ArgumentException);
Assert.That(() => InternetSetOption(hOpen, InternetOptionFlags.INTERNET_OPTION_HANDLE_TYPE, InternetOptionHandleType.INTERNET_HANDLE_TYPE_CONNECT_FTP), Throws.ArgumentException);
Assert.That(() => InternetSetOption(hOpen, InternetOptionFlags.INTERNET_OPTION_URL), Throws.ArgumentException);
Assert.That(() => InternetSetOption(hOpen, InternetOptionFlags.INTERNET_OPTION_CACHE_STREAM_HANDLE), Throws.Exception);
}
[Test]
public void InternetTimeFromSystemTimeTest()
{
var st = new SYSTEMTIME(DateTime.Now, DateTimeKind.Local);
var sb = new StringBuilder(1024);
Assert.That(InternetTimeFromSystemTime(st, INTERNET_RFC.INTERNET_RFC1123_FORMAT, sb, (uint)sb.Capacity), ResultIs.Successful);
Assert.That(InternetTimeToSystemTime(sb.ToString(), out var st2), ResultIs.Successful);
Assert.That(st.Equals(st2), Is.True);
}
[Test]
public void PrivacyGetSetZonePreferenceWTest()
{
URLZONE zone = URLZONE.URLZONE_INTERNET;
PrivacyType priv = PrivacyType.PRIVACY_TYPE_FIRST_PARTY;
PrivacyTemplate iTmpl = 0;
string pref = null;
var sb = new StringBuilder(1024);
foreach (var e in Enum.GetValues(typeof(URLZONE)).Cast<URLZONE>())
{
hOpen.InternetSetOption(InternetOptionFlags.INTERNET_OPTION_USER_AGENT, "dahall");
var un = hOpen.InternetQueryOption<string>(InternetOptionFlags.INTERNET_OPTION_USER_AGENT);
Assert.That(un, Is.EqualTo("dahall"));
hOpen.InternetSetOption(InternetOptionFlags.INTERNET_OPTION_CONNECT_RETRIES, 3U);
var r = hOpen.InternetQueryOption<uint>(InternetOptionFlags.INTERNET_OPTION_CONNECT_RETRIES);
Assert.That(r, Is.EqualTo(3U));
Assert.That(() => hOpen.InternetSetOption(InternetOptionFlags.INTERNET_OPTION_HANDLE_TYPE), Throws.Exception);
Assert.That(() => hOpen.InternetSetOption(InternetOptionFlags.INTERNET_OPTION_HANDLE_TYPE, InternetOptionHandleType.INTERNET_HANDLE_TYPE_CONNECT_FTP), Throws.Exception);
Assert.That(() => hOpen.InternetSetOption(InternetOptionFlags.INTERNET_OPTION_DIGEST_AUTH_UNLOAD), Throws.Nothing);
Assert.That(() => hOpen.InternetSetOption(InternetOptionFlags.INTERNET_OPTION_URL), Throws.Exception);
Assert.That(() => hOpen.InternetSetOption(InternetOptionFlags.INTERNET_OPTION_CACHE_STREAM_HANDLE), Throws.Exception);
var sz = (uint)sb.Capacity;
//Assert.That(PrivacyGetZonePreferenceW(e, priv, out var tmpl, sb, ref sz), ResultIs.Successful);
if (PrivacyGetZonePreferenceW(e, priv, out var tmpl, sb, ref sz).Succeeded)
TestContext.WriteLine($"{e} : {tmpl} : {sb}");
if (e == zone) { pref = sb.ToString(); iTmpl = tmpl; }
}
Assert.That(PrivacySetZonePreferenceW(zone, priv, iTmpl, pref), ResultIs.Successful);
}
}
}