Archive

Archive for September, 2015

Alternative to JSONP for One-shot webservices #AJAX

September 30, 2015 Leave a comment

Cross-domain restrictions prevent you from exchanging data from domainA.com to domainB.com , however, there are some workarounds, such as JSONP, where you trick the browser into loading a script from another domain, and have that script call back to your page – It does mean however, that the webservice has to be specifically designed to include the call back to your javascript callback function.

However, this is another workaround that does not require any specific format in the return value of the webservice, in effect, the return value is ignored, so it’s only for one-shot “fire and forget” webservices.

Here’s an example, where you can send email from javascript, using the webservice from www.directtomx.com 

Email = {
Send : function (to,from,subject,body,apikey)
{
if (apikey == undefined)
{
apikey = Email.apikey;
}
var nocache= Math.floor((Math.random() * 1000000) + 1);
var strUrl = “http://directtomx.azurewebsites.net/mx.asmx/Send?”;
strUrl += “apikey=” + apikey;
strUrl += “&from=” + from;
strUrl += “&to=” + to;
strUrl += “&subject=” + encodeURIComponent(subject);
strUrl += “&body=” + encodeURIComponent(body);
strUrl += “&cachebuster=” + nocache;
Email.addScript(strUrl);
},
apikey : “”,
addScript : function(src){
var s = document.createElement( ‘link’ );
s.setAttribute( ‘rel’, ‘stylesheet’ );
s.setAttribute( ‘type’, ‘text/xml’ );
s.setAttribute( ‘href’, src);
document.body.appendChild( s );
}
};

Then it would be called like this –

window.onload = function(){
Email.apikey = “– Your api key from directtomx.com —“;
Email.Send(“swordfish1234@printfromipad.com”,”info@webtropy.com”,”Sent from JS API”,”Worked!”);
}

It works by pretending that the webservice call is actually a CSS stylesheet. The CSS will be invalid, but this type of error would be swallowed silently by the browser.

Advertisements
Categories: Uncategorized

Backendless form using Parse and Bootstrap

September 29, 2015 Leave a comment

If you want to collect information from users, but don’t need to act on the information right away, for example, a Survey, or unsubscribe form, then you’d think you’d need to start creating a database table, connecting up server side code, etc, etc.,

This is obviously one way to go about it, but sometimes, you’d like a quicker solution, that just uses javascript code, on the client side, and wouldn’t it be nice if I didn’t have to upload Bootstrap, jquery, etc., to the server, and load everything from CDNs?, so something that would typically require a database, business layer code, hundreds of images, css, and javascript libraries can just be deployed with one file?

Which is where Parse comes in. You can use it to store and retrieve arbitrary javascript objects in a persistent manner, so that you don’t have to create a database or middleware.

So, I have a simple unsubscribe form, where I want to capture and store users’ email addresses, and then I’ll export them back out of Parse whenever it comes time to remove bad emails from my list.

Here’s the code in javascript;

$(init);
function init()
{
Parse.initialize(“xxx”, “xxxx”);
$(“#btnReport”).bind(“click”,btnReport_click);
}
function btnReport_click()
{
var Unsubscription = Parse.Object.extend(“Unsubscription”);
var unsubscription = new Unsubscription();
unsubscription.save({email: $(“#ReportedBy”).val()}).then(function(object) {
bootbox.alert(“Thanks, we’ve recorded your request.”);
});
}

I’ve replaced my Parse keys with xxx – you’ll need to get your own. It creates a new Unsubscription object, then saves it with the property “email”, and lets the user know when it’s done.- This is then persistently stored on Parse’s servers.

And, the rest of the form, all loaded from CDN’s

<html >
<head>
<meta name=”viewport” content=”width=device-width, initial-scale=1″>
<link rel=”stylesheet” href=”http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css”&gt;
http://code.jquery.com/jquery-1.11.3.js
http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js
http://cdnjs.cloudflare.com/ajax/libs/bootbox.js/4.4.0/bootbox.js
http://www.parsecdn.com/js/parse-1.6.2.min.js

$(init);
function init()
{
Parse.initialize(“xxx”, “xxx”);
$(“#btnReport”).bind(“click”,btnReport_click);
}
function btnReport_click()
{
var Unsubscription = Parse.Object.extend(“Unsubscription”);
var unsubscription = new Unsubscription();
unsubscription.save({email: $(“#ReportedBy”).val()}).then(function(object) {
bootbox.alert(“Thanks, we’ve recorded your request.”);
});
}

</head>
<body>
<form class=”form-horizontal”>
<fieldset>
<legend>Unsubscibe</legend>

Your email

If you do not want to receive any more email from us, just enter it here.

</div>

</div>
</fieldset>
</form>
</body>

Categories: Uncategorized

Validation in Windows phone, flash textbox red if invalid =WP8

September 23, 2015 Leave a comment

Here’s some nice code to flash a textbox red if the input is invalid – It’s tested in WP8.1

private void Warn(Control target)
{
var elementColour = ((SolidColorBrush)target.Background).Color;
ColorAnimation ca1 = new ColorAnimation();
ca1.Duration = new Duration(TimeSpan.FromSeconds(0.5));
ca1.From = elementColour;
ca1.To = Color.FromArgb(255, 255, 0, 0);
Storyboard.SetTarget(ca1, target);
Storyboard.SetTargetProperty(ca1, new PropertyPath(“UIElement.Background.Color”));
// alternative tested PropertyPath
// “Panel.Background.Color”
// “Panel.Background.SolidColorBrush.Color”
// “(Panel.Background).(SolidColorBrush.Color)”
Storyboard sb = new Storyboard();
sb.Children.Add(ca1);
sb.Begin();
sb.Completed += (a, b) =>
{
ColorAnimation ca2 = new ColorAnimation();
ca2.BeginTime = TimeSpan.FromSeconds(1);
ca2.Duration = new Duration(TimeSpan.FromSeconds(0.5));
ca2.From = Color.FromArgb(255, 255, 0, 0);
ca2.To = elementColour;
Storyboard.SetTarget(ca2, target);
Storyboard.SetTargetProperty(ca2, new PropertyPath(“UIElement.Background.Color”));
Storyboard sb2 = new Storyboard();
sb2.Children.Add(ca2);
sb2.Begin();
};
}

Categories: Uncategorized

Generate #pkpass – Apple Passbook coupons from C#

September 21, 2015 8 comments

This is quite a long lump of code, and it has some prerequisites, that you’ll need to do first.

1. you’ll need to have all your graphic assets in a folder, pre-prepared

2. You’ll need to install the apple root cert into your cert store, from here http://www.apple.com/appleca/AppleIncRootCertificate.cer

3. And, the hardest step, you’ll need to generate a p12 file for your passbook type, – here’s a good tutorial to do this;

http://www.raywenderlich.com/20734/beginning-passbook-part-1 – or

https://blog.dotnetframework.org/2015/09/21/creating-apple-passbook-pkpass-coupons-from-windows/

  • Now, first I’m going to declare some useful objects

using System.Collections.Generic;
using System.Linq;

namespace libPkPass
{
/// <summary>
/// Objects representing the JSON files contained in the .pkpass file
/// </summary>
public class JsonObjects
{
/// <summary>
/// The image assets used to make the coupon more attractive
/// </summary>
public enum AssetTypes
{
/// <summary>
/// 320 x 122
/// </summary>
strippng,
/// <summary>
/// 640 x 244
/// </summary>
stripAt2xpng,
/// <summary>
/// 29 x 29
/// </summary>
iconpng,
/// <summary>
/// 58 x 58
/// </summary>
iconAt2xpng,
/// <summary>
/// 50 x 50
/// </summary>
logopng,
/// <summary>
/// 100 x 100
/// </summary>
logoAt2xpng,
/// <summary>
/// Describes the text content of the coupon
/// </summary>
passjson
}
/// <summary>
/// The Manifest (contents of the zip)
/// </summary>
public class Manifest
{

/// <summary>
/// Gets or sets the strip.png hash
/// </summary>
/// <value>
/// The strip.png.
/// </value>
public string strippng { get; set; }

/// <summary>
/// Gets or sets the strip@2x.png hash.
/// </summary>
/// <value>
/// The strip@2x.png.
/// </value>
public string stripAt2xpng { get; set; }

/// <summary>
/// Gets or sets the icon.png hash
/// </summary>
/// <value>
/// The icon.png.
/// </value>
public string iconpng { get; set; }

/// <summary>
/// Gets or sets the icon@2x.png hash
/// </summary>
/// <value>
/// The icon icon@2x.png.
/// </value>
public string iconAt2xpng { get; set; }

/// <summary>
/// Gets or sets the logo.png hash.
/// </summary>
/// <value>
/// The logo.png hash.
/// </value>
public string logopng { get; set; }

/// <summary>
/// Gets or sets the logo@2x.png hash.
/// </summary>
/// <value>
/// The logo@2x.png.
/// </value>
public string logoAt2xpng { get; set; }

/// <summary>
/// Gets or sets the pass.json.
/// </summary>
/// <value>
/// The pass.json.
/// </value>
public string passjson { get; set; }

/// <summary>
/// Gets the asset for the given type
/// </summary>
/// <param name=”type”>The type.</param>
/// <returns></returns>
public string GetAsset(AssetTypes type)
{
return Map.First(m => m.type == type).asset;
}
/// <summary>
/// A map of assets to types
/// </summary>
public static List<ManifestMapping> Map = new List<ManifestMapping>
{
new ManifestMapping {asset = “strip.png”, type = AssetTypes.strippng, property = “stripping”},
new ManifestMapping {asset = “strip@2x.png”, type = AssetTypes.stripAt2xpng, property = “stripAt2xpng”},
new ManifestMapping {asset = “icon.png”, type = AssetTypes.iconpng, property = “iconpng”},
new ManifestMapping {asset = “icon@2x.png”, type = AssetTypes.iconAt2xpng, property = “iconAt2xpng”},
new ManifestMapping {asset = “logo.png”, type = AssetTypes.logopng, property = “logopng”},
new ManifestMapping {asset = “logo@2x.png”, type = AssetTypes.logoAt2xpng, property = “logoAt2xpng”},
new ManifestMapping {asset = “pass.json”, type = AssetTypes.passjson, property = “passjson”},
};
}
/// <summary>
/// Encapsulates a map of assets to fields
/// </summary>
public class ManifestMapping
{
/// <summary>
/// The type
/// </summary>
public AssetTypes type;
/// <summary>
/// The property
/// </summary>
public string property;
/// <summary>
/// The file name
/// </summary>
public string asset;
}
/// <summary>
/// The Barcode representation of the coupon
/// </summary>
public class Barcode
{
/// <summary>
/// Gets or sets the message.
/// </summary>
/// <value>
/// The message.
/// </value>
public string message { get; set; }
/// <summary>
/// Gets or sets the format.
/// </summary>
/// <value>
/// The format.
/// </value>
public string format { get; set; }
/// <summary>
/// Gets or sets the message encoding.
/// </summary>
/// <value>
/// The message encoding.
/// </value>
public string messageEncoding { get; set; }
}
/// <summary>
/// The general details of the coupon
/// </summary>
public class Pass
{
/// <summary>
/// Gets or sets the format version.
/// </summary>
/// <value>
/// The format version.
/// </value>
public int formatVersion { get; set; }
/// <summary>
/// Gets or sets the pass type identifier.
/// </summary>
/// <value>
/// The pass type identifier.
/// </value>
public string passTypeIdentifier { get; set; }
/// <summary>
/// Gets or sets the serial number.
/// </summary>
/// <value>
/// The serial number.
/// </value>
public string serialNumber { get; set; }
/// <summary>
/// Gets or sets the team identifier.
/// </summary>
/// <value>
/// The team identifier.
/// </value>
public string teamIdentifier { get; set; }
/// <summary>
/// Gets or sets the name of the organization.
/// </summary>
/// <value>
/// The name of the organization.
/// </value>
public string organizationName { get; set; }
/// <summary>
/// Gets or sets the description.
/// </summary>
/// <value>
/// The description.
/// </value>
public string description { get; set; }
/// <summary>
/// Gets or sets the logo text.
/// </summary>
/// <value>
/// The logo text.
/// </value>
public string logoText { get; set; }
/// <summary>
/// Gets or sets the color of the foreground.
/// </summary>
/// <value>
/// The color of the foreground.
/// </value>
public string foregroundColor { get; set; }
/// <summary>
/// Gets or sets the color of the background.
/// </summary>
/// <value>
/// The color of the background.
/// </value>
public string backgroundColor { get; set; }
/// <summary>
/// Gets or sets the color of the label.
/// </summary>
/// <value>
/// The color of the label.
/// </value>
public string labelColor { get; set; }
/// <summary>
/// Gets or sets the barcode.
/// </summary>
/// <value>
/// The barcode.
/// </value>
public Barcode barcode { get; set; }
}
}
}

Then, although not strictly necessary, this code makes the json much prettier to read;

using System.Collections.Generic;
using System.Text;

namespace libPkPass
{
/// <summary>
/// Optional process, makes the json easier to read
/// </summary>
internal class JsonPrettyPrinter
{
/// <summary>
/// Optional process, makes the json easier to read
/// </summary>
/// <param name=”inputText”>The input text.</param>
/// <returns></returns>
public static string Process(string inputText)
{
var escaped = false;
var inquotes = false;
var column = 0;
var indentation = 0;
var indentations = new Stack<int>();
const int tabbing = 8;
var sb = new StringBuilder();
foreach (var x in inputText)
{
sb.Append(x);
column++;
if (escaped)
{
escaped = false;
}
else
{
switch (x)
{
case ‘\\’:
escaped = true;
break;
case ‘\”‘:
inquotes = !inquotes;
break;
default:
if (!inquotes)
{
switch (x)
{
case ‘,’:
sb.Append(“\r\n”);
column = 0;
for (int i = 0; i < indentation; i++)
{
sb.Append(” “);
column++;
}
break;
case ‘{‘:
case ‘[‘:
indentations.Push(indentation);
indentation = column;
break;
case ‘}’:
case ‘]’:
indentation = indentations.Pop();
break;
case ‘:’:
while ((column%tabbing) != 0)
{
sb.Append(‘ ‘);
column++;
}
break;
}
}
break;
}
}
}
return sb.ToString();
}
}
}

And finally, the magic bit

using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Web.Script.Serialization;
using System.Security.Cryptography.Pkcs;
using Ionic.Zip;

namespace libPkPass
{
/// <summary>
/// Generates .pkpass files
/// </summary>
public class PkPassGenerator
{
/// <summary>
/// Generates the .pkpass.
/// </summary>
/// <param name=”details”>The details.</param>
/// <param name=”assetsFolder”>The assets folder.</param>
/// <param name=”p12File”>The P12 file.</param>
/// <param name=”p12Password”>The P12 password.</param>
public static void GeneratePkPass(JsonObjects.Pass details, string assetsFolder, string p12File, string p12Password)
{
var strPass = JavascriptSerialize(details);
var sw = new StreamWriter(assetsFolder + @”pass.json”);
sw.Write(strPass);
sw.Close();
var manifest = new JsonObjects.Manifest();
// Generate SHA1 hash codes for each of the files required
manifest.strippng = GetSha1Hash(assetsFolder + manifest.GetAsset(JsonObjects.AssetTypes.strippng));
manifest.stripAt2xpng = GetSha1Hash(assetsFolder + manifest.GetAsset(JsonObjects.AssetTypes.stripAt2xpng));
manifest.iconpng = GetSha1Hash(assetsFolder + manifest.GetAsset(JsonObjects.AssetTypes.iconpng));
manifest.iconAt2xpng = GetSha1Hash(assetsFolder + manifest.GetAsset(JsonObjects.AssetTypes.iconAt2xpng));
manifest.logopng = GetSha1Hash(assetsFolder + manifest.GetAsset(JsonObjects.AssetTypes.logopng));
manifest.logoAt2xpng = GetSha1Hash(assetsFolder + manifest.GetAsset(JsonObjects.AssetTypes.logoAt2xpng));
manifest.passjson = GetSha1Hash(assetsFolder + manifest.GetAsset(JsonObjects.AssetTypes.passjson));

// write out manifest.json (adapting variable names)
var strManifest = JavascriptSerialize(manifest);
strManifest = JsonObjects.Manifest.Map.Aggregate(strManifest,
(current, map) => current.Replace(map.property, map.asset));

sw = new StreamWriter(assetsFolder + @”manifest.json”);
sw.Write(strManifest);
sw.Close();

// Generate S/MIME Signature
// http://stackoverflow.com/questions/11526572/openssl-smime-in-c-sharp
var cert = new X509Certificate2(assetsFolder + p12File, p12Password);
var buffer = File.ReadAllBytes(Path.Combine(assetsFolder, “manifest.json”));
var cont = new ContentInfo(buffer);
var cms = new SignedCms(cont, true);
var signer = new CmsSigner(SubjectIdentifierType.SubjectKeyIdentifier, cert)
{
IncludeOption = X509IncludeOption.ExcludeRoot
};
cms.ComputeSignature(signer);
var myCmsMessage = cms.Encode();
File.WriteAllBytes(Path.Combine(assetsFolder, “signature”), myCmsMessage);
using (var zip = new ZipFile())
{
foreach (var asset in JsonObjects.Manifest.Map)
{
zip.AddFile(Path.Combine(assetsFolder, asset.asset), “/”);
}
zip.AddFile(Path.Combine(assetsFolder, “manifest.json”), “/”);
zip.AddFile(Path.Combine(assetsFolder, “signature”), “/”);
zip.Save(Path.Combine(assetsFolder, “pass.pkpass”));
}
}

/// <summary>
/// Converts an object into a JSON string. Works with anonymous types.
/// </summary>
/// <typeparam name=”T”></typeparam>
/// <param name=”o”></param>
/// <returns></returns>
public static string JavascriptSerialize<T>(T o)
{
var jsSerializer = new JavaScriptSerializer();
var strJson = jsSerializer.Serialize(o);
var jsonPretty = JsonPrettyPrinter.Process(strJson);
return jsonPretty;
}

/// <summary>
/// Gets the sha1 hash.
/// </summary>
/// <param name=”sourceFileName”>Name of the source file.</param>
/// <returns></returns>
private static string GetSha1Hash(string sourceFileName)
{
StringBuilder formatted;
using (var fs = new FileStream(sourceFileName, FileMode.Open))
using (var bs = new BufferedStream(fs))
{
using (var sha1 = new SHA1Managed())
{
var hash = sha1.ComputeHash(bs);
formatted = new StringBuilder(2 * hash.Length);
foreach (var b in hash)
{
formatted.AppendFormat(“{0:X2}”, b);
}
}
}
return formatted.ToString().ToLower();
}
}
}

So, how this is used, is something like this:

static void Main(string[] args)
{
// Need to install Apple ROOT cert http://www.apple.com/appleca/AppleIncRootCertificate.cer
const string strAssetsFolder = @”C:\demo\assetsOnly\”;
var pass = new JsonObjects.Pass
{
formatVersion = 1,
passTypeIdentifier = “pass.com.whatever”,
serialNumber = “001”,
teamIdentifier = “XXXXxX”,
organizationName = “Your company”,
description = “Free hug”,
logoText = “Free hugs LLC”,
foregroundColor = “rgb(255, 255, 255)”,
backgroundColor = “rgb(135, 129, 189)”,
labelColor = “rgb(45, 54, 129)”,
barcode = new JsonObjects.Barcode
{
message = “All you need is love”,
format = “PKBarcodeFormatPDF417”,
messageEncoding = “iso-8859-1”
}
};
PkPassGenerator.GeneratePkPass(pass, strAssetsFolder, “pass.p12″,”YYYYY”);
}

Categories: Uncategorized

Creating Apple Passbook #PKPass coupons from Windows

September 21, 2015 1 comment

I was following the excellent tutorial by Marin Todorov at http://www.raywenderlich.com/20734/beginning-passbook-part-1 , to create passbook (.pkpass) files from the command line – in order to understand what was going on, rather than depending on third party services to generate them.

However, the tutorial requires a mac, so I adapted it to work from windows as follows;

Download GNUWIN32 http://sourceforge.net/projects/gnuwin32/

—–Generate CSR———-

openssl genrsa -out passbookprivatekey.key 2048

Had to use template openssl.conf (https://www.tbs-certificats.com/openssl-dem-server-cert-thvs.cnf)

set OPENSSL_CONF=%cd%\openssl.cnf

openssl req -new -key passbookprivatekey.key -out PassbookCSR.certSigningRequest -subj “/emailAddress=you@domain.com, CN=Company, C=GB”

> send to apple, and get pass.cer back.

—–Convert CER to P12—–

openssl x509 -inform der -in pass.cer -out pass.pem

openssl pkcs12 -export -out pass.p12 -inkey passbookprivatekey.key -in pass.pem

password XXXX
—- And finally, create signature —-

openssl pkcs12 -in pass.p12 -clcerts -nokeys -out passcertificate.pem -passin pass:XXXX

openssl pkcs12 -in pass.p12 -nocerts -out passkey.pem -passin pass:XXXX -passout pass:XXXX

Download Apple AppleWWDRCA.cer

openssl x509 -inform der -in AppleWWDRCA.cer -out AppleWWDRCA.pem

openssl x509 -inform der -in pass.cer -out pass.pem

openssl smime -binary -sign -certfile AppleWWDRCA.pem -signer passcertificate.pem -inkey passkey.pem
-in manifest.json -out signature -outform DER -passin pass:XXXX

Categories: Uncategorized

#iOS9 #Breaking #Change – HTTP connections blocked by default!

September 18, 2015 Leave a comment

In the new iOS 9 Apple has decided that HTTP is too insecure for communications outside of your app… If you try to make one, you get this error:

Failed to load resource: The resource could not be loaded because the App Transport Security policy requires the use of a secure connection.

So, you can go and get a HTTPS security cert for your server – perhaps the best option – or you can add this to your info.plist

<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>

I discovered this when using http://www.remotelogcat.com on a Phonegap / Cordova iOS app.

Categories: Uncategorized

Understanding the basics of SPF records #EmailTech

September 17, 2015 Leave a comment

SPF or “Sender Policy Framework” is a technique that aims to prevent email sender spoofing, and ultimately cut spam, it means that senders without a properly configured SPF record may be considered spam.

But if your business sends out email, and you want to make sure it isn’t marked as spam at your destination, then you might need to look at your SPF records.

The first step is to look at the headers of a received email, by a client that handles SPF, i.e. Gmail, and if you see something like spf=softfail ( domain of transitioning does not designate as permitted sender) , this means SPF is not configured correctly.

So, lets say, you know the sender is going to have IP address 1.2.3.4 – i.e. your outbound SMTP server. and your sender email is whatever@me.com – you need to then add a DNS TXT record to the domain me.com with the text

v=spf1 ip4:1.2.3.4 ~all

For the host “@” (non-www)

Then try sending the email again, and view the headers on the message, and it should say

Received-SPF: pass (google.com: domain of whatever@me.com designates 1.2.3.4 as permitted sender) client-ip=1.2.3.4;

This will come into play big time if you use Direct to MX software, or Amazon SES

Categories: Uncategorized