Alternatives to Deeply-Nested Callback Functions in Javascript

A few days ago, I wrote a server in Node.js, the purpose of which is to email me when an API found in Nuget is updated. I thought the project would take a few hours, but as it turned out, it took several days. You may ask “How is this possible for such an easy problem?” Unfortunately, I spent a lot of time trying to figure out what API to use to read a text file, and how to use the API. It led me to an understanding of a fundamental problem with Javascript known as “callback hell” (1, 2).

Continue reading “Alternatives to Deeply-Nested Callback Functions in Javascript”

Resources for C# WebSockets

WebSockets is a communication protocol on TCP between a web browser (or other client) and a server. It is full-duplex, event-driven. One important advantage of the technology is the elimination of the client polling of the server. The following post lists some resources for C# WebSockets (1).

C#/WebSocket Resources

 

Articles on Web Sockets

https://tools.ietf.org/html/rfc6455
https://tools.ietf.org/html/rfc7936
https://en.wikipedia.org/wiki/WebSocket
https://www.websocket.org/index.html
https://en.wikipedia.org/wiki/Comparison_of_WebSocket_implementations
http://www.codeproject.com/Articles/1063910/WebSocket-Server-in-Csharp
http://www.codeproject.com/Articles/617611/Using-WebSocket-in-NET-4-5-Part-1
http://www.codeproject.com/Articles/618032/Using-WebSocket-in-NET-Part
http://www.codeproject.com/Articles/619343/Using-WebSocket-in-NET-Part
http://www.codeproject.com/Articles/620731/Using-WebSocket-in-NET-Part

 

Note:

  1. Initial list from http://stackoverflow.com/questions/33467089/net-websocket-client-and-server-library
  2. Although it was suggested in a StackOverflow.com discussion to use “Sockets for PCL“, that is not a viable solution because the library is for TCP sockets not WebSockets.

 

Runtime Performance of NET Core vs. NET Framework vs. Mono

With the release of NET Core, the acquisition of Xamarin and Mono, and the 15 or so years of development of the NET Framework, we now have three platforms to choose from for C#. Why are there three platforms? What are the differences between each? And, what is the performance of the three to each other? From the NET Core Roadmap, it’s clear that Microsoft is trying to focus on OS-agnostic implementations of NET.

NET Framework is for Windows desktop and mobile applications. The NET Framework is specific for Windows because it has Windows UI functionality. If you want an application that works across different OSes, then this won’t be your choice.

NET Core is for console and server applications that need to work on any OS. Also, a focus of the NET Core framework is small size/efficient applications. The first release was only a month ago, and there are many things missing. If you need UI beyond System.Console, look to one of the other two platforms.

Finally, Mono/Xamarin is for mobile applications. Mono can also run NET Framework console applications on most OSes without changes. On Android, C# and Java can call each other. If you have a large Java code base, this is a good choice. Xamarin Forms is an OS-independent UI for mobile devices.

What are the differences in performance between NET Framework, NET Core, and Mono? The following test computes the performance of a recursive implementation of Ackermann’s function and a looping implementation of a Fibonacci function. If you are looking for performance of in a console application, NET Core is your choice.

 

NetPerf1

NetPerf2

Runtimes based on sample size of 10, .NET Core 1.0.1, .NET Framework 4.5, Mono JIT compiler version 4.2.2 (Visual Studio built mono), Windows 10 Anniversary Update, Intel(R) Core(TM) i5-3570K CPU @ 3.40GH, Northbridge Intel Ivy Bridge rev. 09, Southbridge Intel Z77 rev. 04, Graphic Interface PCI-Express, PCI-E Link Width x16, PCI-E Max Link Width x16, Memory Type DDR3, Memory Size 16 GBytes, Channels Dual, Memory Frequency 800.7 MHz (1:6), CAS# latency (CL) 11.0, RAS# to CAS# delay (tRCD) 11, RAS#, Precharge (tRP) 11, Cycle Time (tRAS) 28, Command Rate (CR) 2T, Host Bridge 0x0150.

On Ubuntu, there is a similar speedup for Ackermann’s function with NET Core. But for the Fibonacci function, surprisingly slightly slower with NET Core compared to the Mono implementation.

 PerfAckUb

PerfFibUb

Runtimes based on sample size of 3, .NET Core 1.0.1, .NET Framework 4.5, Mono JIT compiler version 4.4.2 (Stable 4.4.2.11/f72fe45 Fri Jul 29 09:58:49 UTC 2016); Intel(R) Xeon(R) CPU E5-2650L v3 @ 1.80GHz; 512 MB Memory / 20 GB Disk / SFO2 – Ubuntu 16.04.1 x64.

Benchmark Code:

perf.tar.gz

Data analysis in XLSX

Further Information:

.NET Core 1.0, .NET Framework, Xamarin – The “WHAT and WHEN to use it”.  Accessed August 10, 2016.

Microsoft reveals big plans for .Net Core. Accessed August 10, 2016.

.NET Core. Accessed August 10, 2016.

.NET Core Roadmap. Accessed August 10, 2016.

.NET Core Version 1 Released – So What? Accessed August 10, 2016.

Getting Started with ASP.Net Core Accessed August 10, 2016.

Cross-Debugging Mono C# Executables Running on Linux

Debugging C# programs that run on a Linux server can be a challenge. On Ubuntu, a server may not have the Unity GUI installed, so you can’t use MonoDevelop. Even if the server had the GUI, MonoDevelop often does not work with a C# project because it doesn’t support many Visual Studio 2015 projects. Visual Studio supposedly can cross-debug a program running on Linux from a Windows box, but I haven’t been able to get one solution to work. (It does work for C++.) Xamarin Studio works, but the steps are somewhat convoluted, and won’t work if you naively follow what has been outlined by others for a Windows box (e.g., in (a), you cannot simply build the app on Linux using xbuild, because the paths for files between server and debugger host differ). Here, I note how one can get Xamarin Studio working on Windows.

  1. Download a copy of Xamarin Studio for Windows, and install it. Xamarin Studio for Windows is, in fact, no longer officially available, but you can still find the download here as of July 2016. I don’t know how long this link will last; you can’t download Xamarin Studio for Windows though Xamarin.com.
  2. In your Linux server, make sure to have it set up with a firewall, SSH, and Mono.
  3. Create a variable in your environment to enable Xamarin Studio “Custom Soft Debugging.” Create “MONODEVELOP_SDB_TEST” with the value “1” (no quotes) through the System Properties box.
  4. Start Xamarin Studio, and open or create a C# test program, like “Hello World.” Set the configuration to Debug and build the program.
  5. Mono does not understand PDB files, so you have to create the equivalent MDB files. Start a command-line Bash shell in the directory ‘bin/Debug/”. Type: for i in *.exe *.dll;do echo $i; pdb2mdb $i; done. If pdb2mdb is not found, make sure Mono/bin is on the search path.
  6. Open a command-line Bash shell on your Linux box using “ssh”, e.g., “ssh root@192.168.1.10”.
  7. In the Windows Bash shell, type: tar -cvf – Debug | ssh root@192.168.1.10 ‘cat – > Debug.tar’.
  8. In the Linux Bash shell, type: tar -xvf Debug.tar; cd Debug; mono –debug –debugger-agent=transport=dt_socket,address=0.0.0.0:12345,server=y HelloWorld.exe, replacing HelloWorld.exe with the name of the executable you want to debug.
  9. In Xamarin Studio, open Run -> Run with -> Custom Command Mono Soft Debugger. 2016-07-14 (1)
  10. In the pop up, enter the IP address of the Linux box, then click on “Connect”. 2016-07-14 (9)
  11. You should now be able to debug your program. Note: you don’t need to compile the program on Linux. Note: if you can’t set breakpoints, it’s because you haven’t copied the .mdb files from Windows to Linux. Path names in the .mdb files are full paths, and Linux path names do not work.

 

Further Information

  1. https://eladnava.com/debug-remote-mono-apps-via-xamarin-studio/
  2. http://www.mono-project.com/docs/advanced/runtime/docs/soft-debugger/
  3. http://www.jeffongames.com/2012/03/debugging-embedded-mono/
  4. http://tirania.org/blog/archive/2008/Sep-04.html
  5. https://blogs.msdn.microsoft.com/vcblog/2015/11/18/announcing-the-vs-gdb-debugger-extension/

Installing Docker

OK, really simple. I want to install Docker on an Ubuntu box. Should be easy. Right?

Wrong!

When I do a Google search for “install docker”, Google returns a link to the Docker installation page for Ubuntu. That’s fine, but following the 18 page/2000 word installation is insane. The first time I did that, it took 15 minutes. What a waste of time, and not easily reproducible if I stop to get a cup of coffee, then come back.

So, I go to docker.com, and somehow find some other documentation for a Linux install through the now totally indecipherable menu system in docker.com. The instructions are shorter, and seem the right thing to do, basically: curl -fsSL https://get.docker.com/ | sh.

Why ask why there are two different instructions?

 

 

The Mysteries of XAML

I’d like to start with a short story. I’m trying to write a simple Hello World program. I want it to run on Android, and it must use Xamarin Forms, and use XAML to describe the UI. Should be easy, 5 minutes to do, right? Not in my case.

I go into Visual Studio and create a blank app (Xamarin.Forms Portable). I then “Add New/Forms Xaml Page”, which creates Page1.xaml, replace the hard-wired C# code for building the UI in App.cs with “MainPage = new Page1();”, compile and try to run the program. Unfortunately, it doesn’t do what I expected: there is no text displayed. Looking at Page1.xaml, I realize that the code “{Binding MainText}”  isn’t working. What the hell did Visual Studio create?

Maybe you know–or maybe not, as I didn’t–the explanation is quite simple: If the BindingContext of the XAML-specified UI data structure is null, which is so in this case, there is no object to get the string property “MainText”. Consequently, the Text property of the Label object is initialized to the empty string. There is no runtime error message produced because referencing a property with a null BindingContext is “OK.”

Excuse me, but this is bad. People don’t have a chance in hell if an IDE generates code that doesn’t work. Don’t just take my word on it, others have the same observation. The IDE should generate an empty XAML file, or it should generate stubs for an app that has some structure (MVVM, MVP, MVC, etc).

So, on I go to investigate XAML, because that’s what this is really all about.

What is XAML?

XAML is a language for specifying tree-oriented data structures. Simply stated, XML elements and attributes are mapped into UI classes and properties, respectively. While you can avoid using XAML in your program, people want the UI to have a clean separation from the logic of the program. XAML helps you accomplish this because it is a declarative language.

XAML has a long history. Initially, there was speculation whether it was a replacement of HTML for web browsers, but it was just a language for UI data structures for Microsoft’s desktop. Writing an XAML spec was supposed “to be developed with a visual tool where developers do not even need to understand the underlying markups,” but in the initial release, the tool was terrible. It still is a problem, because there is no designer for Xamarin Forms XAML.

That would be fine, but there is no formal definition of the language to fall back on. If you read Microsoft’s spec on XAML, it is stated that the interpretation is up to individual XAML processors. In other words, the interpretation of the directive is what it is, whatever that is. But, as we shall see, XAML elements map to UI objects, and we can get a good idea what it does by reading the API for Xamarin Forms.

When a program is compiled, linked, and run, the XAML code is embedded in the assembly, then converted at runtime into a data structure by LoadFromXaml. The code that converts the XML to a data structure is, of course, not open sourced, but you can read how it works using a disassembly (e.g., with DotPeek).

I’ll go over several examples which illustrate some of the ways you can specify a view, and connect it up with a model, since that is what you will want to do 99% of the time.

Disassociated View

After creating an app, change the Label Text property assignment with a simple “Hello World”, i.e., a static string. In this case, there is no associated information with the view. Everything in the view is self-contained. I refer to this as a disassociated view.

Note, Label is an XML element, but it’s converted into an object of type Xamarin.Forms.Label. Text, VerticalOptions, and HorizontalOptions are XML attributes, properties of the Label object. The declaration x:Class=”App1.Page1″ is a directive that clues the XAML translator to generate C# source code for the class. That’s done while you edit the XAML file in the IDE.

Another important note here. A property of an object can be set one of two ways in XAML:

  • a property element, where the property and assigned value is expressed as a nested XML element of the containing object.
  • a property attribute, where the property and assigned value is expressed as an XML attribute.

Above, you see the property attribute Text. Below, you’ll see property element BindingContext.

View with Binding

Most of the time, a UI needs to get information from a Model. To do that, you need a binding, which is an association of the view to another object. In fact, if the binding is between the UI and an object derived from IObserverableObject, then it can do magic. (Note, for a discussion of MVVM, see So What Exactly is a View-Model?.)

A binding consists of (1) a context assignment, and (2) a binding assignment. Note: nowhere are these terms defined in the spec or by anyone else. However, in order to talk about binding, you have to have a terminology. If you are so inclined, you can read how binding is implemented in the MS documentation.

The context assignment in this example is specified in the XML element <ContentPage.BindingContext>…</ContentPage.BindingContext>. In terms of C# code, it would be the same as “BindingContext = …”. Note how the assignment is written–using a contained element.

The binding assignment associates an object with the view: Label=”{Binding MessageOfTheDay}”. When the UI is constructed, a tree walk is performed up the predecessors until a context is found with the property. NB: the property specified in the binding expression must be a property, not a field or method, otherwise the binding fails.

Singletons

Sometimes you may want a binding to be shared between multiple ContentPage, e.g., a model. In this situation, you can use a x:Static extension.

A singleton property is defined and used in one XAML file.

There is no way to create a singleton tree node, but you can share the tree node using x:Key. XAML extensions are discussed below.

Binding Lists

A list of objects can be consumed by the view. In Xamarin, ListView has the property ItemsSource, which contains an enumerable collection to iterate over and create children. The semantics of setting ItemsSource is not documented, but essentially:

IEnumerable<T> collection = ....;
foreach (T t in collection) {Add(new Label(t));}

If the ListView XAML specifies a <ListView.ItemTemplate>, the ListView will contain a collection of items of the type specified in the template. By default, it creates a Label. See the documentation.

 

Observer/Observable Pattern

After getting used to XAML, at some point, you will want information in the view to update whenever the corresponding model changes while it’s happening. The UI requires the binding object have an INotifyPropertyChanged interface. In the properties that change, OnPropertyChanged() is called to produce the side effect in the view.

 

View and Commands

There are two schools for handling events when the user clicks a button or enters text in a data text box. The “old school” is to add an event handler to the code-behind file to make some response, e.g., the OnButtonClicked() override. (In fact, Xamarin shows how you would do that in their last example of this introduction to XAML.) The "new school” is to add a Command property assignment to the XAML, and add the handler into the “ViewModel”. (Note, as someone else points out, placing all the handlers in the ViewModel reduces it to a code behind file.

 

Debugging XAML

Binding problems can be resolved sometimes by modifying the binding assignment. At the moment, there doesn’t seem to be a way to check if a context is null in Xamarin Forms. In WPF, it would be accomplished using PresentationTraceSources: add a trace statement, Text=”{Binding MessageOfTheDay, diag:PresentationTraceSources.TraceLevel=High}”; define the namespace “diag”, xmlns:diag=”clr-namespace:System.Diagnostics;assembly=WindowsBase”.

If you have a non-null binding context, you can debug the binding when it’s accessed, either in the property or with a data converter.

XAML Extensions

XAML has a special namespace for extensions to the XAML processor. We’ve already seen some of those, e.g., x:Class.

 

  • x:Class – generate a C# class with the given name.
  • x:Name – generate a C# property.
  • x:Reference – use a C# property. Goes in hand with x:Name.
  • x:Key – create a value, in the context of a resource.

An example containing some of these directives follows.

 

Conclusions

XAML is an expressive tree-oriented data structure language for UI. Unfortunately, there isn’t a specification of the language, but there are some well-known idioms to help you use it effectively. Enjoy!

Additional Information

Nathan, Adam. XAML unleashed. Sams Publishing, 2014.

As usual, I provide the source for all examples, here in git.

 

 

Visual Studio 2015 MRU List Cleanup

Somewhere in the many years that Microsoft has been developing Visual Studio, they’ve managed to completely mess up the Most Recently Used (MRU) list of projects in the Start Page. It used to be that if you opened a project, it would appear at the top of the list the next time you open Visual Studio. Unfortunately, that is no longer the case. Visual Studio 2015 now sorts the list in some bizarre manner, and it adds .csproj files (sub-projects) to the MRU list of a solution that I opened. Rather than try to raise the issue with Microsoft, I decided to write a small program that can reorganize and clean the MRU list to what I want.

The program (source in git here) is a WPF application that, when run as administrator, displays a grid of the project, location, whether it exists, date created, and date accessed. By clicking on the column, the registry data for the MRU list is re-ordered by that column. If you want to remove an entry, select the row(s), then hit the Delete key. Double clicking of an item opens the default program for the file.

Enjoy! –Ken

NOTE: I’ve since filed a bug with MS. VS overwrites the MRU list with stale data on the close of VS. https://connect.microsoft.com/VisualStudio/feedback/details/2648192. This is part of the problem with MRU lists in VS.

Mongo, Restheart, and Dokku

Mongo is a popular NoSQL database nowadays. It has several advantages compared to relational databases (schema-less, key-value store, scalable, distributed, propagated consistency) but the main advantage, IMHO, is that JSON is the lingua franca for the data structures it stores and the queries you use. JSON is a nice, simple data structure representation. It can be easily passed between the database and the application; and it can be converted to/from a string and an object in the native language you use. Mongo has many native-language APIs available for interfacing your application with the database, so you should be able to connect your application with Mongo.

Unfortunately, Xamarin Forms applications, written in C#, are Portable Class Library (PCL) applications, and the C# API for Mongo can’t work. Unfortunately, PCL apps and libraries can only link with other PCL libraries that have the same or additional target platforms. So, a PCL app that is targeting Windows, Android, and iOS cannot link with a library that only targets Windows, or only Android, or only iOS.

However, all is not lost. Restheart is an open source REST API server for Mongo databases. You can easily write a layer to encapsulate the calls that you need to access your Mongo database. There aren’t many functions you have to write beyond the usual CRUD, and the signatures for the method are just strings.

Setup

The installations instructions are on the Mongo.org website. Get the latest production version of Mongo. Then, execute the installation file. After it completes, create a directory for the database.

md data/db

To run Mongo, type

mongod --dbpath data/db

To set up Restheart, either copy the latest from Restheart.org, or clone the git repository for Restheart. If you are going to build it from scratch, you will need Maven, Java, and various other tools. Note, I highly recommend you build Restheart from git because the documentation is quite poor, and the only really good way to understand the server is to debug it.

To run Restheart, type java -jar ./restheart/target/restheart.jar, or the appropriate jar file. You can specify a configuration file for Restheart as a parameter when executing the jar.

CRUD

In a SQL database, data are stored in tables. In Mongo, data are stored in a collection. As with SQL, Mongo has CRUD statements for access to the database. The equivalent in Mongo of a row in a SQL table is a document, and is simply a JSON string. A projection of a JSON structure is equivalent to a projection in SQL. If you convert the JSON into a Newtonsoft JObject, you can make a projection of one key/value pair using the [] operator. As in SQL, an index can be created to improve search time.

Examples

SQL Op
Operation
Example
Example in Mongo shell
Example in Restheart
 Create database
 Create a database named db1.
 Create a database named db1.
use db1
NOTE: you need to insert a collection to actually create the database while using the Mongo shell.
 PUT
http://localhost:8080/db1/
NOTE: Do not set data or you will create a record with that data in the database. It can’t be deleted!
Create table
Create collection
 Create a collection named “col”.
db.createCollection(“col”)
PUT
http://localhost:8080/db1/col
Insert a row in a table
Insert a document in a collecton
Insert {“a1″:”b1”} in collection col.
 db.col.insert({“a1″:”b1”})
POST
http://localhost:8080/db1/col
payload is {“a1″:”b1”}
header is Content-Type: application/json
NOTE: The record type/value doesn’t have to be unique. So, you can insert duplicates if you like.
Read a row
Read a document
Find {} — find all records in collection col.
db.col.find({})
or just db.col.find()
GET
http://localhost:8080/db1/col
header is Content-Type: application/json
Read a row
Read a document
Find { “a1” : <value> } — find all records with key a1 in collection col.
db.col.find({“a1”:{$regex : “.*” }})
GET
http://localhost:8080/db1/col?filter={“a1″:{$regex:”.*”}}
NOTE: Make sure to note the correct syntax. The Restheart arg parser is very, very poor. E.g., using parentheses instead of equal sign:
http://localhost:8080/db1/col?filter={“a1″:{$regex:”.*”}}
This will return all records with a1, which is not what you intended!
To limit the find to the “first” record (whatever that means), add ‘&pagelimit=1’ to the args of the GET url.
Read a row
Read a document with projection
Find { “a1” : <value> } — find all records with key a1 in collection col, but only show keys of “cc”. For example, suppose there is one record, {{“aa”:”bb”}, {“cc”:”dd”}}. Return {“cc”:”dd”}.
db.col.find({“aa”:{$regex : “.*” }}).projection({“cc”:1})
http://localhost:8080/db1/col?filter={“aa”:{$regex:”.*”}}&keys={“cc”:1}
 Update a row
 Update a document
Update {“a1″:”*.”} to {“a1″:”asdf”}
db.col.update({“a1″:{$regex:”.*”}},{“a1″:”xx”})
PATCH
http://localhost:8080/tb3/col/*?filter={“a1″:”.*”}
header is Content-Type: application/json
payload is {“a1″:”asdf”}
 Delete a row
 Delete a document
 Delete a record with a particular key/value, { “a1” : <value> }.
 db.col.remove({“a1″:{$regex:”.*”}})
 DELETE
http://localhost:8080/db1/col/*?filter={“aa”:{$regex:”.*”}}
 Delete a table
 Delete a collection
 Nuke an entire collection col.
 db.col.drop()
 DELETE
http://localhost:8080/db1/col
 Delete database
 Delete database
 Nuke the entire database db1.
 db.dropDatabase()
 DELETE
header contains If-Match:<the id of the database>, e.g., 570e3dc71d9563251070fab3
http://localhost:8080/tb1/

 

NOTE: Restheart normally requires an “ETag” header entry, i.e., “If-Match: 570e3dc71d9563251070fab3”, where that number is an ID of the record to delete. You can turn off ETag checking in a configuration file, which you can specify on the java command line.

To get a value, you will have to parse the json for the field of interest. You can use projection to help you with that.

Running Mongo and Restheart on Dokku

To run a Mongo database and a Restheart server on Dokku, you can get a copy of my Github example, then modify it for your needs. The example is here.

References

https://softinstigate.atlassian.net/wiki/display/RH/Installation+and+Setup#InstallationandSetup-7.3.MongoDBauthenticationwithjustenoughpermissionsauth-with-jep

https://softinstigate.atlassian.net/wiki/display/RH/Query+Documents

http://www.tutorialspoint.com/mongodb/mongodb_query_document.htm

https://docs.mongodb.org/manual/reference/method/db.collection.find/

https://www.mongodb.org/downloads#production

http://www.codeproject.com/Articles/1087008/Mongo-DB-Tutorial-and-Mapping-of-SQL-and-Mongo-DB

http://stackoverflow.com/questions/tagged/restheart

https://en.wikipedia.org/wiki/MongoDB

 

GoDaddy left at the Docker

I’m in the process of checking out the advantages and disadvantages of GoDaddy’s new Cloud Server product, which has just been announced as generally available. It has few features, less compared to DigitalOcean, which has been available for a few years. AWS, which has been available for even longer, is generally the gold standard–if you like, or need, a cloud platform with every conceivable tweakable option. You have to wonder what took GoDaddy so long. And, even with years to think about what to implement in order to compete with DigitalOcean and Amazon, it has at least one problem which the others don’t.

As I am currently a tepid fan of Dokku, I decided to check out how a GoDaddy VPS would perform compared to a VPS on DigitalOcean. However, I spent a day or two figuring out that GoDaddy has a problem with routing Docker container network traffic. You can see a discussion of the type of problem here, and a solution provided by GoDaddy here. The tweek involves some changes to iptables. Below is a script that wraps it all together: it installs Docker and fixes the iptables for a GoDaddy VPS. Enjoy!

 

Setting Up Dokku via Command-Line Script

Dokku is a PAAS implementation, useful for websites, servers, or development. As it notes in its website, the installation in a Debian host running Bash is just three steps:

# only works on debian systems!
wget https://raw.githubusercontent.com/dokku/dokku/v0.5.3/bootstrap.sh
sudo DOKKU_TAG=v0.5.3 bash bootstrap.sh
# go to your server's IP and follow the web installer

The last “step” is written as a Bash comment. It states to complete the installation via a web browser. If you’re like me, this is a surprise, completely opposite of command-line driven provisioning. Using Fiddler, I conjured up a script to fix this problem. Enjoy!

(Note: I asked the question in the Dokku issue page, and the reply pointed to using debconf. You can use that. Or, you can use this script–which I think is easier.)

#
# Set up Dokku via command line

set -e

if [ "$#" -ne 1 ]; then
 echo "Try this: cat ~/.ssh/id_rsa.pub | ${0##*/} -"
 exit 1
fi

export IP=`ip route get 8.8.8.8 | awk '{print $NF; exit}'`
export KEY=$(</dev/stdin)

if [ "${KEY/ssh-rsa}" = "$KEY" ] ; then
 echo "Input is not a ssh key."
 exit 1
fi

curl "http://localhost" > /dev/null 2>&1

export FKEY=`echo -ne "$KEY" | hexdump -v -e '/1 "%02x"' | sed 's/\(..\)/%\1/g'`

cat <<EOF | curl -XPOST --data @- "http://localhost/setup"
keys=$FKEY&hostname=$IP
EOF