Archive

Author Archive

Get #ISO3166 Country code from #IP address in C#

cell-tower

Although an IP address can’t always pinpoint where a user is to the correct city, it’s pretty reliable way of getting the user’s country, and you can tailor the content for that user, i.e. show prices in GBP for UK users, and USD for USD users.

There are plenty of ways of doing this, and many services that provide this service, but this worked well for me in an ASP.NET MVC website

WebClient wc = new WebClient();
var strJson = wc.DownloadString(“http://ipinfo.io/” + Request.ServerVariables[“REMOTE_ADDR”]);
var ip = Newtonsoft.Json.Linq.JObject.Parse(strJson);
var country = ip[“country”].ToString();

Categories: Uncategorized

WhitehatTwitterFollowers.com : a new way to boost your twitter presence

splash

WhitehatTwitterFollowers.com  is a website that gets you new twitter followers based on your chosen hashtags ; and it’s WhiteHat, which means that there’s nothing untoward about the service.

That means that it’s not a service that get’s you an instant following of 10,000 zombie twitter accounts that all seem to have random twitter handles, and come from Eblonia*, oh, and they all get cancelled by twitter after it discovers that they’ve been created by a bot.

What it does, is uses the Twitter API to automatically favourite hundreds of tweets based on your selected hashtags, and those “favourites”, get you noticed by the authors of the tweets, and we’ve seen ratios typical of 3 new followers per 100 favourites.

So, it’s not an instant win, but a slow burn. But that’s what Whitehat is all about. If you prefer the 10,000 zombie accounts, look elsewhere.

 

*No, Eblonia is not a real place, it’s actually a nod to Dilbert 🙂

Categories: Uncategorized

Google Image Search No Longer Available

About 2 days ago, Google Image Search API was terminated, and attempts to call the API gives an error “No Longer Available”. There is a work around, using the Google Custom Search API, and here’s some code to do it using JQuery.

(You’ll need to get your own key, since it’s limited to 100 queries per day)

function GoogleImageSearch(searchTerm, callback)
{
var params = {};
params.q = searchTerm; // search text
params.num = 1; // integer value range between 1 to 10 including
params.start = 1; // integer value range between 1 to 101, it is like the offset
params.imgSize = “large”; // for image size
params.searchType = “image”; // compulsory
params.fileType = “jpg”; // you can leave these if extension does not matters you
params.key = “xxxxxxx”; // API_KEY got from https://console.developers.google.com/
params.cx = “xxxxxx”; // cx value is the custom search engine value got from https://cse.google.com/cse(if not created then create it).
$.get(“https://www.googleapis.com/customsearch/v1”,params,function(img){
console.log(img);
callback(img.items[0].link);
}).fail(function(y){
console.log(y);
});
}

Categories: Uncategorized

Prerolled jqm themes #JQM #Themeroller

With the latest version of Jquery Mobile, the included themes have been made decidedly more bland, and the themes available for JQM are quite specialized, like the BlackBerry theme, NativeDroid, Flat UI etc., but if you just want something simple and attractive, here is a hack to show themes that other users have done on ThemeRoller,

Just go to the url – https://themeroller.jquerymobile.com/?ver=1.4.5&style_id=YYYYMMDD-NN

where YYYYMMDD is a date within the last 30 days, and N is a sequental number.

Most of them are un-styled, and a lot are quite ugly, but you might find a gem there,

https://themeroller.jquerymobile.com/?ver=1.4.5&style_id=20151124-15 – Cookie – colourful

https://themeroller.jquerymobile.com/?ver=1.4.5&style_id=20151124-11 – maroon

https://themeroller.jquerymobile.com/?ver=1.4.5&style_id=20151124-10 – blue green

https://themeroller.jquerymobile.com/?ver=1.4.5&style_id=20151123-10 – grey blue

https://themeroller.jquerymobile.com/?ver=1.4.5&style_id=20151123-14 – tourquize

https://themeroller.jquerymobile.com/?ver=1.4.5&style_id=20151123-15 – Grey green

https://themeroller.jquerymobile.com/?ver=1.4.5&style_id=20151123-17 – Grey cyan

https://themeroller.jquerymobile.com/?ver=1.4.5&style_id=20151123-19 – pink

https://themeroller.jquerymobile.com/?ver=1.4.5&style_id=20151123-2 – purple pink

https://themeroller.jquerymobile.com/?ver=1.4.5&style_id=20151122-10 – orange grey

https://themeroller.jquerymobile.com/?ver=1.4.5&style_id=20151122-12 – light green

 

 

themeroller

Categories: Uncategorized

Updating the font used throughout a #wp8 #app

Using a custom font is a nice design touch that helps a windows phone app stand out, by looking a little different. The Segoe font can be a bit boring…

So, the standard way this is done, is by adding the following into Application.Resources in App.xaml

<Style TargetType=”TextBlock”>
<Setter Property=”FontFamily” Value= “assets/fonts/whatever.ttf#whatever”/>
</Style>

<Style TargetType=”TextBox”>
<Setter Property=”FontFamily” Value= “assets/fonts/whatever.ttf#whatever”/>
</Style>

But, here’s another approach, using reflection, and page hooks, like used in a previous post:
https://blog.dotnetframework.org/2015/11/09/localise-datepicker-in-wp8-silverlighttoolkit-using-hooks/

So, from within CompleteInitializePhoneApplication, add the code

PhoneApplicationPage page = RootFrame.Content as PhoneApplicationPage;
FontChangeHook(page);

then, FontChangeHook method as follows;

public static void FontChangeHook(PhoneApplicationPage page)
{
LoopThroughControls(page, (ui => {
var type = ui.GetType();
var prop = type.GetProperty(“FontFamily”);
if (prop != null)
{
prop.SetValue(ui, new FontFamily(@”assets/fonts/whatever.ttf#whatever”));

}
}));
}

Categories: Uncategorized

Free OCR using C= #Webservice

Converting an image into text is a difficult job for a computer, hence the pervasive use of Captcha images, however, OCR (optical character recognition) is quite effective with printed text.

Here’s a free webservice provided by a9t9, it’s limited to 500 requests/day or 15000 requests/month per IP address. You can get more quota by emailing a9t9 – You provide it with a url with an image that contains text;

It returns it’s results in JSON, so the bulk of this code is really just to convert the response to a simple string.

[WebMethod]
public string Automatic(string imageUrl)
{
var wc = new WebClient();
wc.Headers[“Content-Type”] = “application/x-www-form-urlencoded”;
const string strUrl = “https://ocr.a9t9.com/api/Parse/Image&#8221;;
var strPostData = “apikey=helloworld”;
strPostData += “&url=” + HttpUtility.UrlEncode(imageUrl);
var strJson = wc.UploadString(strUrl, “POST”, strPostData);
var result = JavascriptDeserialize<A9T9>(strJson);
return result.ParsedResults.First().ParsedText;
}

And the json conversion;

/// <summary>
/// Converts a JSON string into an object of type T.
/// </summary>
/// <typeparam name=”T”></typeparam>
/// <param name=”json”>The JSON string.</param>
/// <returns></returns>
public static T JavascriptDeserialize<T>(string json)
{
var jsSerializer = new JavaScriptSerializer { MaxJsonLength = Int32.MaxValue };
return jsSerializer.Deserialize<T>(json);
}

public class ParsedResult
{
public int FileParseExitCode { get; set; }
public string ParsedText { get; set; }
public string ErrorDetails { get; set; }
}

public class A9T9
{
public List<ParsedResult> ParsedResults { get; set; }
public int OCRExitCode { get; set; }
public bool IsErroredOnProcessing { get; set; }
public object ErrorDetails { get; set; }
}

Categories: Uncategorized

Free SMS New Zealand, new website launched today

logo-nz

Just launched today http://www.freesms.co.nz – a website for sending free SMS messages to New Zealand, so you can keep in contact with your Kiwi relatives that haven’t yet moved over to the world of Whatsapp / Skype / Facebook Messenger yet.

It’s powered by the great guys over at Fortumo – a great free-to-try PSMS system, zero setup fees, zero monthly cost, and massive coverage. You just can’t beat them!

Categories: Uncategorized

Localise DatePicker in #WP8 #SilverlightToolkit using hooks

The Silverlight toolkit for Wndows phone is really handy to get up and running quickly with advanced functionality on a Windows Phone app, however, when you want to customize it, you find that you end up downloading the source, and tinkering with it directly, which is fine, since it’s an open source project. However, for a minor change, it would be nice to keep treating it as a black box.

This approach however, could therefore be used to access and modify the XAML of any control, even closed-source ones. Which could be useful for Syncfusion or Telerik controls too.

So, first, we modify app.xaml.cs to create our hook.

Comment out // RootFrame.Navigated -= CompleteInitializePhoneApplication; in CompleteInitializePhoneApplication, so that the method gets called on every page load, not just on first load.

Then check the current page like this

PhoneApplicationPage page = RootFrame.Content as PhoneApplicationPage;
var strPage = (sender as NavigationService).CurrentSource.ToString();
if (strPage.Contains(“DatePickerPage.xaml”)) UI.DatePickerHook(page);

Hopefully, you don’t have a page called DatePickerPage.xaml in your app!, but this will call UI.DatePickerHook when the datepicker is opened.

Now, for a helpful utility function, which I’ve called LoopThroughControls – which applies an action to every control on a page recursively as follows;

private static void LoopThroughControls(UIElement parent, Action<UIElement> modifier)
{
int count = VisualTreeHelper.GetChildrenCount(parent);
if (count > 0)
{
for (int i = 0; i < count; i++)
{
UIElement child = (UIElement)VisualTreeHelper.GetChild(parent, i);
modifier(child);
LoopThroughControls(child, modifier);
}
}
return;

Then the DatePickerHook function is defined as follows

public static void DatePickerHook(PhoneApplicationPage page)
{
// Somehow modify the text on the top of the page…
LoopThroughControls(page, (ui => {
var tb = ui as TextBlock;
if (tb != null && tb.Name == “HeaderTitle”)
{
tb.Text = “”;
}
}));
}

Categories: Uncategorized

Pkpass api (Apple passbook)

Categories: Uncategorized

LoadCertFromFile exception IIS when loading p12 cert. #x509

This is a nasty little error that I solved this morning.

I was trying to load a .p12 cert from disk, which worked fine on my local pc, but as soon as I installed it on the server, I got this error “_LoadCertFromFile” – So, I tried importing the certificate manually using certutil, – resetting IIS, but eventually, discovered a fix on stackoverflow, where you have to enable “Load user profile” under advanced application pool settings


Here was the full error for reference:

Server Error in ‘/’ Application.

An internal error occurred.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Security.Cryptography.CryptographicException: An internal error occurred.

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace:

[CryptographicException: An internal error occurred.
]
System.Security.Cryptography.CryptographicException.ThrowCryptographicException(Int32 hr) +41
System.Security.Cryptography.X509Certificates.X509Utils._LoadCertFromFile(String fileName, IntPtr password, UInt32 dwFlags, Boolean persistKeySet, SafeCertContextHandle& pCertCtx) +0
System.Security.Cryptography.X509Certificates.X509Certificate.LoadCertificateFromFile(String fileName, Object password, X509KeyStorageFlags keyStorageFlags) +307
System.Security.Cryptography.X509Certificates.X509Certificate2..ctor(String fileName, String password) +84
libPkPass.PkPassGenerator.GeneratePkPass(Pass details, String assetsFolder, String p12File, String p12Password) in c:\projects\troop\Troops\PKPASS\libPkPass\pkPassGenerator.cs:105
libPkPass.PkPassGenerator.GeneratePkPass(Pass details, Uri logo, String colour) in c:\projects\troop\Troops\PKPASS\libPkPass\pkPassGenerator.cs:40
TroopAdminMVC.Controllers.ApiController.GeneratePkPass() in c:\projects\troop\Troops\TroopAdminMVC\Controllers\ApiController.cs:161
lambda_method(Closure , ControllerBase , Object[] ) +79
System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +242
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +39
System.Web.Mvc.Async.AsyncControllerActionInvoker.b__39(IAsyncResult asyncResult, ActionInvocation innerInvokeState) +12
System.Web.Mvc.Async.WrappedAsyncResult`2.CallEndDelegate(IAsyncResult asyncResult) +139
System.Web.Mvc.Async.AsyncInvocationWithFilters.b__3d() +112
System.Web.Mvc.Async.<>c__DisplayClass46.b__3f() +452
System.Web.Mvc.Async.<>c__DisplayClass33.b__32(IAsyncResult asyncResult) +15
System.Web.Mvc.Async.<>c__DisplayClass2b.b__1c() +37
System.Web.Mvc.Async.<>c__DisplayClass21.b__1e(IAsyncResult asyncResult) +241
System.Web.Mvc.Controller.b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +29
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +111
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +74
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +19
System.Web.Mvc.MvcHandler.b__5(IAsyncResult asyncResult, ProcessRequestState innerState) +51
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +111
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +606
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +288

Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.34249

Categories: Uncategorized