Archive
Select and #Upload a file to #AWS S3 using #WinJS
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”,
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/” + filename;
}
Using #Fortumo payments from within a #Cordova App @Fortumo
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.
Modal popup replacement for ion-select #ionicFramework
Download: https://1drv.ms/u/s!AlkUa-u6o9yJl2Mnv399EnAz4NA8
If you want to extend the functionality of ion-select, and would like to display it as a modal popup, then you can use this code above.
You define the data in $rootScope, and you can edit the template in myPopupBox to determine the properties etc.
This code was written by someone else, it wasn’t me – not claiming credit / responsiblity for it 🙂
#NoSQL Implement persistent key/value storage in #JavaScript
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.
Download a webpage as a #PDF
If you have a webpage that you’d like your users to download and take with them, such as a ticket, receipt, map or timetable; then offering a PDF download is a handy way to do this. However, if your content is dynamic, then you may find that you’ve hit a problem.
By adding the following HTML to your page, you can create a download link for the current page; so your users can have a PDF version of what they are looking at;
<a onclick=”location.href=’http://pdf.apixml.net/download.aspx?url=’
+ location.href” >
<img src=”https://cdnjs.cloudflare.com/ajax/libs/foundicons/3.0.0/svgs/fi-page-export-pdf.svg” />
</a>
You can get more info on this at http://pdf.apixml.net/
Calling a #JSON #REST #API with #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
- Update your homebrew to latest:
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.Projectdef 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()]
enddef application do
[applications: [:logger, :httpotion]]
enddefp 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”]
endend
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.
#Cloudflare App development using Avatar #API
Cloudflare, one of the largest CDN / DDOS protection networks in the world launched a $100M developer fund, so I thought I should take the time to learn a bit about it.
Cloudflare apps, are effectively HTML widgets that you can embed in your webpages, I guess to try and make it easier for developers to drag and drop code that was developed by third parties.
The demo video showed how to use Cloudflare apps to embed a Youtube video into a webpage. Obviously a contrived example, since it would be just as easy to embed the youtube video, than to embed a cloudflare app pointing to a youtube video, but it gets you started.
I wanted to create a cloudflare app that implements the functionality of Avatar API (http://www.avatarapi.com) – a service that returns profile pictures from email addresses.
Effectively, the app has two component parts, an install.json file that defines the properties of the app, and app.js a javascript file that implements the app.
Here’s my install.json
{
“resources”: {
“body”: [
{
“type”: “script”,
“src”: “./app.js”
}
]
},
“options”: {
“properties”: {
“location”: {
“type”: “object”,
“format”: “element”,
“title”: “location”
},
“email”: {
“type”: “string”,
“title”: “Email Address”
}
}
}
}
And here’s my app.js
(function() {
if (INSTALL_OPTIONS.email.indexOf(“@”) == -1) {
INSTALL_OPTIONS.email = “peter.smith@gmail.com”;
}
var el = CloudflareApps.createElement(INSTALL_OPTIONS.location);
el.innerHTML = “https://www.avatarapi.com/iframe.aspx?email=%20+%20INSTALL_OPTIONS.email%20+%20&size=128“;
})()