Archive

Author Archive

We’re now on #NPM; making it easy to use our #APIs from #NodeJS

NPM

And here’s our first set of 20 Packages…

Categories: Uncategorized

Get a country code from an address in c#

atlas-18

If you have a partial address, or just a town / city name and you’d like to get the country code (ISO3166) then you can use Google’s geocode API from c# as follows;

The Google API key is not strictly necessary, but it’s recommended, as they will probably throttle use for unauthenticated calls.

public static string GetCountryFromAddress(string address)
{

try
{
// API key is recommended, but not required
const string strGoogleApiKey = “….”;
var strUrl = “https://maps.googleapis.com/maps/api/geocode/json?address={0}&key={1}”;
strUrl = string.Format(strUrl, address, strGoogleApiKey);
var wc = new WebClient();
var strJson = wc.DownloadString(strUrl);
var json = JObject.Parse(strJson);
var jResult = json[“results”][0];
var jAddressComponents = jResult[“address_components”];
foreach (var jAddressComponent in jAddressComponents)
{
var jTypes = jAddressComponent[“types”];
if (jTypes.Any(t => t.ToString() == “country”))
{
return jAddressComponent[“short_name”].ToString();
}
}
return null;
}
catch
{
return null;
}
}

Categories: Uncategorized

#Headless CMS using C#, #NodeJS or #Java

hcms

Headless Content Management – (https://www.headlesscontentmanagement.com/) is a service that decouples the work typically done by content writers and developers. It is designed for use in situations where the content is not going to be viewed on a web-page, but instead is going to be displayed within a mobile app or desktop application.

There are many CMS systems out there, and most of them have APIs. Your content team are probably familiar with the likes of WordPress, Joomla and Dotnetnuke – but most operate on the premise that the content is going to be viewed on a web page via a web browser. Headless Content Management makes no such assumption, and won’t help you display your content online – it just exposes the content via a set of APIs, XML and JSON based.

Headless CMS can also be used in situations where you have an existing website that isn’t based on a CMS platform like WordPress / Joomla etc. So if you have a in-house developed bespoke website, and need to make it easy for content writers to add and edit content on your website. You can use Headless Content Management to manage your content, then have your existing website call our APIs, in order to retrieve the content to be displayed.

The interface with HeadlessContentManagement.com can be done via many different languages, here are three popular examples – C#, NodeJS and Java

C#

// You need to make a service reference to https://HeadlessContentManagement.com/api.asmx
var api = new api.APISoapClient();

// Replace the username and password with those defined on HeadlessContentManagement.com
var strUsername = “demouser@webtropy.com”;
var strPassword = “demo”;

Console.WriteLine(“Select one of the following articles by it’s id number”);
var articles = api.ListArticles(strUsername, strPassword);
foreach(var article in articles)
{
Console.WriteLine(string.Format(“{0}. {1}”, article.id, article.subject));
}
// Ask the user to enter a number
var strId = Console.ReadLine();
var intArticleId = Convert.ToInt32(strId);

// Get that one Article
var selectedArticle = api.ReadArticle(strUsername, strPassword, intArticleId);
Console.WriteLine(selectedArticle.body);
Console.ReadLine();

csharp

NodeJS

var request = require(‘request’); // run npm install request
var email = ‘demouser@webtropy.com’;
var password = ‘demo’;
request.post(
https://www.headlesscontentmanagement.com/ajax/ListArticles.aspx’,
{form:{email:email,password:password}},
function (error, response, body) {
if (!error && response.statusCode == 200) {
showArticleSummary(JSON.parse(body));
}
else
{
console.log(response.statusCode);
console.log(body);
}
}
);

function showArticleSummary(Articles)
{
console.log(“Please Select one of the following article ids”);
for(var i in Articles)
{
var Article = Articles[i];
console.log(Article.id + “. ” + Article.subject);
}
process.stdout.write(“>”)
var stdin = process.openStdin();

stdin.addListener(“data”, function(d) {
var strArticleId = d.toString().trim();
var intArticleId = parseInt(strArticleId);
process.stdin.pause();
ReadArticle(intArticleId);
});
}

function ReadArticle(intArticleId)
{
request.post(
https://www.headlesscontentmanagement.com/ajax/ReadArticle.aspx’,
{form:{email:email,password:password, id:intArticleId}},
function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(JSON.parse(body).body);
}
else
{
console.log(response.statusCode);
console.log(body);
}
}
);
}

nodejs

Java

import java.net.HttpURLConnection;
import java.net.URL;
import java.net.MalformedURLException;
import java.io.IOException;
import java.io.*;
import org.json.JSONException; // requires org.json package from https://mvnrepository.com/artifact/org.json/json/20170516
import org.json.JSONObject;
import org.json.JSONArray;

public class HeadlessContentManagement {

public static void main(String[] args) {

 

String strJson = getJson(“https://www.headlesscontentmanagement.com/ajax/ListArticles.aspx”, “email=demouser@webtropy.com&password=demo”);

System.out.println(“Got Response”);

JSONArray array = new JSONArray(strJson);

for(int i = 0 ; i < array.length() ; i++){

JSONObject article = array.getJSONObject(i);

System.out.println(article.getInt(“id”) + “. ” + article.getString(“subject”));

}

}

public static String getJson(String serverUrl,String param){

StringBuilder sb = new StringBuilder();

String http = serverUrl;

HttpURLConnection urlConnection = null;
try {
URL url = new URL(http);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoOutput(true);
urlConnection.setRequestMethod(“POST”);
urlConnection.setUseCaches(false);
urlConnection.setConnectTimeout(50000);
urlConnection.setReadTimeout(50000);
urlConnection.connect();
OutputStreamWriter out = new OutputStreamWriter(urlConnection.getOutputStream());
out.write(param);
out.close();
int HttpResult = urlConnection.getResponseCode();
if (HttpResult == HttpURLConnection.HTTP_OK) {
BufferedReader br = new BufferedReader(new InputStreamReader(
urlConnection.getInputStream(), “utf-8”));
String line = null;
while ((line = br.readLine()) != null) {
sb.append(line + “\n”);
}
br.close();
return sb.toString();
} else {
System.out.println( urlConnection.getResponseMessage());
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (urlConnection != null)
urlConnection.disconnect();
}
return null;
}
}

Categories: Uncategorized

You’re linking to your #socialmedia wrong! @urlgenius

Categories: Uncategorized

Select and #Upload a file to #AWS S3 using #WinJS

winjslogo-purple-background

So, this is how to select a file from your phone, and upload it to Amazon S3, using the cordova plugin cordova-plugin-windows-filepicker  and some ASP.NET code on the server.

Here’s the WinJS (Javascript code)

window.plugins.WindowsFilePicker.open(function(uri) {
debugger;
var url = new Windows.Foundation.Uri(uri);
Windows.Storage.StorageFile.getFileFromApplicationUriAsync(url).then(function(file) {
debugger;
Windows.Storage.FileIO.readBufferAsync(file).done(function(buffer) {
debugger;
var bytes = new Uint8Array(buffer.length);
var dataReader = Windows.Storage.Streams.DataReader.fromBuffer(buffer);
dataReader.readBytes(bytes);
dataReader.close();
var base64 = btoa(String.fromCharCode.apply(null, bytes));
$http({
method: ‘POST’,
url: “http://www.yourserver.com/s3upload.aspx&#8221;,
headers: {
‘Content-Type’: ‘application/x-www-form-urlencoded’
},
transformRequest: function(obj) {
var str = [];
for (var p in obj)
str.push(encodeURIComponent(p) + “=” + encodeURIComponent(obj[p]));
return str.join(“&”);
},
data: {
“data”: base64,
“extension”: file.fileType.substring(1)
}
}).then(function(response) {
$scope.file = response.data;
}, function(error) {
debugger;
});
});
}, function(error) {
debugger;
});
}, function(error) {
debugger;
});

This code is using AngularJS, but you can modify the AJAX part to use XHR or JQuery, as you need. – when complete it sets $scope.file to a URL hosted on Amazon AWS S3.

And here’s the code for the server-side:

var strBase64 = Request.Form[“data”];
var strExtension = Request.Form[“extension”];
var bBase64 = Convert.FromBase64String(strBase64);
var strUrl = S3.Upload(bBase64, strExtension);
Response.Write(strUrl);

Where the S3 class is as follows (username / password removed)

public static string Upload(byte[] data, string extension)
{
var ms = new MemoryStream(data);
var filename = Guid.NewGuid().ToString(“D”) + extension;
var cfg = new AmazonS3Config { RegionEndpoint = Amazon.RegionEndpoint.EUWest1 };
const string bucketName = “faxoff”;
var s3Client = new AmazonS3Client(“xxxxxx”, “yyyyy”, cfg);
var fileTransferUtility = new TransferUtility(s3Client);
var fileTransferUtilityRequest = new TransferUtilityUploadRequest
{
BucketName = bucketName,
InputStream = ms,
StorageClass = S3StorageClass.ReducedRedundancy,
Key = filename,
CannedACL = S3CannedACL.PublicRead
};
fileTransferUtility.Upload(fileTransferUtilityRequest);
return “https://s3-eu-west-1.amazonaws.com/xxxxx/&#8221; + filename;
}

Categories: Uncategorized

Using #Fortumo payments from within a #Cordova App @Fortumo

82245285a393b02469f1ce15a4eccecc_fortumo-300x125

Fortumo offers a payment service based on premium SMS and direct carrier billing, it’s ideal for collecting micro-payments from customers who don’t have a credit card. It’s ideal for Android / Windows Phone apps.

They have great SDKs for native Android / Windows Phone, but if you’re developing a hybrid app, like based on Cordova, then you can use their WebSDK, and this is how I integrated it using the InAppBrowser

var webbrowser = window.open(“https://pay.fortumo.com/mobile_payments/dafc782dbdb9fd193b970f359af045a8“, “_blank”);

webbrowser.addEventListener(‘loadstart’, function (event) {
if (event.url == “https://infiniteloop.ie/“)
{
debugger;
}
});

Now, the long GUID marked in bold, and the return url will be different for your application – you’ll get this from Fortumo.

Categories: Uncategorized

Modal popup replacement for ion-select #ionicFramework

Categories: Uncategorized

#NoSQL Implement persistent key/value storage in #JavaScript

nosql

nosql.apixml.net

Implement persistent Key/Value storage using client side java script only

Installation

    http://nosql.apixml.net/nosql.js

Save data

    var id = nosql.guid();
    nosql.put(id,"hello world").then(function (data) {
           // This stores "Hello world"
    });

Load data

    nosql.get(id).then(function(data){
            alert(data);
    });

Each key in the store must be a GUID (i.e. 9ED4B528-7F5F-3074-BBBF-947C6133ED13), this is to prevent overlaps between your keys and other user’s keys. Data can be any string, typically this would be json, but you can store any UTF8 string (not binary data).


This is backed by a REST API, which you make a GET, POST, or DELETE request to http://nosql.apixml.net/%5BGUID%5D to retrieve, update/insert and delete data respectively.

Categories: Uncategorized

Download a webpage as a #PDF

Categories: Uncategorized

Calling a #JSON #REST #API with #Elixir

121ada6-elixir

Elixir is based on Erlang, and is being used by some high profile software companies like Moz and Pinterest, I’ve just used it to develop a proof of concept app, which calls a JSON based API from here; https://www.regcheck.org.uk, returning car details based on a number plate. The code example below has the username/password removed, but you can create a free account for testing.

First off, if you haven’t done so; install elixir on OSX as follows;

Mac OS X

  • Homebrew
    • Update your homebrew to latest: brew update
    • Run: brew install elixir

Windows, and other platforms are available, and the code below is platform agnostic.

Create a new blank application by typing

mix new example

After. which, you cd into the example directory, and edit the mix.exs file to the following;

defmodule Example.Mixfile do
use Mix.Project

def project do
[app: :example,
version: “0.1.0”,
elixir: “~> 1.4”,
escript: [main_module: Example], # <- add this line
build_embedded: Mix.env == :prod,
start_permanent: Mix.env == :prod,
deps: deps()]
end

def application do
[applications: [:logger, :httpotion]]
end

defp deps do
[
{:httpotion, “~> 3.0.2”},
{:poison, “~> 3.1”}
]
end
end

Lines that I have changed have been highlighted in bold, the line referring to escript defines the entry point, and the deps section determines the libraries I require to run my code example, here I am using httpotion, which is a HTTP client library, and Poison, which is a JSON parsing library.

The next step is to edit the file in lib/example.ex, with the following code (username and password removed)

defmodule Example do

def main(args) do
IO.puts “V 1.1.5”
IO.puts “Searching for Irish Reg Number: #{List.first(args)}”
response = HTTPotion.get “https://www.regcheck.org.uk/api/json.aspx/CheckIreland/#{List.first(args)}“, [basic_auth: {“username”, “password”}]
json = Poison.Parser.parse!(response.body)
IO.puts json[“Description”]
end

end

Where I am calling a URL with basic authentication, receiving JSON back, then parsing that JSON to print it’s Description property to screen.

To run this application type:

$ mix deps.get

$ mix escript.build

$ ./example 05-D83975

where mix.deps.get gets the dependencies for the project, including Poison and Httpotion, and only needs to be run once.

mix escript.build compiles the application, and running ./example followed by an Irish car registration number builds it.

The car registration API not only runs in ireland, but also the UK, USA, Australia, India, South Africa and many other countries, you can check out RegCheck.org.uk for more details on this.

Screen Shot 2017-07-08 at 13.50.20

Categories: Uncategorized