Editing any document directly from the Windows Explorer using Notepad plus plus

This is a very short post on the excellent integration of Notepad++ with Windows Explorer Shell. I don’t know about you, but quite often, I want to look at contents of various kinds of files e.g. a XAML file or HTML file or a visual studio project (csporj, vcproj) file. If you try to double click one of these files, they will get opened in their respective programs e.g. in Internet Explorer or Visual Studio. Sometimes, I just need to look at the contents. The usual flow goes like, in Windows Explorer, right click on the file, select “Open With” and then hit “show more options” and then finally select notepad. Now Notepad is a fine enough software. It has shipped with Windows since, well, since forever. However, it is an extremely bare bones software. Often times I desire an editor with more advanced functionality.

And then along came Notepad++. I have been using Notepad++ for a long while. It is, as the name suggests, Notepad on steroids. You can download it from the above link. It has syntax coloring for many languages. Can open pretty large files, has tabs for editing multiple files, opens up in a jiffy and best of all, it directly inserts a menu in the Windows Explorer right click menu named “edit with Notepad++”.

And there, that is a little tidbit that saves me time and frustration when editing files with non-text extensions.

 

How to pass loop variables in a JavaScript callback

This is a common problem encountered i.e. if you are making ajax calls in a loop and you need access to the loop index in the AJAX callback, people often hit the JavaScript ‘reference’ behavior i.e. copying or assigning one variable to another merely makes a reference, not a full copy. This even holds for variables like loop indices, which is extremely counter-intuitive. Anyway, this can be accomplished via JavaScript closures.

1
2
3
4
5
6
7
for (var i = 0; i < arr.length; i++) {
  (function(index) {
    // do your stuff here
    // use the index variable - it is assigned to the value of 'i'
    // that was passed in during the loop iteration.
  })(i);
}

The full answer with more context is present at Stack Overflow

ASP.NET MVC – Adding RequireJS/Backbone/Marionette to your solution

Recently, while build a website on Azure, I needed a quick, simple login mechanism. There is an ASP.NET forms based authentication template, so this was pretty straightforward. All you have to do is to create a website based on the template and viola!, you have a login. However, if only life is so simple. The issues arose when I wanted to integrate a single page application architecture with RequireJS and Backbone.js/Marionette.js. A single page application architecture is a Web Page the likes of Gmail or Facebook where a single page opens up and then all the functionality that you require is available from that page without you needing to navigate out of that page. There are a few templates that already have backbone included but they don’t have all the pieces that I required i.e. requirejs, backbone and marionette. I already had all my single page architecture code in a folder called “public”, so I wanted the least amount of hassle to integrate this.

After some mucking around, this is what I figured out:

Simply go and delete most of the content from the folder Home/index.cshtml. This page is shown only after the user has logged in, so you can host the entire single page HTML app in there. After you have cleaned this page out, simply copy paste the require.js main function call in here. In my case, this looked somewhat like:

1
2
3
4
5
6
7
8
9
10
11
12
13
<!--
    Note that all the code below resides in a completely separate directory called public.
    This way, all my JavaScript and HTML code resides in a folder that has got nothing to do with ASP.NET MVC
    and hence has clean separation. I could easily take this code and port it over to node.js or other webservers.
-->
<link href="@Url.Content("~/public/scripts/vendor/bootstrap/css/bootstrap.min.css")" rel="stylesheet" type="text/css"/>
<link href="@Url.Content("~/public/scripts/vendor/bootstrap/css/bootstrap-theme.min.css")" rel="stylesheet" type="text/css" />

<!-- Note that the following call loads up the requirejs and loads up main.js which contains the app router -->
<script data-main="public/scripts/main" src="public/scripts/vendor/requirejs/require.js"></script>

<!-- This div is used by main.js to load up the application in the div with id=dashboard-->
<div id="dashboard"></div>

The cool thing about keeping all the HTML templates and JavaScript in a separate directory such as public is that this method works for any JavaScript libraries – and you don’t need to depend on any ASP.NET templates that ONLY integrate a specific set of libraries.

C++/Cx: Getting around the very limited DateTime object

You know, I have been writing a LOT of C++/Cx recently and I have hit a bunch of issues. This particular one is about the DateTime object in C++/Cx. If you look at the C# version of the DateTime object, it contains a ton of niceties. There are properties that will give you the Day, Hour, Minute, Seconds, add time to it, remove time to it… I guess you get the point. So, when I had to do some similar operations in C++/Cx, I typed DateTime-> and waited for intellisense to show me all the properties. Unfortunately, all it showed me was a single member called UniversalTime!! I looked a bit deeper and I realized all you get is a 64 bit signed integer which represents time in 100 nanoseconds interval. I almost bit my lip in frustration as I felt like I have gone back to the era of Win32 and FILETIME. Especially so, since the documentation very helpfully suggests that the DateTime.UniversalTime has the same granularity as the FILETIME

After much searching, I finally found something that saved the day. Ta-Da! Here is the well kept secret courtesy the following support page. What you really need is the Windows::Globalization::Calendar class where you can set the value to whatever DateTime you want by using Calendar::SetDateTime. You can do whatever manipulations you want on the calendar object and then finally get a DateTime object back from the calendar. For instance, if you just wanted to get the current time and add a few seconds to it, you could do the following:

1
2
3
4
5
Windows::Globalization::Calendar^ calendar = ref new Windows::Globalization::Calendar();
int expiresInSeconds = 20;
calendar->SetToNow();
calendar->AddSeconds(expiresInSeconds);
DateTime myDateTime = calendar->GetDateTime();

One more problem I faced was that I needed to get the max value of DateTime. I could have calculated it but that is way too much work. This works just fabulous:

1
2
3
Windows::Globalization::Calendar^ calendar = ref new Windows::Globalization::Calendar();
calendar->SetToMax();
DateTime myDateTime = calendar->GetDateTime();

In short, DateTime seems like a structure, that one should wrap up in the Calendar object as soon as possible, do all the manipulations on the calendar and convert back to DateTime as needed.

Cheers

WinRT in C++/Cx and registering and unregistering event handlers

Having to work in C++/Cx, every day I have new appreciation for C#. Things that I take for granted in C#, well, they are not straightforward C++. Take the example of event handlers.

In C#, the usual way of registering and unregistering event handlers is pretty straight forward:

e.g. Click += Button_click_handler and Click -= Button_click_handler

I tried to do the same in C++/Cx and got a nasty shock. That is not how it works! It took quite a bit of searching and finally I reached this MSDN page:

http://msdn.microsoft.com/en-us/library/windows/apps/Hh758286.aspx

The MSDN page, neatly sums it up:

If you need to remove an event handler in C++/CX, you’ll need a registration token, which you should’ve received from the return value of the += event handler registration. That’s because the value you use for the right side of the -= deregistration in the C++/CX syntax is the token, not the method name. For C++/CX, you can’t remove handlers that were added as a XAML attribute because the C++/CX generated code doesn’t save a token.

I could not really find any code samples in 15 minutes of searching, so by trial and error, this is what I figured out

The event registration call returns a token. You need this token to later de-register, so better save it, else you will not be able to deregister. If you declared your event handler in XAML, well, forget about deregistration. You need the token, so if you really want the ability to deregister the event handler, you will have to move the event handler registration from XAML to code behind.

This is how ended up writing the code (I was writing an event handler for the LoadCompleted event in WebView):

In the header file for the WinRT XAML control:

1
Windows::Foundation::EventRegistrationToken myEventHandlerRegistrationToken;

In the C++ code behind file, to register the event handler:

1
2
3
4
5
myEventHandlerRegistrationToken = this->myWebView->LoadCompleted += ref new LoadCompletedEventHandler(this, &MyUserControl::myWebView_LoadCompleted);

void MyUserControl::myWebView_LoadCompleted(Platform::Object^ sender, Windows::UI::Xaml::Navigation::NavigationEventArgs^ e)
{
}

And then to unregister the event handler:

1
this->myWebView->LoadCompleted -= myEventHandlerRegistrationToken;

Getting access to the UI dispatcher from a background thread (Win8/8.1)

I recently struggled quite a bit trying to get access to the UI dispatcher from a background thread. I had a scenario where when I receive a push notification, I had to update the XAML page UI. Obviously, I did not have access to the UI thread from the background thread so I binged quite a bit. Surprisingly, the documentation on this is not clear and I had to go through quite a bit of searching to find the right answer. Here it is for future reference:

1
2
3
4
5
await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.High,
() =>
{
     // UI stuff here
});

C# synchronization blocks containing await or how to lock a block with an await

Recently working on a project, I came across a scenario where I needed to lock a block so that only one thread could enter the block at a time. Simple Monitors, I thought. However as soon as I put the C# lock statement around my block, I noticed Visual Studio started complaining. The problem was that the block contained an await statement like so:

1
2
3
4
5
Object lockObj = new object()
Lock(lockObj)
{
  Await fileIO
}

This was a big head scratcher. I mean, the whole reason we use async/await is because we are spinning threads to go do some work and then invoke the UI thread back on the callback, right? So effectively we are creating multi-threaded programs, right? So we need synchronization primitives, right? So the C# lock statement should work, right?

Grrr! That does not work.

Now what?

I am certainly not the first person to hit this issue.

Someone must have done it already. Let’s Bing!

So, yes, in summary, I did find a solution. The solution was provided by the Awesome Stephen Toub from Microsoft. He summarized the solution using an elegant construct called AsyncSemaphore and AsyncLock. Brilliant!

Here are the links:
http://blogs.msdn.com/b/pfxteam/archive/2012/02/12/10266983.aspx
http://blogs.msdn.com/b/pfxteam/archive/2012/02/12/10266988.aspx

Here is the full code in case you don’t want to copy paste it step by step from the above:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
    // http://blogs.msdn.com/b/pfxteam/archive/2012/02/12/10266983.aspx
    public class AsyncSemaphore
    {
        private readonly static Task s_completed = Task.FromResult(true);
        private readonly Queue<TaskCompletionSource<bool>> m_waiters = new Queue<TaskCompletionSource<bool>>();
        private int m_currentCount;

        public AsyncSemaphore(int initialCount)
        {
            if (initialCount < 0) throw new ArgumentOutOfRangeException("initialCount");
            m_currentCount = initialCount;
        }
       
        public Task WaitAsync()
        {
            lock (m_waiters)
            {
                if (m_currentCount > 0)
                {
                    --m_currentCount;
                    return s_completed;
                }
                else
                {
                    var waiter = new TaskCompletionSource<bool>();
                    m_waiters.Enqueue(waiter);
                    return waiter.Task;
                }
            }
        }

        public void Release()
        {
            TaskCompletionSource<bool> toRelease = null;
            lock (m_waiters)
            {
                if (m_waiters.Count > 0)
                    toRelease = m_waiters.Dequeue();
                else
                    ++m_currentCount;
            }
            if (toRelease != null)
                toRelease.SetResult(true);
        }
    }

   // http://blogs.msdn.com/b/pfxteam/archive/2012/02/12/10266988.aspx
    public class AsyncLock
    {
        private readonly AsyncSemaphore m_semaphore;
        private readonly Task<Releaser> m_releaser;

        public AsyncLock()
        {
            m_semaphore = new AsyncSemaphore(1);
            m_releaser = Task.FromResult(new Releaser(this));
        }

        public Task<Releaser> LockAsync()
        {
            var wait = m_semaphore.WaitAsync();
            return wait.IsCompleted ?
                m_releaser :
                wait.ContinueWith((_, state) => new Releaser((AsyncLock)state),
                    this, CancellationToken.None,
                    TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
        }

        public struct Releaser : IDisposable
        {
            private readonly AsyncLock m_toRelease;

            internal Releaser(AsyncLock toRelease) { m_toRelease = toRelease; }

            public void Dispose()
            {
                if (m_toRelease != null)
                    m_toRelease.m_semaphore.Release();
            }
        }
    }

The usage is pretty simple. This is how you use the AsyncLock

1
2
3
4
5
AsyncLock myLock = new AsyncLock();
using(var releaser = await myLock.LockAsync())
{
     // do synchronized stuff here
}

Thank You Stephen Toub! You saved the day!

C#/XAML App suspend: Bug/Feature – OnNavigatedFrom called during app Suspend

Got hit by this bug in suspension manager (C# and XAML) and wanted to share it with you in case you ever hit this scenario.

Recently, I have been coding an app with Azure backing and I got hit by a bunch of interesting scenarios that left me scratching my head, thinking, “Hmm, how do I do that again?” The following is one of those scenarios.

I was testing my app in the Suspend and Resume Scenarios. If you don’t know, Visual Studio has a very convenient way to Suspend and Resume apps while under the debugger (View->ToolBars->Debug Location) which are available when the app is running under the debugger. Anyway, during the testing of my app, I realized that although I was taking appropriate actions, my app when resumed from a suspend was not working properly. Here is the scenario in detail:

In my app, I have a page, which, when entering up in OnNavigatedTo registers a few event handlers, starts timers etc. When I am exiting this page, I want to clear  up all the event handlers/timers etc. so nothing untowards happens later if the user has navigated away from the page while the timers were still running or if an event handler gets fired later from a callback. The problem I hit was that in App Suspend, the suspension manager calls the OnNavigatedFrom event handler of the page where all my unregister logic was present. This caused a severe problem because when the user would come back to the page after suspend, all the event handlers etc would be unregistered. So the problem is that during suspend, OnNavigatedFrom is called but during Resume OnNavigatedTo is not called.

Anyways, to cut long story short, after searching a lot, I found that this issue has been asked on MSDN, is acknowledged by the product team as a known issue and considered “By Design.” The way I got around was by following the suggestion in the above link which is to say put all of your unregister code in “OnNavigatingFrom” instead of “OnNavigatedFrom”. OnNavigatingFrom is NOT called by the suspension code and is called only when you really are navigating away from the page, so that resolved my issue.

Hope it saves you a bit of time and head scratching.