[Raspberry Pi 2] Create C# Background Application for Windows 10 IoT Core

By | June 8, 2015

Advertisement from Google

windows 10 + raspberry pi 2In this article,  we will see how to create simple Web Server for Raspberry Pi 2 running Windows 10 IoT Core. Because it is a Web Server we don’t need UI for this application, we can run it in headless mode.

Open Visual Studio 2015 RC and create Windows IoT Core Background Application solution.

Now we need a web server. This will be simple one. It will always response with “Hello, World!” string.

internal class WebServer
{
    private const uint BufferSize = 8192;

    public void Start()
    {
        StreamSocketListener listener = new StreamSocketListener();

        listener.BindServiceNameAsync("8080");

        listener.ConnectionReceived += async (sender, args) =>
        {
            StringBuilder request = new StringBuilder();
            using (IInputStream input = args.Socket.InputStream)
            {
                byte[] data = new byte[BufferSize];
                IBuffer buffer = data.AsBuffer();
                uint dataRead = BufferSize;
                while (dataRead == BufferSize)
                {
                    await input.ReadAsync(buffer, BufferSize, InputStreamOptions.Partial);
                    request.Append(Encoding.UTF8.GetString(data, 0, data.Length));
                    dataRead = buffer.Length;
                }
            }

            using (IOutputStream output = args.Socket.OutputStream)
            {
                using (Stream response = output.AsStreamForWrite())
                {
                    byte[] bodyArray = Encoding.UTF8.GetBytes("<html><body>Hello, World!</body></html>");
                    var bodyStream = new MemoryStream(bodyArray);

                    var header = "HTTP/1.1 200 OK\r\n" + 
                                $"Content-Length: {bodyStream.Length}\r\n" +
                                    "Connection: close\r\n\r\n";

                    byte[] headerArray = Encoding.UTF8.GetBytes(header);
                    await response.WriteAsync(headerArray, 0, headerArray.Length);
                    await bodyStream.CopyToAsync(response);
                    await response.FlushAsync();
                }
            }
        };
    }
}

Advertisement from Google

As you can see, we just read request body and send simple HTTP header with HTML content back.

Now we need to start our web server. To do that open StartupTask class:

public void Run(IBackgroundTaskInstance taskInstance)
{
    taskInstance.GetDeferral();
    WebServer server = new WebServer();
    ThreadPool.RunAsync(workItem =>
    {
        server.Start();
    });
}

You should call taskInstance.GetDeferral(); to not let application close immediately after run. To close an application you can call Complete method on BackgroundTaskDeferral instance.

Now you can deploy your application and see how it works. Just type IP and port in browser and you should see “Hello, World!” message.

18 thoughts on “[Raspberry Pi 2] Create C# Background Application for Windows 10 IoT Core

  1. joris

    Hi.
    Great example. I can see the web page, but after refreshing 3 times, my debugging just stops.
    The program ‘[880] backgroundTaskHost.exe’ has exited with code 1 (0x1).

    Any idea?

    Reply
    1. Oscar

      What i did was to put the task into an appservice, and it works for me. altought sometimes the task is closed when the task runs for more than 10 mins. i did some test and i saw that it didn’t happen if you run the program directly from IotCoreWatcher web page. in that case it works all night.

      hope this help.
      regards.

      Reply
  2. Tony

    I gave attribution and linked back to this article from a Project I am a team member of on Hackster.io. If you are not okay with this please let me know and I will remove the link.
    Thank you for the great information!

    Reply
  3. Jelmer Mulder

    The program ‘[4052] backgroundTaskHost.exe’ has exited with code 1 (0x1).

    When I try:

    byte[] bodyArray = Encoding.UTF8.GetBytes(“”+ JsonConvert.SerializeObject(cat) + “”);

    I use JSON.net. It works fine in other IoT apps…

    Thank you for any help!

    Reply
  4. Hans-Jörg

    Hi

    Waht namespaces are needed? It is hard for beginners with you sample if the namespaces are not defined.
    Thank you for your help.

    Regards Hans-Jörg

    Reply
    1. Mike

      Hi Hans-Jörg,
      Being a n00b myself, I wondered the same thing, however, I pushed through it thanks to Visual Studio 2015’s contextual help in identifying/suggesting which name spaces to import with “using” statements.

      I complied and ran the application, but then it immediately crashed. This led to my next discovery, which was that I needed to add a Capability to the application so that it could run as a server on the Pi. This accomplished by ticking the “Internet (Client & Server) on the “Capabilities” tab when editing “Package.appxmanifest” which can be found in your Project files tree.

      Hope this helps!
      — Mike

      Reply
  5. RAFAEL FELIPE

    there any way to host a asp.net mvc in raspberry pi 3?

    or have u any sample how to browse button call a method in raspberry server that i mad?

    Reply
  6. bbSkygazer

    Has Anyone else had problems randomly not receiving full post message from ios clients using this code? It works 100% for form post from Windows and Android devices but ios seems to leave out the form data at least half of the time.

    Reply
  7. garry

    Instead of running a web page, can I call other functions in C# and write the whole app in C# ?

    Reply
  8. Mandar Chandrakant Gawas

    I implemented above suggested background application. It was working perfectly, but now suddenly something is wrong. When i send 2-3 requests one by one. The application stops responding in between. I tried debugging, i also tried to catch the error but didn’t get anything. Please need urgent help!!

    Reply
  9. Ciro Kenzie

    When trying to execute the program at line:
    listener.BindServiceNameAsync(“8080”);

    I’m getting the following error:

    System.UnauthorizedAccessException occurred
    HResult=0x80070005
    Message=Access is denied.

    At least one of either InternetClientServer or PrivateNetworkClientServer capabilities is required to listen for or receive traffic
    Source=
    StackTrace:
    at Windows.Networking.Sockets.StreamSocketListener.BindServiceNameAsync(String localServiceName)
    at BackgroundApplication1.WebServer.Start() in C:\Users\UseerName\Documents\Visual Studio 2017\Projects\BackgroundApplication1\BackgroundApplication1\StartupTask.cs:line 38
    at BackgroundApplication1.StartupTask.c__DisplayClass0_0.b__0(IAsyncAction workItem) in C:\Users\UseerName\Documents\Visual Studio 2017\Projects\BackgroundApplication1\BackgroundApplication1\StartupTask.cs:line 25

    Reply
  10. Robert

    Hi All,
    I got this working on an Raspberry in debug mode without any problems but once I deploy a release version it works only once.
    I can load the page but when I refresh it seems to have crashed.
    Has anyone else had this problem?
    I have just started with this IoT stuff so I don’t know much about it, does anyone know if there is a event log somewhere?

    Cheers!
    Robert.

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *