han page 2 - Dave's Blog

Search
My timeline on Mastodon

WinRT Toast from PowerShell

2016 Jun 15, 3:54

I've made a PowerShell script to show system toast notifications with WinRT and PowerShell. Along the way I learned several interesting things.

First off calling WinRT from PowerShell involves a strange syntax. If you want to use a class you write [-Class-,-Namespace-,ContentType=WindowsRuntime] first to tell PowerShell about the type. For example here I create a ToastNotification object:

[void][Windows.UI.Notifications.ToastNotification,Windows.UI.Notifications,ContentType=WindowsRuntime];
$toast = New-Object Windows.UI.Notifications.ToastNotification -ArgumentList $xml;
And here I call the static method CreateToastNotifier on the ToastNotificationManager class:
[void][Windows.UI.Notifications.ToastNotificationManager,Windows.UI.Notifications,ContentType=WindowsRuntime];
$notifier = [Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier($AppUserModelId);
With this I can call WinRT methods and this is enough to show a toast but to handle the click requires a little more work.

To handle the user clicking on the toast I need to listen to the Activated event on the Toast object. However Register-ObjectEvent doesn't handle WinRT events. To work around this I created a .NET event wrapper class to turn the WinRT event into a .NET event that Register-ObjectEvent can handle. This is based on Keith Hill's blog post on calling WinRT async methods in PowerShell. With the event wrapper class I can run the following to subscribe to the event:

function WrapToastEvent {
param($target, $eventName);

Add-Type -Path (Join-Path $myPath "PoshWinRT.dll")
$wrapper = new-object "PoshWinRT.EventWrapper[Windows.UI.Notifications.ToastNotification,System.Object]";
$wrapper.Register($target, $eventName);
}

[void](Register-ObjectEvent -InputObject (WrapToastEvent $toast "Activated") -EventName FireEvent -Action {
...
});

To handle the Activated event I want to put focus back on the PowerShell window that created the toast. To do this I need to call the Win32 function SetForegroundWindow. Doing so from PowerShell is surprisingly easy. First you must tell PowerShell about the function:

Add-Type @"
using System;
using System.Runtime.InteropServices;
public class PInvoke {
[DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)]
public static extern bool SetForegroundWindow(IntPtr hwnd);
}
"@
Then to call:
[PInvoke]::SetForegroundWindow((Get-Process -id $myWindowPid).MainWindowHandle);

But figuring out the HWND to give to SetForegroundWindow isn't totally straight forward. Get-Process exposes a MainWindowHandle property but if you start a cmd.exe prompt and then run PowerShell inside of that, the PowerShell process has 0 for its MainWindowHandle property. We must follow up process parents until we find one with a MainWindowHandle:

$myWindowPid = $pid;
while ($myWindowPid -gt 0 -and (Get-Process -id $myWindowPid).MainWindowHandle -eq 0) {
$myWindowPid = (gwmi Win32_Process -filter "processid = $($myWindowPid)" | select ParentProcessId).ParentProcessId;
}
PermalinkComments.net c# powershell toast winrt

Tweet from Gregory Schier

2016 May 17, 5:11
Thanks @elmlang for the most useful error message I've ever seen
PermalinkComments

Tweet from David Risney

2016 Apr 28, 4:10
YouTube to change Content ID disputes to collect ad revenue and give to proper owner after dispute resolved http://youtubecreator.blogspot.com/2016/04/improving-content-id-for-creators.html β€¦
PermalinkComments

Retweet of stevefaulkner

2016 Feb 10, 4:57
Chrome change breaks the visual viewport http://www.quirksmode.org/blog/archives/2016/02/chrome_change_b.html β€¦ by @ppk via @powrsurg
PermalinkComments

Retweet of mayabielinski

2016 Feb 9, 9:20
Gender bias on GitHub: women's contributions accepted more often than men's - except when gender is identifiable. https://peerj.com/preprints/1733/ 
PermalinkComments

Cdb/Windbg Commands for Runtime Patching

2016 Feb 8, 1:47

You can use conditional breakpoints and debugging commands in windbg and cdb that together can amount to effectively patching a binary at runtime. This can be useful if you have symbols but you can't easily rebuild the binary. Or if the patch is small and the binary requires a great deal of time to rebuild.

Skipping code

If you want to skip a chunk of code you can set a breakpoint at the start address of the code to skip and set the breakpoint's command to change the instruction pointer register to point to the address at the end of the code to skip and go. Voila you're skipping over that code now. For example:

bp 0x6dd6879b "r @eip=0x6dd687c3 ; g"

Changing parameters

You may want to modify parameters or variables and this is simple of course. In the following example a conditional breakpoint ANDs out a bit from dwFlags. Now when we run its as if no one is passing in that flag.

bp wiwi!RelativeCrack "?? dwFlags &= 0xFDFFFFFF;g"

Slightly more difficult is to modify string values. If the new string length is the same size or smaller than the previous, you may be able to modify the string value in place. But if the string is longer or the string memory isn't writable, you'll need a new chunk of memory into which to write your new string. You can use .dvalloc to allocate some memory and ezu to write a string into the newly allocated memory. In the following example I then overwrite the register containing the parameter I want to modify:

.dvalloc 100
ezu 000002a9`d4eb0000 "mfcore.dll"
r rcx = 000002a9`d4eb0000

Calling functions

You can also use .call to actually make new calls to methods or functions. Read more about that on the Old New Thing: Stupid debugger tricks: Calling functions and methods. Again, all of this can be used in a breakpoint command to effectively patch a binary.

PermalinkCommentscdb debug technical windbg

Let's Encrypt NearlyFreeSpeech.net Setup

2016 Feb 4, 2:48

2016-Nov-5: Updated post on using Let's Encrypt with NearlyFreeSpeech.net

I use NearlyFreeSpeech.net for my webhosting for my personal website and I've just finished setting up TLS via Let's Encrypt. The process was slightly more complicated than what you'd like from Let's Encrypt. So for those interested in doing the same on NearlyFreeSpeech.net, I've taken the following notes.

The standard Let's Encrypt client requires su/sudo access which is not available on NearlyFreeSpeech.net's servers. Additionally NFSN's webserver doesn't have any Let's Encrypt plugins installed. So I used the Let's Encrypt Without Sudo client. I followed the instructions listed on the tool's page with the addition of providing the "--file-based" parameter to sign_csr.py.

One thing the script doesn't produce is the chain file. But this topic "Let's Encrypt - Quick HOWTO for NSFN" covers how to obtain that:

curl -o domain.chn https://letsencrypt.org/certs/lets-encrypt-x1-cross-signed.pem

Now that you have all the required files, on your NFSN server make the directory /home/protected/ssl and copy your files into it. This is described in the NFSN topic provide certificates to NFSN. After copying the files and setting their permissions as described in the previous link you submit an assistance request. For me it was only 15 minutes later that everything was setup.

After enabling HTTPS I wanted to have all HTTP requests redirect to HTTPS. The normal Apache documentation on how to do this doesn't work on NFSN servers. Instead the NFSN FAQ describes it in "redirect http to https and HSTS". You use the X-Forwarded-Proto instead of the HTTPS variable because of how NFSN's virtual hosting is setup.

RewriteEngine on
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule ^.*$ https://%{SERVER_NAME}%{REQUEST_URI} [L,R=301]

Turning on HSTS is as simple as adding the HSTS HTTP header. However, the description in the above link didn't work because my site's NFSN realm isn't on the latest Apache yet. Instead I added the following to my .htaccess. After I'm comfortable with everything working well for a few days I'll start turning up the max-age to the recommended minimum value of 180 days.

Header set Strict-Transport-Security "max-age=3600;" 

Finally, to turn on CSP I started up Fiddler with my CSP Fiddler extension. It allows me to determine the most restrictive CSP rules I could apply and still have all resources on my page load. From there I found and removed inline script and some content loaded via http and otherwise continued tweaking my site and CSP rules.

After I was done I checked out my site on SSL Lab's SSL Test to see what I might have done wrong or needed improving. The first time I went through these steps I hadn't included the chain file which the SSL Test told me about. I was able to add that file to the same files I had already previously generated from the Let's Encrypt client and do another NFSN assistance request and 15 minutes later the SSL Test had upgraded me from 'B' to 'A'.

PermalinkCommentscertificate csp hsts https lets-encrypt nearlyfreespeech.net

Tweet from David_Risney

2016 Jan 31, 11:27
Combat bad drones? NL police have attack eagles. Better than JP police drones w big nets? http://spectrum.ieee.org/automaton/robotics/aerial-robots/dutch-police-training-eagles-to-take-down-drones β€¦
PermalinkComments

Retweet of mathias

2016 Jan 27, 10:29
Take any Facebook/Instagram photo URL.πŸ‘‰ append `.txt` β†’ ASCII artπŸ‘‰ append `.html` β†’ colored ASCII artE.g. https://scontent-ams3-1.cdninstagram.com/t51.2885-15/e35/11906246_1700002456899911_1391970345_n.jpg.html β€¦
PermalinkComments

Unicode Clock

2016 Jan 24, 2:00

I've made a Unicode Clock in JavaScript.

Unicode has code points for all 30 minute increments of clock faces. This is a simple project to display the one closest to the current time written in JavaScript.

Because the code points are all above 0xFFFF, I make use of some ES6 additions. I use the \u{XXXXXX} style escape sequence since the old style JavaScript escape sequence \uXXXX only supports code points up to 0xFFFF. I also use the method String.codePointAt rather than String.charCodeAt because the code points larger than 0xFFFF are represented in JavaScript strings using surrogate pairs and charCodeAt gives the surrogate value rather than codePointAt which gives the code point represented by the pair of surrogates.

"πŸ•›".codePointAt(0)
128347
"πŸ•›".charCodeAt(0)
55357

πŸ•πŸ•‘πŸ•’πŸ•“πŸ•”πŸ••πŸ•–πŸ•—πŸ•˜πŸ•™πŸ•šπŸ•›πŸ•œπŸ•πŸ•žπŸ•ŸπŸ• πŸ•‘πŸ•’πŸ•£πŸ•€πŸ•₯πŸ•¦πŸ•§

The ordering of the code points does not make it simple to do this. I initially guessed the first code point in the range would be 12:00 followed by 12:30, 1:00 and so on. But actually 1:00 is first followed by all the on the hour times then all the half hour times.

PermalinkCommentsjavascript Unicode

Retweet of GundersenMarius

2016 Jan 19, 10:49
I love this diagram in the WHATWG spec. It explains it much better than words could pic.twitter.com/RflCT5JIGu
PermalinkComments

Retweet of FakeUnicode

2016 Jan 10, 10:34
Support! Rather than "Combining" though they would be "Combing." https://twitter.com/martineno/status/686639564207841281 β€¦ [@martineno]
PermalinkComments

Retweet of anildash

2016 Jan 3, 9:59
Oh! @jsnell is way ahead of me: https://sixcolors.com/post/2015/12/the-best-christmas-gift-in/ β€¦ Programming BB-8 with a kid-friendly app! Thanks to @anoopr for the link.
PermalinkComments

Retweet of thegrugq

2015 Dec 21, 5:26
Succinct explanation of the Dual EC travesty as realized in the Juniper debacle.https://storify.com/thegrugq/conversation-with-stewartbaker-ethan-heilman-matth β€¦ pic.twitter.com/tR1dDuJm8u
PermalinkComments

Tweet from David_Risney

2015 Nov 19, 11:04
Finished Breaking Bad finale last night. As last person to do so, feel free to now discuss spoilers. Thank you for your patience.
PermalinkComments

Tweet from David_Risney

2015 Nov 3, 8:49
And how do I express that I wouldn't care if they changed ❀ into πŸ’©? http://gizmodo.com/how-to-replace-twitters-dumb-heart-with-the-emoji-of-yo-1740302661 β€¦ https://twitter.com/BringStarsBack/status/661595143921864705 β€¦
PermalinkComments

Retweet of stevesi

2015 Oct 25, 8:38
πŸ™ https://twitter.com/HuzefaMotiwala/status/658495033541283840 β€¦
PermalinkComments

Tweet from David_Risney

2015 Oct 23, 3:55
Crowd sourced morality on automated cars handling collisions: http://www.technologyreview.com/view/542626/why-self-driving-cars-must-be-programmed-to-kill/ β€¦ 3 laws is thin API over Amzn Mechanical Turk service.
PermalinkComments

Tweet from David_Risney

2015 Oct 7, 2:17
On whistleblower Edward Scissorhands: "to cast him out… simply because he has scissors for hands… that's strange" http://kottke.org/15/09/whistleblower-edward-scissorhands β€¦
PermalinkComments

Retweet of robleathern

2015 Oct 3, 7:44
Crunching @nytimes ad analysis: It costs consumers 16.6x more in data costs than top 50 news sites make on them in mobile ad$ @BenedictEvans
PermalinkComments
Older EntriesNewer Entries Creative Commons License Some rights reserved.