Category Archives: ASP.NET

Copy/Paste image into an editable DOM element in Chrome

All major browsers allow to paste image directly into a DOM element with contentEditable property set to true. They automatically convert it into IMG element with source pointing to base64 encoded DataURI of the pasted image. That is all browsers, but Chrome. Chrome needs a little help.

In my particular case I need to be able to paste image into an IFRAME with editable body of the content document (for some reason Infragistics WebHtmlEditor ASP.NET control renders itself as this contraption). But the code below applies (with small changes) to any editable DOM element.

To achieve the result we need to perform 3 tasks:

1. Capture image from the clipboard
2. Convert the image to DataURI format
3. Create IMG element with the DataURI source and insert it into the DOM

Take a look at the code below:

if (window.chrome) {
    var elem = document.getElementById("myIframe");
    elem.onload = function () {
        elem.contentWindow.addEventListener(
          "paste", function (event) {
            var me = this;
            var items = (event.clipboardData ||
                event.originalEvent.clipboardData).items;
            var blob = null;
            for (var i = 0; i < items.length; i++) {
                if (items[i].type.indexOf("image") === 0) {
                    blob = items[i].getAsFile();
                }
            }
            if (blob !== null) {
                var reader = new FileReader();
                reader.onload = function (event) {
                    var image = new Image();
                    image.src = event.target.result;
                    image.onload = function () {
                        var range = 
                            me.getSelection().getRangeAt(0);
                        if (range) {
                            range.deleteContents();
                            range.insertNode(image);
                            me.getSelection().removeAllRanges();
                        } else {
                            me.document.body.appendChild(image)
                        }
                    }
                }
                reader.readAsDataURL(blob);
            }
        })
    }
}

Line 1 Checks the browser for chromness (well Edge if you want to pretend to be Chrome – so be it)
Lines 2-3 Grab the IFRAME element and attach onload event handler so we would know when it’s good and ready
Lines 4-8 Attach onpaste event handler and grab clipboard data when the event fires
Lines 10-14 Loop thru clipboard items and if an image is found – read it as blob file
Lines 16-17 Initiate file reader and attach onload event to it so we know when the reading (that begins on line 29) is complete
Lines 18-20 Create a new IMG element, assign DataURI result from file reader as IMG source and attach onload event so we know when the image loading is complete
Lines 21-29 Check if we’re inserting into or replacing any existing data at the target and if so – inserting image into selected range, otherwise simple append it to the target.

And that’s it – with this addition you’re now able to copy/paste images into Chrome in the same way as old respectable browsers do.

Tweet images with Scriptr and IFTTT

Sev Trek

Looks like everybody is doing Twitter bots these days so I decided to try my hand on one as well. And it had to be something lighthearted – to let people’s mind off things for a while. Way back in early 2000s there was a funny parody comic of Star Trek called Sev Trek. Original site is gone now, but archive of images was saved at http://sevspace.com/stupidarchive/sevtrek.asp.htm. Images are numbered sequentially – ideal for automatic processing. My bot would tweet random images every couple hours.

To host bot’s script I decided to go with Scriptr which offers powerful JavaScript backend and multiple expansion modules. And IFTTT has a cool Twitter service, one that can tweet image from an URL. So the idea was:

  1. Code hosted at Scriptr generates URL pointing to an image at sevspace.com
  2. Code then call Maker service of IFTTT – custom service capable of accepting HTTP requests
  3. Maker service triggers Twitter service and passes URL of image it got from Scriptr code
  4. IFTTT Twitter service tweets the image

Continue reading →

Using FusionCharts in SSRS reports

Microsoft’s SSRS is pretty advanced reporting system with multitude of advanced features. SSRS also has charting capabilities, but it’s somewhat lacking compared to more advanced desktop or web charting suites

On the other hand FusionCharts offers very cool charting package with gazillion of chart types and very cool features. But it uses JavaScript engine and renders charts client-side only!

What if there was a way to marry the two technologies together – to render cool FusionCharts in advanced SSRS repots? Continue reading →

Simulating Pebble GPath in Rocky.js

RockyJS is a black magic voodoo from Pebble Dev team. It allows you to run your JavaScript code on the actual smartwatch (unlike PebbleJS that runs on the phone). When RockyJS debuted it ran as a simulation in a browser, but since then it matured and now runs in Pebble emulators and on actual hardware.

RockyJS changed drastically since that web release. It resembles C code less and takes more standardized JavaScript approach. During that transition some features were lost. One of them is Pebble GPath concept – a graphical object that consist of set of coordinates that you can freely move and rotate. In particular missing commands gpath_move_to, gpath_rotate_to and gpath_draw_outline that move, rotate and draw the GPath. When I was porting my first Pebble watchface to Rocky I used those extensively. You can read about that implementation complete with the source code here. But now the commands are gone and I needed a substitution. Continue reading →

Future Time – watchface for Pebble smartwatch

http://tinyurl.com/timefu

This is the face of the future.

Two faces actually – because you get both analog and digital face – and it’s up to you which one to use. You also get eight predefined color themes as well as ability to set each color individually. This face also provides weather and fitness tracking at your fingertips. And it just looks cool.

Key features:

– Digital or Analog face type selection
– Multiple color themes as well as custom color settings (or you can leave it on auto and the color will depend on battery level)
– Weather (powered by Forecast.io), Step Counter, Distance Walked, Sleep Hours
– Bluetooth Connect/Disconnect alert of configurable intensity with visual clue
– Battery level represented by percentage number as well as visually by outer perimeter of dots (also by watchface color – if in auto color mode).
– Visual step goals

$0.99

After installing watchface you have a 3-day trial period to explore all the features and different aspects. At the end of trial if you like Future Time and want to keep it – it’s just $1.50 USD via Kiezel Pay payment system, you will be prompted to enter code and follow few easy payment steps. Once purchased – the watchface is yours permanently, no matter what Pebble or what phone you use, as long as you keep the same Pebble account.

You will need to get free key for weather services at https://developer.forecast.io – this is one time procedure.

Design by Paul Joel http://www.pauljoel.com

CobbleStyle 2 – watchface for Pebble smartwatch

http://tinyurl.com/cobblestyle2

CobbleStyle is back! This time with THREE modes to display the time: analog, digital or BIG TIME! With complete customization on what information you want displayed. With pre-designed color sets and complete color customization. Make CobbleStyle 2 how you want it!

Key features:

– Three Ways to display the time: Analog, digital, or BIG TIME!
– Multi-language support
– Anti-aliasing text and graphics.
– Date / Weather / Bluetooth connection.
– GPS Location.
– Week number.
– Local time.
– Alternative timezones.
– AM/PM.
– Seconds counter.
– Pre-designed color sets.
– Custom colors.
– Custom text.
– Backlight when charging option.
– Bluetooth alert options.
– THREE weather providers – choose most reliable for your location
– Master Key weather provider control via https://www.pmkey.xyz – store all your weather API keys in one convenient location

Health Info:

– Step Count
– Live step goal bar.
– Custom step goal.
– Distance Walked
– Time Active
– Calories burned at rest
– Calories burned while active

Only $0.99 USD

After installing CobbleStyle 2 you will have a three days trial period to explore all the features and different aspects. At the end of the trial if you like CobbleStyle 2 and want to keep it, it’s just $0.99 via KiezelPay payment system. You will be prompted to enter code and follow easy payment steps. Once purchased, the watchface is yours permanently, no matter what Pebble or phone you use, as long as you keep the same Pebble account.

Design and Art Direction by Paul Joel – http://www.pauljoel.com

API keys for weather providers

Many apps and watchfaces for Pebble smartwatch provide weather information and many of them require you to have your own key, unique for each weather provider. Here’s how to obtain API keys for 3 major most popular weather providers:

  1. For Forecast.io register at https://developer.forecast.io/ – and at the very bottom of the page there will be long string of letters an numbers – that’s the key.
  2. For OpenWeatherMap register at https://home.openweathermap.org/api_keys and you will see a form create your API key there
  3. For WeatherUnderground go to https://www.wunderground.com/weather/api, click LOGIN button, fill the form to create account, go to “Key Settings” in menu and generate your API key there

It is *highly* recommended once you get your keys – save them at https://www.pmkey.xyz service. Then all you have to remember to get them is simple 5-digit pin and more and more watchfaces (CobbleStyle 2 being one of them) use this service for easy key retrieval.

Full control of your Limitless LED/Milight bulbs from Amazon Echo

Limitless LED Limitless LED offers full color RGBW light bulbs that you can control over Wi-Fi/4G from your computer, phone or smartwatch. They’re an inexpensive alternative to Philips Hue and they look really cool.
But I, being lazy ass that I am, was wondering if you can control the lights from Amazon Echo by voice commands alone. Out of the box Echo and Limitless LED don’t recognize each other. Amazon can see and control Hue, but not Limitless LED. Fortunately geniuses of BWS Systems came up with a really cool piece of software – home automation bridge “HA-Bridge”. It’s free and written in Java so it can run pretty much in any environment under any OS. What it does – it emulates Philips Hue API so other devices on your network – like Echo – can see and interact with it. Continue reading →

Flicker-Free IFRAME refresh

One of our projects consists of single parent page and “widgets” that display secondary (classic ASPX webform) pages. A recent feature request was to auto-refresh widget information at given intervals. On the surface it was pretty straghtforward:

<iframe id="xIfrWidget0"></iframe>
var ifr = document.getElementById('xIfrWidget');

setInterval(function () {
   ifr.src = 'widget.aspx';
}, 2000)

The problem with this approach – there’s an ugly flicker of white between page refresh and the goal was to keep displaying current IFRAME content up until refreshed content is ready. Yes, there’re various AJAX-ified methods (including ASP.NET UpdatePanel) – but they add unnecessary overhead and may cause other issues.

The solution was suggested by this Stack Overflow post. The idea is to have secondary, hidden IFRAME into which perform actual load. Once load complete – switch IFRAMES – currently visible with old content becomes hidden, and hidden one with new content becomes visible. It goes something like this: Continue reading →

Pebbles, rectangles and stack overflow

UntitledWhile working on my Pebble watchface “Future Time” I have encountered persistent annoying problem – watchface would run for a while and then crash – and not only crash, but actually restart the watch. What made this even more frustrating – after 3 restarts in a row Pebble would revert to recovery mode and complete firmware reinstall was required (did I accidentally write a Pebble virus?).
When I dug into device logs I found out that every restart was given reason: “Dangerous Stack Overflow”. Which is kinda strange – I don’t have any recursions nor deeply nested function calls nor large local variables. I tried lots of things – including extreme ones like declaring all local function variables as global or static – nothing helped.
Finally Christian form Pebble developers forum shed a light. He pointed out that I use a lot of GRect constructs which is basic rectangle building block for pretty much anything from defining layers to graphics functions. I used GRect inline directly inside function calls, which I thought wasn’t a big deal, after all “everybody does that” – including Pebble in its examples. Well, as Christian pointed out those GRects are kind of local variables, and either memory is not reclaimed fast enough when they go out of scope or they spring memory leak.
Keeping this in mind I created a global GRect variable and when needed to use a GRect in local function, first I’d assign it’s value to the variable and then use variable in the function.
So something like this:

static void layer_update(Layer *layer, GContext *ctx) {
   //...
   graphics_draw_rect(ctx, GRect(10, 10, 30, 30));
   //...
   graphics_draw_bitmap_in_rect(ctx, bitmap, GRect(20, 20, 40, 40));
}

Becomes thus:

GRect temp_rect;

static void layer_update(Layer *layer, GContext *ctx) {
   //...
   temp_rect = GRect(10, 10, 30, 30);
   graphics_draw_rect(ctx, temp_rect);
   //...
   temp_rect = GRect(20, 20, 40, 40);
   graphics_draw_bitmap_in_rect(ctx, bitmap, temp_rect);
}

That’s it. This simple change cured the plague, no more crashes, restarts or recovery – just smooth sailing.