Funny ‘Lorem ipsum’ memories

Hey folks

I remember the first time I found ‘Lorem ipsum’ in our codebase. I was working for the Netherlands company so I thought it is something like ‘Hello World’ in Dutch 🙂

I only realized its real meaning when I found the same words at my next job’s codebase.

Funny mistake, isn’t it?

Stay tuned

Posted in Uncategorized | Leave a comment

Funny Out-of-memory error

Hey folks

I’ve just encountered a funny error

I tried to run my virtual machine from VirtualBox and got

virtualbox

I tried to reopen VirtualBox a few times but issue persisted.

I didn’t run anything memory intensive.

Then I open Task Manager and see

taskmanager

Oh wow. Looking into Sublime

sublime

Ah! That’s it. I accidentally pressed F4 in Total Commander so the file was opening in editor and eating my memory.

A gotcha moment 🙂

Stay tuned

Posted in Uncategorized | Leave a comment

‘One long debug story’ or ‘checkbox.onclick’

Hey folks

I spent another working day debugging something simple

I work on a legacy project which has many approaches that are discouraged nowadays.

The problem I tried to solve was around checkboxes. The very simplified version of the code looks like

<input id="abc" type="checkbox" onclick="someWeirdLogic()">
function someWeirdLogic() {
    var str = makeSynchronousAjaxPostback(); // don't ask me why it is synchronous... legacy...
    // and here str is
    // "document.getElementById('abc').checked = true";
    // or 
    // "document.getElementById('abc').checked = false";
    // depending on some server-side logic
    eval(str);
}
public string WeirdResponse(bool currentAbcValue)
{
    bool newValue = !currentAbcValue;
    return string.Format("document.getElementBydId('abc').checked = {0}", newValue.ToString().ToLower());
}

I know it is weird…
But previously it was working…

Now I had to implement a new requirement. Under some conditions you click on the checkbox it should not become ticked

So I implemented

public string WeirdResponse(bool currentAbcValue)
{
    bool newValue = DoSomeAdditionalCheck(currentAbcValue);
    return string.Format("document.getElementBydId('abc').checked = {0}", newValue.ToString().ToLower());
}

But I found that my checkbox is being ticked on and off ignoring this logic.

Then I tried to modify the HTML to skip built-in checkbox click behavior

<input id="abc" type="checkbox" onclick="someWeirdLogic(); return false;">

And now my checkbox is not being ticked at all also ignoring the server-side logic.

I thought maybe there are some other code where my checkbox checked state is being modified and I tried to use the approach I described in my recent post.

So I kinda set a breakpoint on checkbox checked property setter to see what code makes it unchecked.

But that setter was firing only once with true value and when I stopped on the breakpoint, the checkbox was ticked. But later on when I released the debugger, checkbox became unticked again. WTF?!

I did not know what’s going on and tried many-many hours trying here and there. You can imagine that the real code was way more complicated so I spent some time debugging the server-side code first…

And after many hours I realized what’s going on.

We can see this behavior in a much simpler form without going server-side and eval.

<input id="abc" type="checkbox" onclick="document.getElementById('abc').checked = true; return false;">

You can try it http://output.jsbin.com/jidibotaku/

Actually your checkbox is not ticked even if onclick handler explicitly said to make it checked.

And the trick here is to use delayed execution.

<input id="abc" type="checkbox" onclick="setTimeout(function() { document.getElementById('abc').checked = true; }, 0); return false;">

And this works! See it http://output.jsbin.com/sepodevino/1/

You can’t untick the checkbox anymore, but that’s what we explicitly set in onclick handler.

Damn! That was not easy to find at all.

Stay tuned

Posted in Uncategorized | Leave a comment

How to debug JavaScript to find code which modifies your DOM

Hey folks

Sometimes, especially on legacy projects, it’s too difficult to find what code modified your DOM control.

I had such situation recently. I spent almost 5 hours trying to find where some malformed value was coming from.

To simulate the problem, please follow https://output.jsbin.com/wufimi . It has an input and a button. Some bad value is being set to the input value when you take mouse out of the button.

Let’s pretend that that code is not obvious and we have too many JavaScript code to look it through.

1. Our first approach would be to search through JavaScript files to find word bad, but unfortunately it is slightly obfuscated, so we won’t find anything.

2. In modern browsers like Google Chrome you can set breakpoint when DOM element changes. See https://developer.chrome.com/devtools/docs/javascript-debugging#breakpoints-mutation-events . Unfortunately this won’t help us because those events are not triggered when value property is changed. Those events would be triggered if value attribute is changed.

3. We’ll need to try some kind of property debugging. Chrome has some non-standard Object.observe. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/observe . Unfortunately this doesn’t work either. Try it https://output.jsbin.com/cahodo/

4. My next idea is to overwrite value property and set some breakpoint. And that worked. Try it https://output.jsbin.com/kojuvud/
Your F12 Developer Tools should be open.

For completeness I’ll copy the debugging magic code here.

    var input = $("input")[0];
    var defaultDescriptor = Object.getOwnPropertyDescriptor(input.constructor.prototype, "value");
    Object.defineProperty(input, "value", {
        set: function set(newValue) {
            if (newValue.indexOf("bad") !== -1)
            	debugger;
            defaultDescriptor.set.call(input, newValue);
        }
    });

Here input.constructor.prototype could be replaced with input.__proto__, or even HTMLInput.prototype. This doesn’t really matter.

Such if statement is helpful when you are trying to debug changes that happen on focus/blur, as control looses focus when breakpoint hit and it may become extremely annoying.

The call for defaultDescriptor is needed because we want to modify actual value

I did not invent this technique, I found this first http://stackoverflow.com/questions/11618278/how-to-break-on-property-change-in-chrome but it says nothing about defaultDescriptor which is crucial.

I hope this may help you with difficult debugging one day.

Stay tuned

Posted in Uncategorized | 2 Comments

Perfectionist’s hell or SQL formatting

Hi folks

As a programmer-perfectionist I have a habit which is killing me.

Every time I need to add some script to SQL file, I am formatting it manually.

I would like to get a tool which would format SQL for me but everything I’ve tried has some flaws.

I tried online formatters, stand-alone tools and SQL Server Management Studio plugins. I am wasting so much time to configure them but still results are not perfect.

I was already thinking to write my own formatter which formats ideally, but decided to write this blogpost to get ideas from community.

I’ve many people just take the script as it is from SQL Server Management Studio with all that autogenerated crap.

Does anyone had similar problem? What do you do with your SQL scripts?

Stay tuned

Posted in Uncategorized | 1 Comment

jQuery BlockUI and iframe vs require.js

Hi folks

We are using jQuery BlockUI plugin to indicate long-running operations.

progress-indicator.js

(function script() {
    "use strict";

    define(["jquery", "jquery.blockUI"], function module($) {
        function showProgressIndicator() {
            $.blockUI();
        }

        return {
            showProgressIndicator: showProgressIndicator
        };
    });
})();

Also we show popups using iframes.

When we execute long-running operation from popup, BlockUI blocks only popup iframe and that doesn’t look great especially for small popups.

So we want to block the whole page, and to do that we just have to call BlockUI in the global window context.

window.top.$.blockUI()

However, require.js complicates things. If we replace $ with window.top.$, it defeats the whole purpose of the require.js modular approach.

We want to load jquery and jquery.blockUI dependencies from top level window, but there is no a way to achieve this with vanilla require.js so I decided to write a simple plugin.

top.js

(function script() {
    "use strict";

    define([], function module() {
        return {
            load: function load(name, parentRequire, onload, config) {
                window.top.require([name], onload);
            }
        };
    });
})();

then we call this top plugin

progress-indicator.js

(function script() {
    "use strict";

    define(["top!jquery", "top!jquery.blockUI"], function module($) {
        function showProgressIndicator() {
            $.blockUI();
        }

        return {
            showProgressIndicator: showProgressIndicator
        };
    });
})();

Such an elegant solution, isn’t it?

Stay tuned

Posted in Uncategorized | Leave a comment

MSBuild custom task and assembly locks

Hi folks

Sometimes you may want to perform some operations during build which are impossible or at least too difficult to perform using vanilla MSBuild.

For that purpose you may want to use custom task.

The simplest usage would look like

<UsingTask
  TaskName="MyCoolAssembly.MyCoolTask" 
  AssemblyFile="MyCoolAssembly.dll"
/>
<Target
  Name="MyCoolTarget">
  <MyCoolTask />
</Target>

It can be made more complex and pass addition parameters and even define output parameters. But there is not a topic of this blogpost. Read MSBuild documentation if you want to know more.

I would like to discuss one thing that annoys me.

MSBuild loads custom assembly dll into its main AppDomain and therefore this assembly becomes locked until MSBuild exited. So by default after compilation completed MyCoolAssembly.dll couldn’t be removed until Visual Studio (or command prompt) reopened.

There are some workarounds you may find in questions like this http://stackoverflow.com/questions/13510465/the-mystery-of-stuck-inactive-msbuild-exe-processes-locked-stylecop-dll-nuget

But I’d prefer a solution which would work regardless of the way MSBuild called.

And recently I invented a way to solve this problem

<PropertyGroup>
  <TempFolder>$([System.IO.Path]::GetTempPath())$([System.Guid]::NewGuid())</TempFolder>
</PropertyGroup>
<Target
  Name="CopyTaskAssemblyToTempFolder"
  BeforeTargets="BeforeBuild">
  <Copy
    SourceFiles="$(MSBuildThisFileDirectory)MyCoolAssembly.dll"
    DestinationFolder="$(TempFolder)"
  />
</Target>
<UsingTask
  TaskName="MyCoolAssembly.MyCoolTask" 
  AssemblyFile="$(TempFolder)\MyCoolAssembly.dll"
/>
<Target
  Name="MyCoolTarget">
  <MyCoolTask />
</Target>

Here my dll is being copied to the unique temp folder and then loaded and executed from there.

Well, ideally the dll should be removed after execution but to mark dll for deletion we’ll need to P/Invoke MoveFileEx which is too complicated to put into MSBuild script. So my solution will litter into the temp folder a bit but I think it is not that big deal.

Stay tuned

Posted in Uncategorized | Tagged | 6 Comments