How to send text, JSON or files using HttpClient.PostAsync().

This is a common question in StackOverflow and MSDN forums. So, lets take a look at our three main options.

HttpStringContent

Send any string like this:

// E.g. a JSON string.
HttpStringContent stringContent = new HttpStringContent(
    "{ \"firstName\": \"John\" }",
    UnicodeEncoding.Utf8,
    "application/json");

HttpClient client = new HttpClient();
HttpResponseMessage response = await client.PostAsync(
    uri,
    stringContent);

This sends a request like this:

POST / HTTP/1.1
Accept-Encoding: gzip, deflate
Content-Length: 23
Content-Type: application/json; charset=UTF-8
Host: kiewic.com
Connection: Keep-Alive
Cache-Control: no-cache

{ "firstName": "John" }

HttpFormUrlEncodedContent

Send a list of key-value pairs, better known as x-www-form-urlencoded:

Dictionary<string, string> pairs = new Dictionary<string,string>();
pairs.Add("Name", "Bob");
pairs.Add("Age", "18");
pairs.Add("Gender", "Male");
HttpFormUrlEncodedContent formContent =
    new HttpFormUrlEncodedContent(pairs);
 
HttpClient client = new HttpClient();
HttpResponseMessage response = await client.PostAsync(uri, formContent);

This sends a request like this:

POST / HTTP/1.1
Accept-Encoding: gzip, deflate
Content-Length: 27
Content-Type: application/x-www-form-urlencoded
Host: kiewic.com
Connection: Keep-Alive
Cache-Control: no-cache

Name=Bob&Age=18&Gender=Male

This is equivalent to submit the following HTML form from a web browser:

<html>
  <head>
    <meta charset="UTF-8" />
  </head>
  <body>
    <form action="http://kiewic.com" method="post">
      <input type="text" name="Name" value="Bob">
      <input type="text" name="Age" value="18">
      <input type="text" name="Gender" value="Male">
      <input type="submit" />
    </form>
  </body>
</html>

These values can be easily accessed from PHP using the $_POST array. Or from ASP.NET using Request.Form property.

HttpMultipartFormDataContent

Send files, or text and files mixed, better known as multipart/form-data.

First, create a sample file:

IStorageFolder folder = ApplicationData.Current.LocalFolder;
IStorageFile file = await folder.CreateFileAsync(
    "foo.txt",
    CreationCollisionOption.ReplaceExisting);
await FileIO.WriteTextAsync(
    file,
    "The quick brown fox jumps ...");

Then, send a request like this:

IInputStream inputStream = await file.OpenAsync(FileAccessMode.Read);
HttpMultipartFormDataContent multipartContent =
    new HttpMultipartFormDataContent();
multipartContent.Add(
    new HttpStreamContent(inputStream),
    "myFile",
    file.Name);
multipartContent.Add(
    new HttpStringContent("Hello World"),
    "myText");
 
HttpClient client = new HttpClient();
HttpResponseMessage response = await client.PostAsync(
    uri,
    multipartContent);

The raw request looks like this:

POST / HTTP/1.1
Accept-Encoding: gzip, deflate
Content-Length: 371
Content-Type: multipart/form-data; boundary=c9b47f5b-ca6c-43bd-a953-6ea78b2ee24b
Host: kiewic.com
Connection: Keep-Alive
Cache-Control: no-cache

--c9b47f5b-ca6c-43bd-a953-6ea78b2ee24b
Content-Disposition: form-data; name="myFile"; filename="foo.txt"; filename*=UTF-8''foo.txt

The quick brown fox jumps ...
--c9b47f5b-ca6c-43bd-a953-6ea78b2ee24b
Content-Length: 11
Content-Type: text/plain; charset=UTF-8
Content-Disposition: form-data; name="myText"

Hello World
--c9b47f5b-ca6c-43bd-a953-6ea78b2ee24b--

These values can be accessed from PHP using the $_FILES array. Or from ASP.NET using the Request.Files property.

 

When traveling to Mexico, what forms do I need to fill out?

As a foreigner, you should fill out two forms before passing immigration when arriving at a Mexican airport:

  1. Customs declaration.
  2. Entry registration form.

The customs declaration looks like this:

Mexico Customs Declaration

The entry registration looks like this:

Mexico Entry Registration

Mexico Entry Registration Back 2

Mexico Entry Registration Stamp

The entry registration (immigration form) can be split into two. You have to fill out both parts of the form before seeing the immigration agent when arriving to Mexico. The immigration agent will keep the top part, and it will put a stamp to the bottom part, which you must keep and give to the airline when departing from Mexico.

It would be better if you fill out the forms in the airplane. Ask for both to your air attendant :)

How to install the Universal Apps templates in Visual Studio 2013?

If you are having troubles finding the Universal Apps templates, you may need to download the Visual Studio 2013 Update 3.

Once installed, you will find the Universal Apps templates under Templates > Visual C# > Store Apps > Universal Apps in the New Project window.

Visual Studio New Project Universal Apps Screenshot

The Universal Apps templates allow you to create one solution for an app that runs on Windows 8.1 and Windows Phone 8.1. Learn more here!

 

 

WRL WeakRef

So, you have two objects that are related. A mother gorilla and a baby  gorilla. You want the mother gorilla can reference the baby gorilla, and vice versa, so you add a reference to the baby from the mother and another reference to the mother from the baby.

class MotherGorilla : public RuntimeClass<FtmBase>
{
private:
    ComPtr<BabyGorilla> baby;
};

class BabyGorilla : public RuntimeClass<FtmBase>
{
private:
    ComPtr<MotherGorilla> mother;
};

Guess what? In COM, where the objects are freed until the reference counter hits zero, the mom’s counter will never be zero because the baby has a reference to the mom, and the baby’s counter will never be zero because the mom holds a reference to the baby. Possible memory leak.

Fix? Make one of the references a weak reference.

class MotherGorilla : public RuntimeClass<FtmBase>
{
private:
    WeakRef baby;
};

// BabyGorilla class requires a UUID, otherwise WeakRef::CopyTo()
// fails with "error C2787: 'BabyGorilla' : no GUID has been
// associated with this object" [uuid("7c8ab438-a275-467f-8bdd-7e556e0016f4")] class BabyGorilla : public RuntimeClass<FtmBase> { private: ComPtr<MotherGorilla> mother; };

And each time the mother wants to interact with the baby, she will need to get a hard reference to the baby by calling WeakRef::As or WeakRef::CopyTo.

Parse WinDbg wt command output by converting it into CSV

The output of the WinDbg wt command (trace and watch data) looks like this:

  105     0 [  0] MyModule!myFunction
    1     0 [  1]   MyModule!ILT+1555(_printf)
    9     0 [  1]   MyModule!printf
    1     0 [  2]     MyModule!ILT+370(__stbuf)
   11     0 [  2]     MyModule!_stbuf
    1     0 [  3]       MyModule!ILT+1440(__isatty)
   14     0 [  3]       MyModule!_isatty
   50    15 [  2]     MyModule!_stbuf
   17    66 [  1]   MyModule!printf
    1     0 [  2]     MyModule!ILT+980(__output)
   59     0 [  2]     MyModule!_output
   39     0 [  3]       MyModule!write_char
  111    39 [  2]     MyModule!_output
   39     0 [  3]       MyModule!write_char

It may be easier to interpret by converting it into another format such as Comma Separated Values (CSV) and analyzing it using Microsoft Excel.

With Notepad++, open the Replace window, look for the following regular expression:

[ ]+([0-9]+)\s*([0-9]+)\s*\[\s*([0-9]+)\s*\]\s*(.*)

And replace with:

\1,\2,\3,"\4"

The final result should look like this:

105,0,0,"MyModule!myFunction"
1,0,1,"MyModule!ILT+1555(_printf)"
9,0,1,"MyModule!printf"
1,0,2,"MyModule!ILT+370(__stbuf)"
11,0,2,"MyModule!_stbuf"
1,0,3,"MyModule!ILT+1440(__isatty)"
14,0,3,"MyModule!_isatty"
50,15,2,"MyModule!_stbuf"
17,66,1,"MyModule!printf"
1,0,2,"MyModule!ILT+980(__output)"
59,0,2,"MyModule!_output"
39,0,3,"MyModule!write_char"
111,39,2,"MyModule!_output"
39,0,3,"MyModule!write_char"

Win32 Mutex, HANDLEs and WinDbg !handle extension.

It turns out a mutex is like a lock that is shared between processes. So if we run two instances of the following program at the same time, the second instance will hang/wait 10 seconds before acquiring the mutex.

#include "stdafx.h"
#include <Windows.h>
#include <synchapi.h>

int main(int argc, _TCHAR* argv[])
{
    WCHAR* cacheMutexName = L"HelloWorldMutex";
    HANDLE handle = ::CreateMutex(nullptr, FALSE, cacheMutexName);

    DWORD result = WaitForSingleObject(handle, INFINITE);

    switch (result)
    {
    case WAIT_OBJECT_0:
        printf("The thread got ownership of the mutex.\r\n");
        break;
    case WAIT_ABANDONED:
        printf("The thread got ownership of an abandoned mutex.\r\n");
        break;
    }

    // Countdown.
    for (int i = 10; i > 0; i--)
    {
        wprintf(L"%d\r\n", i);
        Sleep(1000);
    }
    wprintf(L"0\r\n");

    ReleaseMutex(handle);
    printf("Mutex released.\r\n");

    return 0;
}

In Win32, once you get the mutex, you can distinguish between two different cases. The first case is WAIT_OBJECT_0 and it means the previous owner released the mutex properly by calling ReleaseMutex() and the second case is WAIT_ABANDONED and it means the previous owner terminated without calling ReleaseMutex().

To reproduce the WAIT_ABANDONED case with the sample program, press CTRL + C in the first instance before the countdown hits zero.

When using WinDbg, during live debugging or during dump analysis, the !handle extension comes very handy.

Just get the handle value:

0:000> dv
 argc = 0n1
 argv = 0x010f6f28
 handle = 0x00000038
 result = 0xcccccccc
 cacheMutexName = 0x003f5858 "HelloWorldMutex"

And print all the handle info:

0:000> !handle 0x00000038 f
Handle 38
 Type Mutant
 Attributes 0
 GrantedAccess 0x1f0001:
 Delete,ReadControl,WriteDac,WriteOwner,Synch
 QueryState
 HandleCount 3
 PointerCount 98306
 Name \Sessions\1\BaseNamedObjects\HelloWorldMutex
 Object Specific Information
 Mutex is Owned
 Mutant Owner 11ac.1628

Now we know 11ac.1628 is the owner of the mutex:

If we print the call stack for each thread in the second instance of the program:

0:000> ~* kcn

.  0  Id: 29f8.778 Suspend: 1 Teb: 7f15c000 Unfrozen
 # 
00 ntdll!NtWaitForSingleObject
01 KERNELBASE!WaitForSingleObjectEx
02 KERNELBASE!WaitForSingleObject
03 MutexExample!main
04 MutexExample!__tmainCRTStartup
05 MutexExample!mainCRTStartup
06 KERNEL32!BaseThreadInitThunk
07 ntdll!__RtlUserThreadStart
08 ntdll!_RtlUserThreadStart

#  1  Id: 29f8.ec4 Suspend: 1 Teb: 7f159000 Unfrozen
 # 
00 ntdll!DbgBreakPoint
01 ntdll!DbgUiRemoteBreakin
02 KERNEL32!BaseThreadInitThunk
03 ntdll!__RtlUserThreadStart
04 ntdll!_RtlUserThreadStart

We do not see any 11ac.1628 thread.

But if we print the call stacks of the first process intance:

0:000> ~* kcn

.  0  Id: 11ac.1628 Suspend: 1 Teb: 7fe7d000 Unfrozen
 # 
00 ntdll!NtDelayExecution
01 KERNELBASE!SleepEx
02 KERNELBASE!Sleep
03 MutexExample!main
04 MutexExample!__tmainCRTStartup
05 MutexExample!mainCRTStartup
06 KERNEL32!BaseThreadInitThunk
07 ntdll!__RtlUserThreadStart
08 ntdll!_RtlUserThreadStart

#  1  Id: 11ac.1c48 Suspend: 1 Teb: 7fe7a000 Unfrozen
 # 
00 ntdll!DbgBreakPoint
01 ntdll!DbgUiRemoteBreakin
02 KERNEL32!BaseThreadInitThunk
03 ntdll!__RtlUserThreadStart
04 ntdll!_RtlUserThreadStart

Then we see the 11ac.1628 thread.

In fact 0x11ac and 0x29f8 match the PID of the processes:

C:\>tlist

4524 MutexExample.exe
10744 MutexExample.exe

Happy handle debugging!