Archive

Archive for June, 2015

Detect browser locale using Javascript

June 30, 2015 Leave a comment

On Chrome and Firefox 32+, navigator.languages contains an array of locales in order of user preference, and is more accurate than navigator.language, however to make it backwards-compatible (Tested Chrome / IE / Firefox / Safari), then use this:

function getLang()
{
 if (navigator.languages != undefined) 
 return navigator.languages[0]; 
 else 
 return navigator.language;
}

I tested this against a more complex technique by making an ajax call to a service that returns the HTTP headers, and parsing the Accept-Language.

The server side code as follows;

<%@ Import Namespace=”System” %>
<%@ Page Language=”c#”%>
<script runat=”server”>
public string ServerSideFunction()
{
Response.AddHeader(“Access-Control-Allow-Origin”, “*”);
int loop1;
NameValueCollection coll;
coll=Request.Headers;
String[] arr1 = coll.AllKeys;
Response.Write(“{“);
string seperator = “”;
for (loop1 = 0; loop1<arr1.Length; loop1++)
{
Response.Write(seperator + “\”” + arr1[loop1] + “\”:”);
// Get all values under this key.
String[] arr2=coll.GetValues(arr1[loop1]);
Response.Write( “\”” + Server.HtmlEncode(arr2[0]) + “\””);
seperator = “,”;
}
Response.Write(“}”);
return “”;
}
</script>
<% =ServerSideFunction() %>

Which is called by some JQuery script as follows;

$(init);
function init()
{
$.ajax({
url: “http://xxxx.xxxxx.net/Headers.aspx&#8221;,
success: function(data){
var strLanguage = data[“Accept-Language”].split(“,”)[0];
$(“#output”).html(strLanguage);
},
dataType: “json”
});
}

Categories: Uncategorized

Submitting my first Mac OS X app to the mac app store using #Xamarin

June 28, 2015 Leave a comment

Writing an app is one thing, but publicising and selling it is where the real upside is for a developer. I recently discovered that Xamarin allows you to develop Mac desktop apps. Which got me interested, since I’m a seasoned .NET developer, and thought that it seemed easier than learning objective C (although I should…).

I’ve written plenty of PhoneGap (Cordova) apps, which are basically HTML apps, and I thought that I could really easily port a phone gap app across to objective C, once I could embed a WebView (WebBrowser control) into an Mac OS X app. So, kicking off Xamarin studio, I created a basic Cocoa app, and opened the XIB in Xcode, dropped in a webView, and set its auto-resizing  to fill the window. then ctrl-dragged it as an outlet into MainWindow.h

Back to Xamarin Studio, I copied the www folder from the Phonegap project, and set it’s build action to content, I then added the code:

public override void AwakeFromNib ()
        {
            base.AwakeFromNib ();
            // https://github.com/xamarin/macsamples/blob/master/SkinnableApp/MainWindowController.cs
            var htmlPath = Path.Combine (NSBundle.MainBundle.ResourcePath, www/index.html);
            webBrowser.MainFrame.LoadRequest(new NSUrlRequest (new NSUrl (htmlPath)));
        }

which just opens the index.html from the www folder, and loads it into the browser.

I went into Developer.apple.com member centre, and set up a cert, app identifier, and provisioning profile, then into iTunes Connect and set up the app with the same bundle identifier

I clicked on the project > options > Mac application – entered the bundle identifier, pressed enabled entitlements and app sandboxing, set the icon* (By generating an icns file). Then under options > Mac Signing – selected an identity, and then selected custom entitlements as Entitlements.plist.

Editing the Info.Plist file in TextWrangler I had to manually add the keys

<key>MonoBundleExecutable</key>
<string>{ProjectName}.exe</string>
<key>CFBundleExecutable</key>
<string>{ProjectName}</string>

Where {ProjectName} is the name of the project – not literally that string! – This avoids error ITMS-90259 which gives an Invalid Binary error on iTunes connect

I then changed it to release mode, selected Build > Archive for Publishing

Using terminal, I navigated to the output folder, and ran

chmod -R a+rX *

This got rid of an earlier submission error where it was complaining that only the root user had access to certain files.

I then switched to Xcode organiser and submit to app store, selected my provisioning profile, and unchecked “include app symbols”, and submitted. – Once it said uploaded successfully, then I went back into iTunes Connect, selected the build, and filled in the rest of the information, including screenshots. No Icon necessary, it takes it from the Binary, then pressed submit for review….

It’ll probably get rejected, since it’s a very simple game, but lets keep our fingers crossed! 🙂

Screen Shot 2015-06-28 at 05.40.46

Categories: Uncategorized

Printing in Mac OSX C# / Xamarin / Mono

June 26, 2015 Leave a comment

Just figured this out !

using System.Diagnostics;

ProcessStartInfo pStartInfo = new ProcessStartInfo();
            pStartInfo.FileName = lpr;
            pStartInfo.Arguments = /Users/fiachreid/Desktop/osxprinter.png;
            Process.Start(pStartInfo);

Categories: Uncategorized

Convert BlackBerry 10 BAR file to Android APK #BlackBerryDev

June 26, 2015 1 comment

I just developed this proxy to convert BlackBerry 10 BAR files based on the android runtime to APKs that can be installed on and Android phone.

There’s no user interface yet to this, you just post a url to a BAR file, and the APK will be returned back to you, like this

http://bar2apk.webtropy.com/?url=http://107.150.58.162/Apk2Bar/bar/com.topaccolades.volcanofree_v1.41.6.bar

The whole process is done in-memory, with no temporary files, I’ve used sharpziplib :

var strUrl = Request.QueryString[“url”];
var wc = new WebClient();
var zipped = wc.DownloadData(strUrl);
var stream = new MemoryStream();
stream.Write(zipped, 0, zipped.Length);
stream.Position = 0;
var zf = new ZipFile(stream);
foreach(ZipEntry ze in zf)
{
if (!ze.Name.EndsWith(“.apk”)) continue;
var zs = zf.GetInputStream(ze);
using (var ms = new MemoryStream())
{
zs.CopyTo(ms);
Response.ContentType = “application/vnd.android.package-archive”;
Response.AddHeader(“Content-Disposition”, “attachment; filename=” + ze.Name + “;”);
Response.BinaryWrite(ms.ToArray());
}
}

Categories: Uncategorized

Translate a webpage server-side using CURL and PHP for added #SEO

June 26, 2015 1 comment

guidesA great way to increase the accessibility of your website to more users is to provided it in multiple languages, not just English. but what happens if you have dynamic content, and just too much content to justify translating manually?

You can simply link out to Google translate, but then you loose the SEO advantage of having your content served from your domain, so doing it server side is key to maintain your traffic. – You “should” use the Google Translate API for this, but it’s a paid-for service, and if you’re not feeling that generous, you can hack your way through Google’s page translation service – until such time as they block your IP 🙂

So, here’s my case in point for a project I was working on http://guide.universaltravelsearch.com , where when a user navigates to the “attraction page”, such as http://guide.universaltravelsearch.com/attraction/33634/%22Sylvan%20Beach%20Resort%22 Then there are links on the foot foot of the page which link to http://guide.universaltravelsearch.com/translate/33634/ru/%22Sylvan+Beach+Resort%22 for the Russian version, for example. – where the user is kept on the same domain, but the content is in Russian.

So, here’s how I did it:

<?php

$url = “http://yoururl/yourpage.php?id=&#8221; . $_GET[“id”];
$url = “http://translate.google.com/translate_p?hl=en&sl=en&tl=&#8221; . $_GET[“lang”] . “&u=” . urlencode($url);
$output = HttpGet($url);
preg_match(‘/href..(.*).>Translating../’, $output, $m);
$url = html_entity_decode ($m[1]);
$output = HttpGet($url);
echo $output;

function HttpGet($url) {
$ch = curl_init($url );
//return the transfer as a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_USERAGENT,’Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.14′);
curl_setopt($ch, CURLOPT_REFERER, ‘http://www.google.com/&#8217;);
// $output contains the output string
$output = curl_exec($ch);
// close curl resource to free up system resources
curl_close($ch);
return $output;
}

This makes a call to translate_p, and extracts the link that google returns, then makes a call to this url. The Curl request has to fake the user agent, and referrer, otherwise Google will block the request.

There’s no guarantee that this will last for ever, in fact, it’s probable that it will be blocked before too long, but should be fine for low-traffic websites.
?>

Categories: Uncategorized

Console app to send form emails in C=

June 24, 2015 Leave a comment

If you want to send form emails from the command line, based on data returned from a SQL server, then this bit of code might be what you;re looking for. I’m omitting the SMTP settings and Database settings, but it should be clear where they go.

private static void Main(string[] args)
{
var strBaseDirectory = AppDomain.CurrentDomain.BaseDirectory;
var fs = new FileStream(strBaseDirectory + @”\content.txt”, FileMode.Open);
var sr = new StreamReader(fs);
var strTemplate = sr.ReadToEnd();

// email and subject columns are mandatory
var strSQL = “select ‘someone’ as name, ‘xxxx@hotmail.com’ as email, ‘test’ as subject”;
var ds = ExecuteSQL(strSQL);
var intProgress = 0;
foreach (DataRow dr in ds.Tables[“sql”].Rows)
{
var strBody = strTemplate;
foreach (DataColumn dc in ds.Tables[“sql”].Columns)
{
strBody = strBody.Replace(“$” + dc.ColumnName + “$”, dr[dc.ColumnName].ToString());
}
sendEmail(dr[“email”].ToString(), dr[“subject”].ToString(), strBody);
Console.Clear();
intProgress++;
Console.Write(“Sent ” + intProgress + ” of ” + ds.Tables[“sql”].Rows.Count);
}
Console.ReadLine();
}

This calls two other functions, sendEmail and executeSQL which are: – I’m using Amazon SES, but any SMTP host would work fine here.

public static void sendEmail(string to, string subject, string body)
{
var client = new SmtpClient
{
Port = 587,
Host = “email-smtp.eu-west-1.amazonaws.com”,
EnableSsl = true,
Timeout = 10000,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new System.Net.NetworkCredential(
“xxxxx”,
“xxxxx”)
};
var mm = new MailMessage(“xxxx@gmail.com”, to, subject, body)
{
BodyEncoding = UTF8Encoding.UTF8,
IsBodyHtml = true,
DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure
};
client.Send(mm);
Thread.Sleep(1000);
}

And my ExecuteSQL is:

public static DataSet ExecuteSQL(string sql)
{
DataSet dataSet = null;
const String sqlConnection =
“Data Source=WWW.xxxxx.COM;Initial Catalog=xxxxx;User Id=xxxx;Password=xxxx”;
using (var conn = new SqlConnection(sqlConnection))
{
var command = new SqlCommand(sql) {Connection = conn};
var adapter = new SqlDataAdapter(command);
dataSet = new DataSet();
adapter.Fill(dataSet, “sql”);
}
return dataSet;
}

– Then , I’ve added a file called content.txt, and set its build action to “copy to output directory” with the content

Hi, $name$

This is a test email with some <b>HTML</b> content

😉

Categories: Uncategorized

Calculate Stripe fees using Javascript

June 19, 2015 1 comment

var fees = { USD: { Percent: 2.9, Fixed: 0.30},
GBP: { Percent: 2.4, Fixed: 0.20},
EUR: { Percent: 2.4, Fixed: 0.24},
CAD: { Percent: 2.9, Fixed: 0.30},
AUD: { Percent: 2.9, Fixed: 0.30},
NOK: { Percent: 2.9, Fixed: 2},
DKK: { Percent: 2.9, Fixed: 1.8},
SEK: { Percent: 2.9, Fixed: 1.8},
JPY: { Percent: 3.6, Fixed: 0},
MXN: { Percent: 3.6, Fixed: 3}};
function addFee(amount, currency)
{
var fee = fees[currency];
return (amount + fee.Fixed) / (1 – fee.Percent/100);
}

alert(addFee(100,”GBP”));

– and viola, your consumer pays your stripe fees!.

Categories: Uncategorized