Send content using PUT method

This post demonstrates how to send content to server from a client application written in C#. A typical REST API implements PUT methods to receive content from clients. I’ve been using RestSharp for most REST requests, but this is one use case it doesn’t provide for, yet. It is fairly easy to implement using .NET’s HttpClient.

Uri uri = ...
byte[] content = ...
string contentType = ... 

HttpClient client = new HttpClient();
ByteArrayContent httpContent = new ByteArrayContent(content);
httpContent.Headers.ContentType = new MediaTypeHeaderValue(contentType);
Task<HttpResponseMessage> put = client.PutAsync(uri, httpContent);
HttpResponseMessage response = put.Result;

Task<string> read = response.Content.ReadAsStringAsync();

if (response.StatusCode == HttpStatusCode.Created)
    // use read.Result

Specify a different ssh key for each host

The ~/.ssh/config file can be edited to specify a different key/identity for each host. This is useful when you have different ssh keys setup on different git servers.

Host mycompany
    HostName mycompany.com
    User fooey
Host github.com
    IdentityFile ~/.ssh/github.key

See Simplify Your Life With an SSH Config File for more.

Join multi-user chat with node-xmpp-client

XEP-0045 defines the XMPP protocol extensions required to join multi-user chat rooms, and receive and post messages. In this post I use the execllent node-xmpp-client library to join a multi-user char room. Any messages sent to the chat room after you join are received, but I don’t parse them in the code below.

node-xmpp-client can be installed from source or npm as follows

npm i -g node-xmpp-client
export NODE_PATH=/usr/local/lib/node_modules

Change NODE_PATH value appropriately. npm -g list should show where your global node_modules folder is located.

Here’s the code that creates a new XMPP client, and sends a presence stanza to the XMPP server to join a chat room.

var Client = require('node-xmpp-client')

var jid = 'user@domain'
var password = 'password'
var room = 'room@domain/nickname'

var client = new Client({
    jid: jid,
    password: password,
    preferred: 'PLAIN'
})

client.on('online', function() {
    console.log('online')
    var stanza = new Client.Stanza('presence', {from: jid, to: room})
    client.send(stanza)
})

client.on('stanza', function(stanza) {
    console.log('Incoming stanza: ', stanza.toString())
})

client.on('error', function(e) {
    console.log(e);
})

process.on('SIGINT', function(code) {
    console.log('leaving the room')
    var stanza = new Client.Stanza('presence', {from: jid, to: room, type: 'unavailable'})
    client.send(stanza)

    setTimeout(function() {
        process.exit()
    }, 1000);
})

If you don’t specify a unique nickname, the XMPP server will likely reject the request to join the room. Modify the above script appropriately, and invoke node to execute it.

If you get any strange errors, try setting the DEBUG environment variable as follows, and try again.

export DEBUG=*

WeightLE

WeightLE (\ˈwāt-lē\) is a concept Bluetooth Smart utility, not unlike a beverage coaster or beermat, that learns from the weight placed over it, and notifies you when it’s too low. You get to decide what low means.

WeightLE.jpg

It can be used with bottles, cups, jars, and even water coolers. Anything that isn’t smart yet can be made smarter, so you are not left without that something when you need it the most. An accompanying Smartphone or Smartwatch app is required with WeightLE.

PhotoMath

PhotoMath, by MicroBlink Ltd., is a neat little utility available from the iOS App Store, and Android Play Store, that can make solving elementary Math homework less of a chore. Besides giving the answer outright, it provides a detailed step-by-step procedure for arriving at the answer.

Try it while the following equation is displayed on a second screen

2x^2+3=11

It does have its limitations though. An equation such as the following is currently unsolvable

\frac{1}{1-\frac{1}{1+\frac{1}{1-\frac{1}{x}}}}=3

Wolfram Alpha makes short work of that equation when you query it using its \LaTeX representation.

History of file in Git repo

Who changed what, and when, in a file in a Git repo? The following simple command is usually enough

git log -p path

Simple message dispatcher using event delegates

This post demonstrates a simple asynchronous message dispatcher that decouples message producers from consumers. It leverages event delegates.

using System;
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Threading.Tasks;

namespace NetDispatcher
{
    public delegate void MessageHandler<U>(U message);

    public class MessageDispatcher<T, U>
    {
        static ConcurrentDictionary<T, System.Delegate> handlers =
            new ConcurrentDictionary<T, System.Delegate>();

        public static async Task Dispatch(T type, U message)
        {
            System.Delegate eventHandlers;
            handlers.TryGetValue(type, out eventHandlers);
            if (eventHandlers != null)
            {
                try
                {
                    await Task.Run(delegate
                    {
                        ((MessageHandler<U>)eventHandlers)(message);
                    });
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.Message);
                    Debug.WriteLine(ex.StackTrace);
                }
            }
        }

        public static void RegisterHandler(T type, MessageHandler<U> handler)
        {
            Delegate d;
            handlers.TryGetValue(type, out d);

            if (d == null)
            {
                handlers[type] = null;
            }

            handlers[type] = (MessageHandler<U>)handlers[type] + handler;
        }

        public static void DeregisterHandler(T type, MessageHandler<U> handler)
        {
            Delegate d;
            handlers.TryGetValue(type, out d);

            if (d != null)
            {
                handlers[type] = (MessageHandler<U>)handlers[type] - handler;
            }
        }
    }
}

This is how the message dispatcher may be used

        // Register a handler for "foo" that accepts messages of type string
        MessageDispatcher<string, string>.RegisterHandler("foo", delegate (string message)
        {
            // ...
        });

        // Dispatch a message
        MessageDispatcher<string, string>.Dispatch("foo", "bar");

The use of static methods with generic types allows it to be used for multiple message payload types. Subclass it if you want to make an instance for another purpose.