Archive

Author Archive

#SQL Hashbytes compatible code in C#

dog1

The SQL function hashbytes allows you to hash strings directly in the database; by using something such as;

select hashbytes(‘MD5′,’hello world’)

which returns 0x5EB63BBBE01EEED093CB22BB8F5ACDC3

But if you want to compare this string with a hash created on the server by C#, then you’ll need to get it into the right format – where you could use this code here:

public static string HashBytes(string valueToHash)
{
HashAlgorithm hasher = new MD5CryptoServiceProvider();
Byte[] valueToHashAsByte = Encoding.UTF8.GetBytes(String.Concat(valueToHash, SaltValue));
Byte[] returnBytes = hasher.ComputeHash(valueToHashAsByte);
StringBuilder hex = new StringBuilder(returnBytes.Length * 2);
foreach (byte b in returnBytes) hex.AppendFormat(“{0:x2}”, b);
return “0x” + hex.ToString().ToUpper();
}

Categories: Uncategorized

Helo command rejected: need fully-qualified hostname

smtpjs

When sending email from C#, if you ever get the error “Helo command rejected: need fully-qualified hostname”, you may end up scratching your head, because there is no easy way to change what gets sent in the HELO command from the SMTPClient class.

You, can however, use reflection to override what the SmtpClient class sends. here I have hard-coded “www.smtpjs.com”  – because this code is specifically for this project.

You need to subclass SMTPClient as SMTPClientEx, and override the private properties localHostName and clientDomain as follows;

using System.Net.Mail;
using System.Reflection;

/// <inheritdoc />
/// <summary>
/// Subclass of Smtpclient, with overridden HELO
/// </summary>
public class SmtpClientEx : SmtpClient
{

public SmtpClientEx()
{
Initialize();
}

private void Initialize()
{
const string strHelo = “www.smtpjs.com”;
var tSmtpClient = typeof(SmtpClient);
var localHostName = tSmtpClient.GetField(“localHostName”, BindingFlags.Instance | BindingFlags.NonPublic);
if (localHostName != null) localHostName.SetValue(this,strHelo);
var clientName = tSmtpClient.GetField(“clientDomain”, BindingFlags.Instance | BindingFlags.NonPublic);
if (clientName != null) clientName.SetValue(this, strHelo);
}
}

Categories: Uncategorized

Automate “Get Latest Version” from Visual Studio Team Services #VSTS

VS-TFS

If you use Visual Studio Team Services – previously known as “Visual Studio Online” to manage your source control, and you find yourself frequently exporting zip files, and copying them to deployment, you might be pleased to know there is an extensive API that allows you do a “Get Latest Version” from C#

So, first off you need to create an app with VSTS here;

https://app.vsaex.visualstudio.com/app/register

You’ll need to have a publicly accessible HTTPS website for the callback. I’ve just used https://<mydomain>/callback.aspx – I selected all the available scopes, but you can be more selective.

Once registered, you’ll get your Oauth credentials, and slot them into your web.config

<appSettings>
<add key=”app_id” value=”….”/>
<add key=”app_secret” value=”….”/>
<add key=”client_secret” value=”…..”/>
<add key=”Authorize_URL” value=”https://app.vssps.visualstudio.com/oauth2/authorize?mkt=en-US”/&gt;
<add key=”Access_Token_URL” value=”https://app.vssps.visualstudio.com/oauth2/token?mkt=en-US”/&gt;
<add key=”Scopes” value=”vso.build_execute vso.code_full vso.code_status vso.codesearch vso.connected_server vso.dashboards vso.dashboards_manage vso.entitlements vso.extension.data_write vso.extension_manage vso.gallery_acquire vso.gallery_manage vso.graph_manage vso.identity_manage vso.loadtest_write vso.machinegroup_manage vso.memberentitlementmanagement_write vso.notification_diagnostics vso.notification_manage vso.packaging_manage vso.profile_write vso.project_manage vso.release_manage vso.security_manage vso.serviceendpoint_manage vso.symbols_manage vso.taskgroups_manage vso.test_write vso.wiki_write vso.work_full vso.workitemsearch”/>
<add key=”RemoteLogCat” value=”…..”></add>
<add key=”RemoteScope” value=”$/….”></add>
<add key=”LocalWorkSpace” value=”F:\….\”></add>
<add key=”accountName” value=”…..”></add>
<add key=”projectName” value=”…..”></add>
</appSettings>

I’ve removed sensitive data above, but each setting is as follows:

  • app_id, app_secret, client_secret – Displated after creating your app on VSTS
  • RemoteLogCat – optional, from RemoteLogCat.com
  • RemoteScope – The path where the root of your website resides on TFS
  • LocalWorkSpace – The file path where the website will be downloaded to locally
  • accountName – your account on VSTS
  • projectName – the project within your account on VSTS

Then, the first step is to request consent to access your account on VSTS, which you can do a redirect link as follows;

strUrl += “?client_id=” + ConfigurationManager.AppSettings[“app_id”];
strUrl += “&response_type=Assertion”;
strUrl += “&state=any”;
strUrl += “&scope=” + ConfigurationManager.AppSettings[“Scopes”];
strUrl += “&redirect_uri=https://…./callback.aspx”;
Response.Redirect(strUrl);
This, should display a page such as the following;
login
… Press Accept at the foot of the page, and you are reditected to your callback, with some parameters in the Querystring.
To Convert the code to a bearer token, you have to send this back to VSTS as follows;
var strCode = Request.QueryString[“code”];
var strClientSecret = ConfigurationManager.AppSettings[“client_secret”];
var strCallbackUrl = “https://&#8230;./callback.aspx”;
var strPostData = GenerateRequestPostData(strClientSecret, strCode, strCallbackUrl);
var wc = new WebClient();
wc.Headers[“Content-Type”] = “application/x-www-form-urlencoded”;
try
{
var strJson = wc.UploadString(strTokenUrl, strPostData);
Response.Write(strJson);
Response.Write(“<hr>”);
var jObject = JObject.Parse(strJson);
var strAccessCode = jObject[“access_token”].ToString();
//BuildLocalWorkSpaceTree(strAccessCode);
//GetLastChangeSet(strAccessCode);
}
catch(WebException ex){
var resp = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();
Response.Write(resp);
}
Where the function GenerateRequestPostData is defined as follows;
privatestaticstring GenerateRequestPostData(string appSecret, string authCode, string callbackUrl)
{
return String.Format(
“client_assertion_type=urn:ietf:params:oauth:client-assertion-type:jwt-bearer&client_assertion={0}&grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer&assertion={1}&redirect_uri={2}”,
HttpUtility.UrlEncode(appSecret),
HttpUtility.UrlEncode(authCode),
callbackUrl
);
}
If you run this, you should see some JSON on the page, with your bearer token.
Now, to do something useful with the code, let’s imagine, you want to Do a “Get Latest Version”, then you can uncomment the BuildLocalWorkSpaceTree , and add the function
privatevoid BuildLocalWorkSpaceTree(string bearer)
{
var strLocalWorkspace = ConfigurationManager.AppSettings[“LocalWorkSpace”];
var strAccountName = ConfigurationManager.AppSettings[“accountName”];
var strRemoteScope = ConfigurationManager.AppSettings[“RemoteScope”];
DeleteAllFilesAndFoldersInPath(strLocalWorkspace);
var strItemsUrl = “https://{0}.visualstudio.com/_apis/tfvc/items?scopePath={1}&recursionLevel=Full&api-version=5.0-preview.1”;
strItemsUrl = string.Format(strItemsUrl, strAccountName, strRemoteScope);
var wc = new WebClient();
wc.Headers[“Authorization”] = “Bearer ” + bearer;
var strItemsJson = wc.DownloadString(strItemsUrl);
Response.Write(“<hr>”);
var jObject = JObject.Parse(strItemsJson);
foreach (var jItem in jObject[“value”])
{
var strRemotePath = jItem[“path”].ToString();
var strLocalPath = strRemotePath.Replace(strRemoteScope, strLocalWorkspace).Replace(“/”, @”\”);
Response.Write(“Creating ” + strLocalPath + “<br>”);
Response.Flush();
if (jItem[“isFolder”] != null)
{
Directory.CreateDirectory(strLocalPath);
}
else
{
var strItemUrl = “https://{0}.visualstudio.com/_apis/tfvc/items?download=true&path={1}&api-version=5.0-preview.1”;
strItemUrl = string.Format(strItemUrl, strAccountName, HttpUtility.UrlEncode(strRemotePath));
var raw = wc.DownloadData(strItemUrl);
File.WriteAllBytes(strLocalPath,raw);
}
}
}
Categories: Uncategorized

Remote #ErrorLogging in C#

rlc

If you are running a C# Application on a client’s machine, and can’t run the debugger on it, then instead of asking your client to send you log files whenever something goes wrong, you can use a remote logging service to record error events, and view them, and even act on them before the client complains.

This example uses RemoteLogCat.com – a logging service designed for Android, but works equally well in C# / .NET. You will need to have an API Key, and store it as a setting as “RemoteLogCat” in your web.config / app.config

public class Logging
{
public static string key = ConfigurationManager.AppSettings[“RemoteLogCat”];
    public static void Log(string channel, string log)
{
var strUrl = “http://www.remotelogcat.com/log.php?apikey={0}&channel={1}&log={2}”;
strUrl = string.Format(strUrl, key, channel, log);
var wc = new WebClient();
wc.DownloadString(strUrl);
}
}
This is then called using
Logging.Log(“MyApp”,”Your Error”)
Categories: Uncategorized

#ImageRecognition #API with REST webservice

ai

Image Recognition API

This Image Recognition API allows images to be tagged with a label to describe the content of the image, and a confidence score percentage to indicate the level of trust in the algorithm’s judgement. View our homepage at http://imagerecognition.apixml.net

Image Recognition Web Service

The API endpoint can be accessed via this url:

http://imagerecognition.apixml.net/api.asmx

It requires an API Key, which can be applied for via this url:

https://goo.gl/7ND8jG

Recognise

The first API endpoint is http://imagerecognition.apixml.net/api.asmx?op=Recognise

It accepts a url to an image, for example “https://www.argospetinsurance.co.uk/assets/uploads/2017/12/cat-pet-animal-domestic-104827-1024×680.jpeg

And returns a result as follows;

<RecogntionResult xmlns:xsd=”http://www.w3.org/2001/XMLSchema&#8221; xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance&#8221; xmlns=”http://imagerecognition.apixml.net/”&gt;

<Label>Egyptian cat</Label>

<Confidence>3.63228369</Confidence>

</RecogntionResult>

Urls must be publicly accessible, you cannot use localhost urls, or intranet addresses.

RecogniseFromBase64

The next API Endpoint is http://imagerecognition.apixml.net/api.asmx?op=RecogniseFromBase64

It accepts a base64 encoded string containing the image, you must also provide the image format, such as “jpg”, “png”, “bmp” etc.

It returns a result as follows;

<RecogntionResult xmlns:xsd=”http://www.w3.org/2001/XMLSchema&#8221; xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance&#8221; xmlns=”http://imagerecognition.apixml.net/”&gt;

<Label>Egyptian cat</Label>

<Confidence>3.63228369</Confidence>

</RecogntionResult>

OCR Web Service

Optical character recognition converts an image containing text to the text itself, a microsite for this service can be reviewed at http://ocr.apixml.net/ , here, there are two API endpoints exposed

ProcessUrl

Extract text from an image that is available on the internet via a Url. It’s endpoint is here

http://ocr.apixml.net/ocr.asmx?op=ProcessUrl

Urls must be publicly accessible, you cannot use localhost urls, or intranet addresses.

ProcessBase64

Extract text from an image which has been base64 encoded. You also require a file extension (png/jpg/etc) to indicate the format. It’s endpoint is here;

http://ocr.apixml.net/ocr.asmx?op=ProcessBase64

By default, this service will assume a single line of text, rather than a page of text, in order to change this default behavior, or to customise it to your needs, then you can use the “extraArguments” parameter to fine-tune the OCR operation. The full list of these possible parameters are available on http://ocr.apixml.net/

RESOURCES

Contact information

This software is designed by Infinite Loop Development Ltd (http://www.infiniteloop.ie) and is subject to change. If you would like assistance with custom software development work, please contact us below;

  • info@infiniteloop.ie

  • +44 28 71226151

  • Twitter: @webtropy

Categories: Uncategorized

#ImageRecognition in C# using #tensorflow #inception

image recognition

Ever been faced with that situation, where you are confronted with fluffy grey animal, with four legs, whiskers, big ears and you just have no idea what it is ?

Never fear, with Artifical intelligence, you can now tell, with 12% confidence, that this is infact a tabby cat!

Ok, in fairness, what this is going to be used for is image tagging, so that a given image can be tagged based on image contents with no other context. So part of a bigger project.

Anyway,  This is based on EMGU, and the Inception TensorFlow model. Which I have packaged into a web service.

You need to install the following nuget packages

Install-Package Emgu.TF
Install-Package EMGU.TF.MODELS

Then, ensuring your application is running in 64 bit mode (x86 doesn’t cut it!)

Run the code;

Inception inceptionGraph = new Inception(null, new string[] { Server.MapPath(@”models\tensorflow_inception_graph.pb”),
Server.MapPath(@”models\imagenet_comp_graph_label_strings.txt”) });
Tensor imageTensor = ImageIO.ReadTensorFromImageFile(fileName, 224, 224, 128.0f, 1.0f / 128.0f);

float[] probability = inceptionGraph.Recognize(imageTensor);

Where filename is a local image file of our trusty moggie, and the output is an array of floats corresponding to the likelyhood of the image matchine one of the labels in inceptionGraph.labels

The 224, 224 bit is still a bit of dark magic to me, and I’d love someone to explain what those are!

Categories: Uncategorized

Improving .NET #performance with Parallel.For

tuning-performance

If you ever have a bit of code that does this;

var strSoughtUrl = “”
for each url in urls
var blnFoundIt = MakeWebRequestAndFindSomething(url);
if (blnFoundIt)
{
strSoughtUrl = url
}
next

That is to say, loops through a list of Urls, makes a web request to each one, and then breaks when it finds whatever you were looking for –

Then you can greatly improve the speed of the code using Parellel.for to something like this;

var resultCollection = new ConcurrentBag<string>();
Parallel.For(0, urls.Count, (i,loopstate) =>
{
var url = urls[(int)i];
var blnFoundIt = MakeWebRequestAndFindSomething(url);
if (blnFoundIt)
{
resultCollection.Add(url);
loopstate.Stop();
}
});
var strSoughtUrl = resultCollection.ToArray().First()

I have seen this code speeding up from 22 seconds to 5 seconds when searching through about 100 urls, since most of the time spent requesting a url is waiting for another machine to send all it’s data.

This is yet another performance increase for the Car Registration API service! 🙂

Categories: Uncategorized

#OpenSource KBA & Natcode lookup App for iOS in #Swift

690x0w

This app allows German and Austrian users search for German KBA (“Kraftfahrt-Bundesamt”) codes, and Austrian NatCode (“Nationaler Code”) by searching by make and model, or by entering the code in the search box.

There is also an API that allows businesses to obtain this data automatically. If you are interested in the API, please visit our German or Austrian website at http://www.kbaapi.de or http://www.natcode.at

The source code for the app is available (minus the API Keys), at Github: https://github.com/infiniteloopltd/KBA-Natcode/ it’s written in Swift, and it’s the first app we’ve published that’s entirely written natively.

The App itself can be downloaded from iTunes here;

https://geo.itunes.apple.com/us/app/kba-und-natcode/id1378122352?mt=8&uo=4&at=1000l9tW

 

Categories: Uncategorized

Remote error #logging with #Swift

remotelogcat

When you are running your app in the simulator, or attached via USB, you can see your error messages in the debugger, but whenever your app is in the wild, or even on your client’s phone (Or Apple’s testing department) – you can no longer easily see your debug messages, to understand technically, what’s happening in your app.

Remote error logging isn’t new, and you can even knock a simple remote logging mechanism up your self with a little server-side code, but this should make the process super easy for you.

Firstly, Create an Account on “RemoteLogCat.com” and then you get an API key back, then add the following class to your Swift App:

import Foundation

class Logging
{
static var Key : String?
static func Log(Channel : String, Log : String, Completion: ((Bool) -> ())? = nil)
{
if let apiKey = Logging.Key
{
let strChannel = Channel.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)!
let strLog = Log.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)!
print(“\(Channel):\(Log)”)
let url = URL(string: “http://www.remotelogcat.com/log.php?apikey=\(apiKey)&channel=\(strChannel)&log=\(strLog)”)
let task = URLSession.shared.dataTask(with: url!) {(data, response, error) in
Completion?(error == nil)
}
task.resume()
}
else
{
print(“No API Key set for RemoteLogCat.com API”)
Completion?(false)
}
}
}

Then you can simply Log errors to the service using the code:

Logging.Key = “……”
Logging.Log(Channel: “macOS”, Log: “Hello Log!”)

Obviously Logging.Key only needs to be set once, and be aware, that this is an asynchronous method, so if your application terminates immediately afterwards, then nothing will be logged.

You can get a completion handler, by adding

Logging.Log(Channel: “macOS”, Log: “Hello Log!”) {
print(“Success: \($0)”)
}

Where the argument to the completion handler is a Boolean indicating success or failure (i.e. no internet)

 

Categories: Uncategorized

#Bing Image Search using Swift

swift-1

Here’s a quick code snippet on how to use Microsoft’s Bing Search API (AKA Cognitive image API) with Swift and the AlamoFire Cocoapod. You’ll need to get a API key for the bing image search API, and replace the \(Secret.subscriptionKey) below.

static func Search(keyword : String, completion: @escaping (UIImage, String) -> Void )

    {

        let escapedString = keyword.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)!

        let strUrl = https://api.cognitive.microsoft.com/bing/v7.0/images/search?q=\(escapedString)&count=1&subscription-key=\(Secret.subscriptionKey)”

        Alamofire.request(strUrl).responseJSON { (response) in

             if response.result.isSuccess {

                let searchResult : JSON = JSON (response.result.value!)

                // To-Do: handle image not found

                let imageResult = searchResult[“value”][0][“contentUrl”].string!

                print(imageResult)

                Alamofire.request(imageResult).responseData(completionHandler: { (response) in

                    if response.result.isSuccess {

                        let image = UIImage(data: response.result.value!)

                        completion(image!, imageResult)

                    }

                    else

                    {

                        print(“Image Load Failed! \(response.result.error ?? “error” as! Error)”)

                    }

                })

            }

            else{

                print(“Bing Search Failed! \(response.result.error ?? “error” as! Error)”)

            }

        }

    }

It’s called like so:

Search(keyword: “Kittens”){ (image,url) in

imageView.image = image

}

Categories: Uncategorized