Creating random strings for a dummy table

23. Januar 2014

Today I worked on a JavaScript placed in a DirectSmile Crossmedia campaign, which is currently used for supporting auto-completion based on a list of entries coming from a DataRelation. The customer who uses this script asked if we could allow prefixes which will not being recognized by the auto-completion.

Well, sounded like a challenge – perfect for me as I like such things, challenge accepted! Before I could begin I had to get some dummy data… but how?

So I could just create an empty campaign, fill the database with dummy data I have to write on my own and then link it with a DataRelation to the real campaign.

This approach sounds like a plan – but on the other hand it sounds like a lot of manual work to do. And as software engineers are lazy by nature I had the idea for a slightly different approach:

With the latest release of DirectSmile CrossMedia a new feature has been introduced: Scripted DataRelations! This special DataRelation uses JavaScript to produce data. So all I had to do was create some JavaScript which will create my dummy string which fulfills my needs.

To create a random string in JavaScript all you need is a string with all wanted chars – in my case I separated the capital letters from the normal ones and placed them in two strings:

var possibleCapitals = „ABCDEFGHIJKLMNOPQRSTUVWXYZ“;

var possible = „abcdefghijklmnopqrstuvwxyz“;

Now you only need a random number between 0 and the length of each source-string:

for (var i = 0; i < 10; i++) {

randomString += possible.charAt(Math.floor(Math.random() * possible.length));

}

This will create you a random string with 10 characters. Could be enough for my needs but it could even be „fancier“ – using capitals in front of each cityname and different string lengths:

So I’ve added a random length variable with at least four characters and a maximum of 16:

var length = Math.floor(4 + Math.random() * 12);

And added this to my for-loop:

var possibleCapitals = „ABCDEFGHIJKLMNOPQRSTUVWXYZ“;

var possible = „abcdefghijklmnopqrstuvwxyz“;

var length = Math.floor(4 + Math.random() * 12);

var randomString = possibleCapital.charAt(Math.floor(Math.random() * possibleCapital.length));

for (var i = 0; i < length; i++) {

randomString += possible.charAt(Math.floor(Math.random() * possible.length));

}

Now I’ve got a nice function which will render me one single random string with a capital letter at the beginning. So all I needed to do now is to call this snippet of code a couple of times and add each string to my DataRelation output.

After adding a Scripting Relation…

Add a Scripting Relation

… in my campaign I’ve just copy & pasted the code from above to it’s editor…

Edit the data source

… and modified the section where the data is added to the „newRow“ variable:

if(Mode == „GetCount“)
{
    MyTable.ResultCount = 100;
}
else if(Mode == „LoadData“)
{
    var possibleCapitals = „ABCDEFGHIJKLMNOPQRSTUVWXYZ“;
    var possible = „abcdefghijklmnopqrstuvwxyz“;
    var tResult = “;
    for (var n = 0; n < 101; n++) {
        tResult = ‚NAV ‚ + possibleCapitals.charAt(Math.floor(Math.random() * possibleCapitals.length));
        var length = Math.floor(4 + Math.random() * 12);
        for (var j = 0; j < length; j++) {
            tResult += possible.charAt(Math.floor(Math.random() * possible.length));
        }
    var newRow = MyTable.AddRow();
    newRow.SetValue(„ID“, n);
    newRow.SetValue(1, tResult);
}
}
As you can see I’ve already placed my specific prefix to the random string variable („NAV „). And finally I had my data presented:
See the result
And finally I could begin my work on the auto-completion with the nearly correct values 🙂 Challenge won!!
 
Werbeanzeigen

Touch & Gestures in JavaScript with Windows 8

29. Januar 2013

Recently I had to implement touch & gesture support in JavaScript for a Windows 8 touch device (Asus Ultrabook). As I prior had to add Android support to my existing iOS-library I picked a nice framework: hammer.js which supports iOS & Android… but even then they recently updated to support Windows RT on a Surface this did not work out on our new Asus Ultrabook which we bought especially for developing touch support with JavaScript.

So I had to study how Microsoft did implement their touch support. Pretty fast I stumbled over their well documented library. But unfortunately I had to discover that (again) Microsoft did something on their own: Even if Android and iOS did manage to support nearly the same eventtypes („touchstart“, „touchmove“, „touchend“) so you can easily use the same code for both device types, Microsoft introduced two proprietary event types: MSPointer and MSGesture.

So this lead to the point where I had to extend the nice hammer.js framework with new code which handles the special Microsoft events. You can find a fork on github which I will try to add it to the original framework soon when I’ve finished testing.

The main thing about the gesture support is that you have to create a MSGestureObject for each element you want to handle gestures – otherwise you will only get PointerEvents and will need to handle all interpretation by yourself. After you registrated such an object you will get the events with a plentyfull of information about the current gesture and it’s changes – like rotation and scaling. But here comes the disappointment: The online documentation only names it as rotation but unfortunately it’s more like a translation of the CSSMatrix which is also a proprietary object of Microsoft to handle CSS-transformations. So as I wanted to extend a framework which delivers a wrapper-event with these information I had to pull back and calculate the scaling and rotation by myself instead of using the quite cool but in this scenario unuseful features.

During my work I stumbled over several issues with the MSPointer & MSGesture events which I would like to share:

Event Bubbeling
One issue is that the event bubbeling in IE10 works bottom-up – on iOS or Android it’s top-down… so after realizing this (and it unfortunately took quite long) I finally got an answer why I retrieved events from the wrong HTML elements – something which can be real disturbant when you try to register the MSGestureObject only for these elements you want events for.

Dual Events
Another problem is that even when MSGesture-events are fired the browser still continues to throw the MSPointer-events – fortunately this is something positive as you can now record your own „touches“-array… As the MSGestureEventObject comes with already calculates scale and rotation, they simply miss an array of touches with the coordinates of the finger-tips… As the hammer.js and my own implementation take big usage of these arrays I had to implement my own array with the MSPointerEvents.

Still MouseEvents
On our Ultrabook we had also the problem that the touch device also fires a Mouse-event each time you tap or drag something… as this is normally not to be expected the initial author of the hammer.js-framework simply ignored this and interpreted each mouse event as a touch-event… I expected Windows 8 to hold back the mouse events as I’m really only touched the screen.

Debugging
Finally there is to say that there does not really exists a nice debug-tool for the IE10 in touch-mode (or Metro-Style or however it is called)… so I had to turn back to classic „debug.print“/“console“-debugging by writing my own debug-console to the DOM… Every iOS-developer without Safari 6 (see my last post) will know what I mean.

Identify
UPDATE: Currently I’m struggeling with identifying whether the IE10 comes as Metro or desktop version… unfortunately there is no clear way to identify. The best practice is that you can only hope the desktop version is not started as 64-bit application and so you can lookup the userAgent-string. See this stackoverflow question for more details.

Our next question is how a Microsoft Surface behaves with Windows 8? On Windows RT it seems to simply send „touch“ events as there is a contributor of the hammer.js-framework who added Surface-support without interpreting new event types. But unless I do not have a Surface-device in my hands I will not be able to say something about it. But when I get hold of such a device I will post an article of course.


Hidden feature in Apple iOS 6 for web developers

10. Januar 2013

Developing mobile pages sometimes is really difficult – especially if you want to use JavaScript. Normally you have some nice develop tools like FireBug or the Internet Explorer Develop Tools… but on a mobile device there simply does not exist any like that.

Adobe had the idea of an interconnection between Chrome and an App on your iPhone – something nice but first it was really buggy and second it is not for free anymore.

But with iOS 6 there is a hidden feature (or simply instead of the „activate javascript console“ menu entry) which allows you to connect to your desktop safari and simply debug there. Wow… a really nice tool – at first.

After downloading the latest version of Safari I followed the simple instructions to enable the iPhone-support and then there happend nothing… A short lookup simply explained my situation: The iOS6 feature for remote debugging simply works only for Safari 6.x – and for a windows based machine there only exists 5.x even if the version 6 is already released for more than half a year.

So for me it is simple to say: Great job Apple… Having iOS 6 installed on my mobile device and NOT having a Mac (I decided to buy an equivalent PC and a car instead) this simply results in being unable to develop mobile pages with javascrit for iOS-devices… This idea must have come from a genious…


Facebook Development: Posting Feeds and Uploading Images

12. Juni 2012

Currently I’m working on some experimental stuff with Facebook and their JavaScript SDK which can be used in several cases like e.g. a FacebookApp, your own website when integrated the FacebookLogin etc pp.

When learning how to use the SDK you will soon recognize that the documentation is a little bit short – just with the experience from other users who share their knowledge I solved my problems. That’s why I want to share mine too – maybe it helps someone who stumbles by accident over this blog.

So when working with the JavaScript SDK you will get a really powerfull jQuery-like weapon to get access to someones Facebook-account – if he/she grants you the access. For today I will restrict my article on how to post to the users wall and „upload“ a picture to ones album via JavaScript.

When working with the tutorials you will come to a point where you find the first approach on how to post a feed via javascript: Do a HTTP-POST call to an url with the message as JavaScript array. Basically this works fine – but when trying to do this asynchronously you will fail due to the cross-domain-policy rules which will only allow a GET.

But working with the SDK this is easy as anything else:

FB.api('/<TARGET>/<WHAT>', 'post', {
message: '<MESSAGE>' },
function(response) {   if (!response || response.error) {     alert('Error occured');   } else {     alert('Post ID: ' + response.id);   } }); }

Or more as an example:

FB.api('/me/feed', 'post', { message: 'Hello world!' }, function(response) {   if (!response || response.error) {     alert('Error occured');   } else {     alert('Post ID: ' + response.id);   } }); }

As you can see it is simply the same as the first intention: You get a target („/me/feed“) and depending on your choosen target you will need to support a dynamic array of data. In this case the simple message „Hello World!“.

Now to „upload“ an image – as you should know it is impossible to really upload an image via JavaScript as this would open a direct door to your computer files. But you can support an URL of an image which will then be „uploaded“ to the users album you targeted at or in case you did not defined a target album id it will then create a new album with the registered FacebookAppName:

FB.api('/me/photos', 'post', {
message: msg,
url: pic },
function(response) {   if (!response || response.error) {     alert('Error occured: ' + response.error.message);   } else {     alert('Post ID: ' + response.id);   } });

Now it should be a little bit easier to understand the documentation of the Facebook-API as we now have a nice tool (the SDK) given to access all the nice litte informations we’re offered by Facebook about the users of our websites or Apps.

But always think of the policies about posting in name of others: You have to follow the rules and you should not post without the users permission. So better do it visible instead silently in the background – this could harm your reputation as a company and also have other consequences.


Be careful using jQuery’s .click()

19. Dezember 2011

Today I would like to share my current experience with jQuery event handler registration and why you should not use jQuery’s .click()-function:

In my current project I need to use lots of javascript and of course startet from begin to use jQuery as one of the most useful (if not THE most useful) javascript-frameworks. Currently my script uses plenty of event-handlers all added via .bind() from jQuery. Additional I use a nice little script for contextmenues which I found to be very useful and easy to integrate (https://github.com/joewalnes/jquery-simple-context-menu).

Unfortunately this contextmenu uses .click() to bind the handler for the menu-entries. For the first weeks this did noch caused any issue – unless last weeks Internet Explorer update (maybe it could be of interested that we primarly develop for IE and currently do not regard the other browsers). So today one of my colleagues came up and reported to me that the context menu is not working anymore.

So what seems to have happened is that Microsoft decided to fix their event-handling: My code defines a global mouse-down-event which eleminates data which my contextmenu needs. Of course it make sense that a mouse-down is called before a mouse-click as the click-event only is kind of virtual event and combines mouse-down and mouse-up. But as it always worked fine for me and I did not took a closer look into the context-menu-script…

Here the code as it was before:

row.find('a').click(item.action);

And as I modified to prevent the global mouse-down-event:

row.find('a').bind('mousedown', function (e) {
                        return false;
                    }).bind('mouseup', item.action);
 
Happy Shopping!!

ReSharper 6.0 – First Impressions

16. Dezember 2011

About a week ago I’ve been allowed to use the companies credit card to purchase an update of ReSharper to version 6.0. ReSharper is a really nice plug-in for Microsoft Visual Studio enhancing it with several really useful functions (eg. „Find Usage“, a whole pallette of refactoring tools and code-style-checks).

The new version offers better support for JavaScript and HTML5 and many other things which I’ve been not able to test yet.

But nevertheless I want to share my first experiences:
One of the very fist things I recognized was the visual alert that I’m not following the coding-conventions – especially the naming of variables and functions. With one of my colleagues I discussed the pro’s and cons about this special convention – but finally to say that I think this is a great feature as you start writing code which follows at least one 😉

Also improved are the automatic correction options: Now you’re presented to mostly all „wrong“ parts of code some options to fix it or improve it. Something I do not want to miss anymore…

But with all these „wow“s and „yeah“s there is also one major „d’oh“: The speed of my IDE went down the basement… At several moments I’m able to type words faster than they appear on the screen – not because I’m a hell of a writer but the IDE reacts many times slower than without the plugin. Hopefully the guys from JetBrain will fix this soon.

Stay tuned in case I write a longer review after working more and more with ReSharper.

Happy Shopping!!!