Tuesday, January 22, 2013

Embedding Images into HTML Pages

Just another trick used for the offline page mentioned in this post.  The page should display a number of images (like jQuery UI theme icons) and they have to be completely available after the page is downloaded.  If you save the page from the browser menu it creates the additional folder named MyCoolHtmlPage_files (assuming the page is named MyCoolHtmlPage.html) and places all downloadable from the same server resources there.  JavaScript, CSS files, images - all of them go into that folder.  But I think for downloadable page it is not a good idea to give our users the page itself and all needed support files separately.  So we need to embed all the resources into the page.  It is no problem to embed JavaScript and CSS files as they are just a plain text.  Images are less friendly.

Fortunately all modern browsers support the data URI scheme which allows us to embed the actual image content into the CSS resource URL.  For one of embedded jQuery UI backgrounds this will look like:

.ui-widget-header {
    background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSU
hEUgAAAAEAAABkCAYAAABHLFpgAAAALElEQVQYlWN49OjRfyYGBgaGIUT8//8fSqBx0
Yh///4RL8vAwAAVQ2MNOwIAl6g6KkOJwk8AAAAASUVORK5CYII=');
}

Yeah, some effort is needed to convert all used images into Base-64 encoded strings and write appropriate styles to override standard ones but I think it is minor (I just used an online encoder).

Note: Not all browsers support newlines in the url() so it is a good idea to place embedded data on the single line.  I have added newlines to my example just for readability (if the word "readability" is applicable to the Base-64 encoded binary data).

X-Posted to: http://hill30.blogspot.com/2013/01/embedding-images-into-html-pages.html

Friday, January 18, 2013

From Twitter

if (Thread.currentThread() != null) { ... }

Looking for JavaScript Decompressor for Data Compressed by C#

It happened that I needed to make an HTML page.  Sometimes such things happen, you know.  That page was required to be completely offline, just a snapshot of some piece of data being downloaded by users for further analysis.  At the same time that offline page was required to be as interactive as the online page with the same data.

The online page for that data contained grid with "master" rows and upon clicking on the row it presented a dialog box with "details" loaded from the server by AJAX request.  The offline page could not use AJAX so it should contain all needed data, both "master" part and all the "details", inside it.  The average amount of data used on these pages was not very small - about 3 megabytes in JSON format, so it was decided to compress that data on the server side and decompress needed pieces on the fly when they should come into the dialog.

The code for the server side was not very complex.  As the web application uses ASP.NET MVC and is written on C# I could use standard .NET classes for compression like either System.IO.Compression.DeflateStream or System.IO.Compression.GZipStream:


var details = new Dictionary<string, string>();
foreach (DataRow row in detailsData.Rows)
{
    var text = Convert.ToString(row["details_content"]);
    var bytes = Encoding.UTF8.GetBytes(text);
    using (var ms = new MemoryStream())
    {
        using (var zipStream = new DeflateStream(ms, CompressionMode.Compress))
        {
            zipStream.Write(bytes, 0, bytes.Length);
            zipStream.Flush();
        }
        details[Convert.ToString(row["master_id"])] = Convert.ToBase64String(ms.ToArray());
    }
}
viewModel.ZippedResultsJson = EncoderHelper.SerializeToJsonString(details);

But what to do on the page?  Are there any JavaScript implementations of, say, inflaters?  Initially I thought that these days there are lots of them as probably almost all things are already implemented in JS.  But when I tried to look for them I've found that things are not that good.  Actually there are just a few implementations of deflate/inflate algorithms and not all of them look working.  Thanks StackOverflow, they know answers to almost all our questions and I've found lots of answers how to get some of JS decompressors to work with Java or Python server-side compression.

But just a pair of questions about C#-JS were answered like "just use the browser gzip support", i.e. encode the whole response.  This is not my case as I don't have response so I tried to use some of implementations to see which of them is more usable.  Things were worse than I expected, no one of relatively small inflate implementations worked with C#'s DeflateStream-compressed data (although they worked quite fine with data compressed by themselves).

So I decided to try gzip instead of the "raw" deflate.  And I've found the only JS implementation of gzip decompressor on http://jsxgraph.uni-bayreuth.de/wp/2009/09/29/jsxcompressor-zlib-compressed-javascript-code/.  I tried it and it worked!  (Of course, I've changed the DeflateStream to the GZipStream on the server side).  Lots of thanks to those guys who created that really working tool!  With it all I needed on the page was just:

$('#details-div').html(JXG.decompress(detailsData[masterId]));

And that's it!  Simple, usable, great!  And it does Base-64 decoding inside so there is no need to use separate decoding tools or libraries.  Great job guys!  Now I know the right tool for this task.

X-Posted to: http://hill30.blogspot.com/2013/01/looking-for-javascript-decompressor-for.html

Thursday, January 17, 2013

The First Post

Okay, let's see what's up.  Probably here should be some words about me, my bio, my experience, references to my other profiles and so on and so on.  And maybe I'll add such an official post later... not now.

Actually I am going to publish programmer's tricks from my own experience.  And if these tricks are useful for somebody else it will make me happy.

So please welcome and enjoy!