<![CDATA[Aaron Holmes - My Thoughts]]>http://aholmes.azurewebsites.net/Ghost 0.5Mon, 31 Aug 2020 22:41:02 GMT60<![CDATA[Displaying response headers and pretty JSON with cURL]]>The Problem

I tend toward using cURL when testing HTTP services, but I had a difficult time parsing the result when these services spit back unformatted JSON responses. To make my life a little easier, I set out to find a way to bend cURL to my will.

The Solution

Let's get straight to it. To make cURL display both response headers and formatted JSON, we need to make cURL send the headers to STDERR, so we can then send STDOUT to a formatting utility.

We can accomplish this as so.

curl -s -D "/dev/stderr" -X POST 'http://example.org/some/url' --data-binary @some-file | python -m json.tool  

This will show a nicely formatted response like this.

HTTP/1.1 500 Internal Server Error  
Content-Type: application/json; charset=utf-8  
X-Powered-By: ASP.NET  
Date: Wed, 18 Sep 2019 22:39:24 GMT  
Content-Length: 114

{
    "Status": 3,
    "Timestamp": "2019-09-18T22:39:24.1659165Z",
    "Error": {
        "Code": 1,
        "Message": "An error has occurred."
    }
}
What's Going On Here?

Let's break this down a bit.

After some initial research into how to send the HTTP headers to STDERR, I found this article that demonstrated the use of -D "/dev/stderr".

Breaking the command down:

  • -s will silence the statistics output of cURL
  • -D "/dev/stderr" will send the HTTP headers to STDERR
  • python -m json.tool receives STDOUT, which is the JSON response of my service
  • The other options are specific to my service request, and are not relevant to the formatting

Note: you can also pipe the cURL output to a utility like jq, I just happen to use python -m json.tool.

A Step Further

These commands and then be turned into Bash aliases and functions.

I have this in my ~/.bashrc.

alias curl-json='curl -s -D "/dev/stderr"'  
curl-json-format()  
{
        curl-json "$@" | python -m json.tool
}

Now I can use this command!

curl-json-format -X POST 'http://example.org/some/url' --data-binary @some-file | python -m json.tool  
]]>
http://aholmes.azurewebsites.net/displaying-response-headers-and-pretty-json-with-curl/32996482-d2a7-4d32-8864-e9b4a74e7b63Thu, 19 Sep 2019 19:12:43 GMT
<![CDATA[The Behavior of C# Nested Static Classes]]>While working on a code review, I found a nested static class that I needed to verify the validity of. I had three questions:

  • Does the CLR create new instances when the containing class is instantiated?
  • Do the static class members retain the same values across all instances of the containing class?
  • Is the nested class truly static?

As you'll read below, it turns out the nesting of a static class is a bit of a red herring. If you write C# regularly, you already know how this works.

Check the Documentation

Like any good dev, I checked the documentation first.
The Microsoft C# docs for Static Classes and Static Class Members states the following.

As is the case with all class types, the type information for a static class is loaded by the .NET Framework common language runtime (CLR) when the program that references the class is loaded. The program cannot specify exactly when the class is loaded. However, it is guaranteed to be loaded and to have its fields initialized and its static constructor called before the class is referenced for the first time in your program. A static constructor is only called one time, and a static class remains in memory for the lifetime of the application domain in which your program resides.

This is pretty clear on static class behavior, but I still wasn't sure whether there were additional nuances regarding nested static classes. We can find more information in the documentation regarding Nested Types, however, this documentation is missing any information about static classes.


Solving the Unknown

With my questions unanswered, and a desire to be certain in my code review, it was time to create a test case. Here's the code I wrote.

By the way, I typically use RoslynPad for one-off tests like this.

// Foo is the containing/outer class that is instantiated
public class Foo  
{
    // OuterI is used to retrieve the value of the integer
    // parameter for the constructor
    public static int OuterI;

    public Foo(int i)
    {
        OuterI = i;
    }

    // BarI returns the value of the nested static
    // class's value, which points to the containing
    // class's OuterI property
    public int BarI => Bar.InnerI;

    // This is the nested static class being tested
    private static class Bar
    {
        // This is used to retrieve the containing class's
        // value of the OuterI property, which is set by
        // an instance of Foo. Keep in mind, this is a value type,
        // not a reference type, and this is a field,
        // not a property.
        public static int InnerI = Foo.OuterI;
    }
}

I then tested two scenarios.

The first scenario observes what happens when 1+n Foos are instantiated, followed by printing the value of each instance's BarI property.

var f1 = new Foo(1);  
var f2 = new Foo(2);  
var f3 = new Foo(3);  
var f4 = new Foo(4);

Console.WriteLine(f1.BarI);  
Console.WriteLine(f2.BarI);  
Console.WriteLine(f3.BarI);  
Console.WriteLine(f4.BarI);  

The second scenario observes what happens when n+1 Foos are instantiated, then immediately followed by printing the value of the instances BarI property.

Console.WriteLine(new Foo(1).BarI);  
Console.WriteLine(new Foo(2).BarI);  
Console.WriteLine(new Foo(3).BarI);  
Console.WriteLine(new Foo(4).BarI);  

A Challenger Appears!

Before reading further, I'd like to offer you a challenge; predict what happens in both scenario 1 and 2.


The Behavior, Discovered

Figured it out?

The output of the first scenario is:

4

4

4

4

The output of the second scenario is:

1

1

1

1

While this may be surprising (the first scenario caught me off guard), the behavior is explained in the Static Classes and Static Class Members documentation. Indeed, this line applies to all static classes.

A static constructor is only called one time, and a static class remains in memory for the lifetime of the application domain in which your program resides.

Why Does this Occur?

So with that in mind, what's actually happening here? Let's make a couple changes to observe the application execution in both scenarios.

Add a static constructor to Bar, and insert a new Console.Writeline statement.

private static class Bar  
{
    static Bar()
    {
        Console.WriteLine("initialized");
    }

    public static int InnerI = Foo.OuterI;
}

Then, for both scenario 1 and two, insert new Console.WriteLine statements between each operation.

Scenario 1

Console.WriteLine("new 1");  
var f1 = new Foo(1);  
Console.WriteLine("new 2");  
var f2 = new Foo(2);  
Console.WriteLine("new 3");  
var f3 = new Foo(3);  
Console.WriteLine("new 4");  
var f4 = new Foo(4);

Console.WriteLine("bar 1");  
Console.WriteLine(f1.BarI);  
Console.WriteLine("bar 2");  
Console.WriteLine(f2.BarI);  
Console.WriteLine("bar 3");  
Console.WriteLine(f3.BarI);  
Console.WriteLine("bar 4");  
Console.WriteLine(f4.BarI);  

Scenario 2

Console.WriteLine("bar 1");  
Console.WriteLine(new Foo(1).BarI);  
Console.WriteLine("bar 2");  
Console.WriteLine(new Foo(2).BarI);  
Console.WriteLine("bar 3");  
Console.WriteLine(new Foo(3).BarI);  
Console.WriteLine("bar 4");  
Console.WriteLine(new Foo(4).BarI);  

Now, if we execute these scenarios, the application execution flow becomes clear. The reason for the observed behavior is as stated in the documentation. The static class is set up before it is accessed, and it is initialized only one time.

Scenario 1 outputs the following.

new 1

new 2

new 3

new 4

bar 1

initialized (BarI is accessed for the first time, and the static class is initialized)

4

bar 2

4

bar 3

4

bar 4

4

Scenario 2 outputs the following.

bar 1

initialized (BarI is called for the first time, and the static class is initialized)

1

bar 2

1

bar 3

1

bar 4

1

Now I am curious what the non-gaurantee of when the static class is initialized means in runtimes other than the CLR.

]]>
http://aholmes.azurewebsites.net/the-behavior-of-c-nested-static-classes/f89db787-7c02-4c96-86c7-c90ebf58fe9dThu, 26 Jul 2018 22:58:50 GMT
<![CDATA[Transparent Video in all Browsers from Cross-Domain Sources]]>A brief history of time cross-domain transparent video

Transparent video is not a terribly new concept in web development, however, because browsers do not support transparency in videos, accomplishing this requires a unique solution that involves a canvas element and a video with a separate alpha channel.

This solution does actually work very well to work around the limitation. There is a gotcha to be aware of when using video sources from a different origin, however; drawing to the canvas with data from a different origin "taints" the canvas. Once a canvas has been tainted, you are no longer able to extract data from the canvas. This breaks the workaround for transparent video, which relies on extracting the values of the alpha channel stored in a canvas. Thankfully, this can be worked around in most browsers by configuring CORS correctly and setting the crossorigin attribute on the source video element.

Where this fails

Unfortunately, like many things in web development, the latest versions of Safari 9.0.2, Internet Explorer 11, and Edge 25 do not correctly honor the CORS configuration when cross-domain data is drawn to a canvas. This means there was no way to achieve transparent video in these three browsers unless the source video comes from the same origin.

After a lot of research, I stumbled across this answer regarding drawing cross-domain images to a canvas. The missing piece for me was the existence of the URL.createObjectUrl() method.

The solution in its entirety

Please reference How to use transparency info from a video on a website for a more descriptive writeup on the basics of video transparency in browsers. The primary piece I have left out here is that you will need a video with the alpha channel stored in a separate position.

First, the HTML. The page needs:

  • A single video element that does not display (because the video will be drawn to the canvas)
  • A canvas whose width and height match the video, which is used to draw the video data to
  • A canvas whose width matches the video, and whose height is twice the video height

The main JavaScript file execution is deferred in order to run after the page has finished loading.

<head>  
    <script src="script/main.js" defer></script>
</head>  
<body>  
    <video style="display:none" autoplay>
        <source src="video.mp4" type='video/mp4' />
    </video>
    <canvas width="1920" height="1080" id="output"></canvas>
    <canvas style="display:none;" width="1920" height="2160" id="buffer"></canvas>
</body>  

The JavaScript will reference all three HTML elements, references to the canvas' 2D contexts and video width and height are saved, and the buffer and output canvas widths and heights are set.

var outputCanvas = document.getElementById('output'),  
    output       = outputCanvas.getContext('2d'),
    bufferCanvas = document.getElementById('buffer'),
    buffer       = bufferCanvas.getContext('2d');

outputCanvas.width  = Math.floor(outputCanvas.clientWidth );  
outputCanvas.height = Math.floor(outputCanvas.clientHeight);  
bufferCanvas.width  = Math.floor(bufferCanvas.clientWidth );  
bufferCanvas.height = Math.floor(bufferCanvas.clientHeight);

var video  = document.getElementById('video');  
var width  = outputCanvas.width;  
var height = outputCanvas.height;  

In order to avoid excessive CPU usage, and to continually draw video frames to the canvas, a recursive method, determineDraw() is used in conjunction with requestAnimationFrame().

var lastDrawTime = -1;  
function determineDraw() =>  
{
    // If the video has finished, there is no need to execute again, and this ends the script.
    if (vid.paused || vid.ended)
    {
        URL.revokeObjectURL(url);
        return;
    }

    // If the current playhead of the video has not changed since the last time this method executed,
    // there is no need to draw the same frame again.
    // lastDrawTime's initial value is -1 because video.currentTime will never be -1.
    if (video.currentTime !== lastDrawTime)
    {
        // If the video playhead has changed, the current frame is drawn (explained below).
        draw();
        // Store the current playhead position.
        lastDrawTime = video.currentTime;
    }

    // Recurse.
    requestAnimationFrame(determineDraw);
};

To kick things off

var xhr = new XMLHttpRequest();  
xhr.onload = function()  
{
    var url = URL.createObjectURL(this.response);
    var vid = document.createElement('video');
    (<any>vid).crossorigin = 'anonymous';

    vid.addEventListener('loadeddata', () =>
    {
        // now that our in-memory video element has loaded, we can remove the original video element.
        (video.remove && video.remove()) || ((<any>video).removeNode && (<any>video).removeNode());

        // Once the video starts playing, recursion begins, and we draw to the canvas roughly every 16ms.
        video.addEventListener('play', determineDraw, false);

        // start playback
        vid.play();
    });

    // setting the in-memory video source URL to the in-memory object bypasses the tainted canvas cross-origin check.
    vid.src = url;
};
function draw() =>  
{
    buffer.drawImage(video, 0, 0);

    // this can be done without alphaData, except in Firefox which doesn't like it when image is bigger than the canvas
    var image = buffer.getImageData(0, 0, width, height),
        imageData = image.data,
        alphaData = buffer.getImageData(0, height, width, height).data;

    // Grabs every 4th data point (the alpha value) and overwrites the same data point on the RGB channel.
    for (var i = 3, len = imageData.length; i < len; i = i + 4)
    {
        imageData[i] = alphaData[i - 1];
    }

    output.putImageData(image, 0, 0, 0, 0, width, height);
}
An admission

I started writing this post almost a year ago now, and I never got back around to breaking the code down into more describable parts.

I also, unfortunately, am unable to include another significant portion of the code that allows these same concepts to work in some older browers, or those with iffy CORS support. I can give a hint, though: it uses XMLHttpRequest to get the video (instead of a video tag) and draws the request result to the canvas.

]]>
http://aholmes.azurewebsites.net/transparent-video-in-all-browsers-from-cross-domain-sources/7df0fd7b-35e4-4981-a7b8-00f3dae4248dFri, 06 Jan 2017 21:57:30 GMT
<![CDATA[Using Git with the .git directory outside the Git repository directory]]>I have a particular use case where I want to use Git on top of another version control system. The only problem I ran into is that the other VCS wanted to track the .git directory that Git creates for its own tracking purposes.

Rather than mess about with making the existing VCS ignore this directory, I set out to make Git store the .git directory somewhere else. Turns out it's pretty easy, but Git is fickle, and you have to set a couple environment variables rather than simply using --git-dir or --work-tree.

The bash script below creates a function named git in your environment that shells out to the real Git binary. It will also attempt to create a new directory in your home directory (~/gitdirs) to hold these new .git directories. This script also works in Git Bash!

# Store a reference to the Git binary
GIT_BIN=`which git`

# The function that runs when you type `git`
function git  
{
    # The location .git directories are stored in
    gitdirroot=~/gitdirs
    # Create that directory if it does not exist
    if [ ! -d $gitdirroot ]; then
        mkdir -p $gitdirroot
    fi

    # Use the current working directory as the .git directory name
    gitdirname="$gitdirroot/`pwd | tr "/" '_'`"

    # Set the two environment variables Git needs to use the new .git directory
    export GIT_DIR=$gitdirname
    export GIT_WORK_TREE=.

    # Execute the Git command
    $GIT_BIN $@
}
]]>
http://aholmes.azurewebsites.net/using-git-with-git-directory-outside-the-git-repository/3b67d582-0ad0-4611-a023-ba466089720aFri, 19 Aug 2016 15:06:21 GMT
<![CDATA[Simple Way to Prevent Websites Jumping from Scrollbars]]>A common occurance I see on websites, and a frequent question I see as well regards websites "jumping" when more content loads onto the page and a scrollbar becomes visible in the browser. The solution to this is remarkably easy, but I don't think I've seen many developers mention it.

The trick is simply to make the scrollbar present at all times.

If your site creates a vertical scrollbar, use this CSS.

.body {
    overflow-y: scroll;
}

If horizontal, use this CSS.

.body {
    overflow-x: scroll;
}

And lastly, if your site creates scrollbars in both directions, you can just use overflow.

.body {
    overflow: scroll;
}

Just be aware that overflow-x and overflow-y may not be supported in your target browsers!

https://developer.mozilla.org/en-US/docs/Web/CSS/overflow-y

https://developer.mozilla.org/en-US/docs/Web/CSS/overflow-x

Update Jan 10th, 2019

It turns out Mac OS and iOS may hide scrollbars regardless of the overflow: scroll rule. Check out this fix to override this behavior.

]]>
http://aholmes.azurewebsites.net/simple-way-to-prevent-website-jumping-from-scrollbars/38a99f09-4b0d-4f4f-bfd7-d2ac73df0713Fri, 01 Apr 2016 00:16:00 GMT
<![CDATA[Two short ack filetype definitions for TypeScript.]]>I search my TypeScript code a lot and finally got tired of using awk, grep, and friends to filter out irrelevant files. Here's a definition for .ts files and .d.ts files to help you out.

--type-set=ts:ext:ts
--type-set=tsdef:match:/.+\.d\.ts/

Put this in your .ackrc file (or use those switches at the command line).

Now you can search just your .ts files without also searching compiled .js and .d.ts files with ack --ts --notsdef mySearch.

More information in the ack manpage.

]]>
http://aholmes.azurewebsites.net/two-short-ack-filetype-definitions-for-typescript/b4b17924-1de6-4020-b14a-59b978735766Tue, 09 Feb 2016 23:58:55 GMT
<![CDATA[Simple programming patterns and conventions]]>I thought it might be helpful to some developers to see some simple patterns and conventions in a variety of languages. Many of us know about more complex and abstract patterns, like the Abstract Factory Pattern or the Flyweight Pattern, but smaller patterns are rarely discussed outside of answers to questions.

These are some patterns and conventions that I tend to use in any code I write. They range from one-liners to a couple of methods, and are mostly understandable at first glance. I've avoided going too much into why someone might choose any given pattern, and leave it as an exercise to the reader to determine where these patterns might be useful for them.

As of now, I've only listed a single convention because I use it in a number of the patterns below. I'm sure the convention is controversial, so if you don't agree with it, please keep in mind that the meat of this post is in the patterns.

I will add other conventions and patterns in the future, and may add others from comments here or on reddit.

A final note on the code below. I did not enclose all code in the required class or method blocks in order to keep the focus on the patterns alone. Additionally, I've specified the language that each example is written for; many of them work just fine in other languages. If you have any questions on why a pattern doesn't make sense, or is not executing, don't hesitate to ask.

Enjoy!


Conventions


Branching flow-control statements

For branching flow-control statements, do not use braces and keep the code on a single line.

Return statements

Language: C#, most C-like languages with some contingencies

if (MyBoolean) return null;  

Continuing in a loop

Language: C#, most C-like languages

for(var i = 0; i < 5; i++)  
{
    if (i == 4) continue;
}

Breaking out of a loop

Language: C#, most C-like languages

var i = 0;  
while(true)  
{
    if (i == 4) break;
    i++;
}

Patterns


Prevent a method from executing more than once

This is an easy way to prevent a method from executing multiple times. By checking a condition at the beginning, and then ensuring that condition is true immediately after, any subsequent calls will return immediately.

Language: C#, Java with some contingencies

static boolean executed;  
static void MyFoo()  
{
    if (executed) return null; // simply check the condition before any other code
    executed = true; // then assign your variable
    /* ... */
}

Using a switch statement as a compact alternative to if statements

Language: JavaScript

switch(true)  
{
    case myFoo === myBar: FooBar(); break; // while the next statement is false if this is true, the additional check is avoided with the `break` statement
    case myFoo === myBaz: FooBaz(); break;
    default: DefaultMethod();
}

Execute multiple using blocks without braces

Like any other block statement, in C#, using can be used without braces as well. This is especially useful to avoid excessive visual nesting.

Language: C#

using(var myDisposableObject = new Disposable())  
using(var myFoo = new Foo())  
using(var myBar = new Bar())  
{
    // Each of myDisposableObject, myFoo, and mBar are accessible here
    /* ... */
}

Avoid unnecessary awaits by passing the Task around

At least for me, using async/await in C# seemed to require making your methods that called asynchronous methods async themselves, and making those methods await. Instead, if your method does not need to await, you can make it return a Task and then pass the task returned from an asynchronous method wherever you need it. This is especially helpful if you need to use out or ref in a method that calls an asynchronous method.

Language: C#

static void Main()  
{
    MySyncMethod().Wait();
}

static async Task MyAsyncMethod()  
{
    Console.WriteLine("Waiting 1 second @ " + DateTime.UtcNow);
    await Task.Delay(1000); // here we await the result so we can execute code immediately after, usually to operate on the result of the Task
    Console.WriteLine("Finished waiting @ " + DateTime.UtcNow);
}

static Task MySyncMethod()  
{
    Console.WriteLine("Calling asynchronous method");
    return MyAsyncMethod(); // MySyncMethod doesn't need to execute code immediately after, so it is synchronous and only returns the Task
}

Prevent a method call with a specific type during compile time

I happened across this solution when clicking around Stack Overflow. Apologies for not crediting the solution; I don't recall where I found it.

You may have a method that accepts an abstract class, an interface, or some form of "base" class, but you want to restrict a certain subclass of that type from being used (perhaps the subclass is obsolete). Rather than checking the type during runtime and throwing an exception, you use this pattern to gain a compile time check in addition to a runtime check. This example uses constructors, but it works for methods as well.

By default, the Obsolete annotation will display a warning. You can configure msbuild or Visual Studio to treat warnings as errors, which will prevent the following code from compiling.

Language: C#

public interface IBar {}

public class Bar: IBar {}  
public class Baz: IBar {}

public class Foo  
{
    public Foo(IBar bar)
    {
    }

    [Obsolete("Foo cannot be instantiated with a Baz.")]
    public Foo(Baz baz) // overload the IBar constructor with the type that is disallowed
    {
        throw new NotImplementedException();
    }
}

public class Program  
{
    public static void Main()
    {
        new Foo(new Bar());
        new Foo(new Baz()); // this generates a warning during compile time, and an exception during runtime
    }
}

Define and declare the type of arrays and objects in TypeScript

I think this is a problem and solution unique to TypeScript. You need to define a variable as an array or an object, but either you've disallowed implicity any, or you need to declare the type of the variable. There are, of course, other ways to accomplish this, but I believe this is the most compact way.

Language: TypeScript

var myFoos = <Foo[]>[]; // here we simply cast the array to the specific type needed

var myFood = <Foo>{}; // the same pattern is used for objects as well  

Execute multiple async tasks in parallel

You may need to execute a series of asynchronous tasks in parallel, and then await their result. There are a couple different ways I accomplish this, depending on how the tasks are created. You can use the pattern Avoid unnecessary awaits by passing the Task around here as well.

Language: C#

static async Task MyFirstMethod()  
{
    var tasks = new List<Task>(); // here we use a List<Task> in order to optionally add tasks to await

    tasks.Add(Task.Delay(1000));

    if (aCondition) // if aCondition is true, two tasks are added to the list
    {
        tasks.Add(Task.Delay(1000));
        tasks.Add(Task.Delay(1000));
    }

    Console.WriteLine(DateTime.UtcNow);
    await Task.WhenAll(tasks); // this method will complete after 1 second, when all three tasks are completed
    Console.WriteLine(DateTime.UtcNow);
}

static async Task MySecondMethod()  
{
    var tasks = new[] // here an array is initialized because there is no need to conditionally add more tasks
    {
        Task.Delay(1000),
        Task.Delay(1000),
        Task.Delay(1000)
    };

    Console.WriteLine(DateTime.UtcNow);
    await Task.WhenAll(tasks);
    Console.WriteLine(DateTime.UtcNow);
}
]]>
http://aholmes.azurewebsites.net/simple-programming-patterns-and-conventions/2ff19dba-cc90-412c-97b7-66301faaece3Thu, 24 Dec 2015 03:54:10 GMT
<![CDATA[Printing function body in Chrome's console]]>Chrome used to, by default, print a function body in the console if you entered a function name into it, or if you called console.log() with a function name.

What happens now is that Chrome will print a link to the function which, when clicked, will navigate your source viewer to that function.

For example, executing (or logging) BLT.TypeScript.Text.truncate will print function truncate(input, length, ellipsize).

For me, navigating away from my source viewer when I want a reference to a function is distracting. I am not aware of a way to re-enable the old behavior, but an alternative is to now call toString() on the function. Unfortunately, it does not appear that whitespace is preserved.

BLT.TypeScript.Text.truncate.toString()

function truncate(input, length, ellipsize) {  
    if (ellipsize === void 0) { ellipsize = true; }
    if (input.length <= length) return input;
    var whitespace = new RegExp('\\s');
    var truncatedStr = input.substr(0, length);
    if (!whitespace.test(truncatedStr)) return truncatedStr + (ellipsize ? ' ...' : '');
    while (length > 0 && !whitespace.test(input.substr(--length, 1))) { }
    return input.substr(0, length) + (ellipsize ? ' ...' : '');
}
]]>
http://aholmes.azurewebsites.net/printing-function-body-in-chromes-console/78c2a404-a374-481f-8204-1a529bba42c1Wed, 01 Jul 2015 19:22:55 GMT
<![CDATA[Reading an HTTP Request Response Body from Exceptions]]>Every so often I need to read the response body of a failed HTTP request while debugging a .NET application in Visual Studio. It's not immediately obvious how you can do this, so here's a quick way to do so. You can use these same methods when working directly with an HTTP response object or an HTTP request object as well.

1) Open the Immediate Window under Debug > Windows > Immediate, or by pressing CTRL + ALT + I.

2) You'll need to cast your exception to a WebException. Try either of these, depending on what kind of exception you're working with.
e as System.Net.WebException

e.InnerException as System.Net.WebException

Still no luck? Look in the Locals window and see if you can find the correct exception that has the HTTP response object in it. You'll know you have the right one when the Immediate Window prints something other than null. For example:

{"The remote server returned an error: (404) Not Found."}
    base: {"The remote server returned an error: (404) Not Found."}
    Response: {System.Net.HttpWebResponse}
    Status: ProtocolError

3) Now you can get the response stream from the WebException.
var s=(e.InnerException as System.Net.WebException).Response.GetResponseStream();

{System.Net.SyncMemoryStream}
     [System.Net.SyncMemoryStream]: {System.Net.SyncMemoryStream}
    base: {System.Net.SyncMemoryStream}
    CanRead: true
    CanSeek: true
    CanTimeout: true
    CanWrite: true
    Length: 78
    Position: 0
    ReadTimeout: -1
    WriteTimeout: -1

4) Create a new StreamReader object just for ease of use.
var sr = new System.IO.StreamReader(s);

{System.IO.StreamReader}
    base: {System.IO.StreamReader}
    BaseStream: {System.Net.SyncMemoryStream}
    CurrentEncoding: {System.Text.UTF8Encoding}
    EndOfStream: false

5) Finally, read the stream contents. This is the HTTP response body.
sr.ReadToEnd();

"{\"Message\":\"The index 'products' for service 'search' was not found.\"}"
]]>
http://aholmes.azurewebsites.net/reading-an-http-request-response-body-from-exceptions/e6f8c2fe-e70c-40b9-b9e4-dbd5d7e770bfThu, 16 Apr 2015 22:28:05 GMT
<![CDATA[Circuit Scribe art project step #3]]>I finally took the time to start maping out where I'll need to draw my Circuit Scribe ink lines. I also drew where I want to place LEDs and calculated resistor values. I may need to revisit some of this to use less resistors to lower the load on the circuit, but I'm not sure. I'll have to draw out a couple circuits and test.

The LEDs I have need a forward voltage of 3.2 and a max forward current of 20mA. With one LED, I've found that 3 80.6Ω resistors in series gives an appropriate brightness without hitting the max current rating. I'm hoping that the ~130Ω resistance I've placed in a few places will allow a similar brightness for two LEDs in series. Some individual LEDs are placed on the ~130Ω resistance rail as well, and for those I added two additional 80.6Ω resistors in series bringing the total resistance up to ~290Ω. I may have to drop my source voltage to 5V to avoid burning out some LEDs, or add more resistors.

Some calculations follow.

MeasurementValue
Source voltage9
LED forward voltage3.2
LED max forward current20mA
Single resistor80.6Ω

For single LEDs I calculated R = ((9 - 3.2) / 0.02) = 290.
I need R / 80.6 = 3.6 resistors. I rounded down to 3. I didn't experience any excessive heat with this configuration.

For two LEDs in series I used four 80.6Ω resistors; two in series, and those two in parallel with two more 80.6Ω resistors also in parallel. The total resistance is R = 1 / (1/80 + 1/80 + 1/(80 + 80)) = 32.
The power, then, is calculated as I = (9 - 3.2 - 3.2) / 32 = 8.1mA.

For driving a single LED off the 32Ω rail, we need to add additional resistors in series to limit the maximum forward current into the LED.

We already know that the resistance required for a single LED is 290Ω. From here, we can subtract 32Ω to determine how many more ohms of resistance we need to add. 290 - 32 = 258. We can then figure out how many 80.6Ω resistors are needed just with division. 258 / 80.6 = 3.2. That's 3 resistors.

Oops! I only drew two additional resistors, which gives us a forward current of about 30mA - about 10mA too many. I'll have to revisit that circuit, or simply use a third resistor. That would give this rail about 274Ω of resistance.

Screenshot of final frame from video

Next up, I should have the corrected circuits drawn out and I'll actually be able to draw them on my canvas!

]]>
http://aholmes.azurewebsites.net/circuit-scribe-art-project-step-3/e5a60dd2-b1b2-4e4a-8e2e-16df896a4b86Sun, 25 Jan 2015 05:47:37 GMT
<![CDATA[Circuit Scribe art project step #2]]>I put another hour into this and started sketching out the buildings surrounding the Space Needle. The landscape is starting to take shape, but it lacks any depth. Next I need to figure out where I'm going to route my circuit, and then I'll start drawing some of the details in the buildings.

Also I really need to get my camera to pick up the pencil marks as I'm working. It looks like I'm just zipping all over a black board and doing nothing.

]]>
http://aholmes.azurewebsites.net/circuit-scribe-art-project-step-2/b1184e21-5178-459b-92d7-19f48d71777fTue, 20 Jan 2015 04:37:04 GMT
<![CDATA[Circuit Scribe art project step #1]]>I finally started my "cityscape" project with Circuit Scribe! Here's a quick video showing the first pencil sketches. I will be posting these as I go along under the Circuit Scribe - Seattle tag, so stay tuned for more!

]]>
http://aholmes.azurewebsites.net/circuit-scribe-art-project-step-1/8f2e42af-2a43-4ad1-a9e7-8cfe1da14a4bMon, 19 Jan 2015 11:53:36 GMT
<![CDATA[Writing AngularJS directives as TypeScript classes]]>Introduction

TL;DR? Read the implementation details here.

Note: This post was written for AngularJS 1.x. Angular 2+ has different conventions that make parts of this post obsolete.

TypeScript is a fantastic language that extends JavaScript by providing static typing syntax. Writing TypeScript to utilize AngularJS can be clunky at times, and one pain point for me was in writing directives.

AngularJS expects to be feed a factory function that returns an object that defines parameters and functionality for your directive.

In JavaScript, that looks like this.

module.directive('myDirective', function()  
{
    return {
        scope: {},
        template: '<div>{{name}}</div>',
        link: function (scope)
        {
            scope.name = 'Aaron';
        }
    };
}

A direct translation of this to TypeScript looks like this. By the way, I am using the angular.d.ts type definition file from definitelytyped.org.

module MyModule.Directives  
{
    export interface IMyScope extends ng.IScope
    {
        name: string;
    }

    export function MyDirective(): ng.IDirective
    {
        return {
            template: '<div>{{name}}</div>',
            scope : {},
            link  : (scope: IMyScope) =>
            {
                scope.name = 'Aaron';
            }
        };
    }
}

The registration is then handled as follows.

module.directive('projects', MyModule.Directives.MyDirective.Factory());

Not too different, really, but I feel this doesn't encapsulate a directive very well, nor does it really take advantage of the utility of TypeScript.

Why this is problematic

If MyDirective is a base class, I would not be able to extend MyDirective with a subclass. Granted, because TypeScript is a superset of JavaScript, it would be possible to extend this function through prototypal inheritance, or one of a plethora of such approaches. This, however, has the disadvantage of muddying your TypeScript with syntax and code that doesn't necessarily need to be there.

A real-world example without a class

To bring my examples into the real world, here's a previous iteration of a directive I wrote for my personal site. This uses the export function syntax.

module AaronholmesNet.Directives  
{
    interface IProject extends Resources.IProject
    {
        title: string;
        active: boolean;
    }

    interface IProjectsScope extends ng.IScope
    {
        [key: string] : any;

        projects: Interfaces.IListInterface<IProject>
    }

    // return my repositories first, and forks second.
    // from there, sort by last change time.
    function ProjectSort(a: Resources.IProject, b: Resources.IProject): number
    {

        if (a.fork === false && b.fork === true) return -1;

        if (a.fork === true && b.fork === false) return 1;

        if (a.updated_at > b.updated_at) return -1;

        if (a.updated_at < b.updated_at) return 1;

        return 0;
    }

    export function ProjectsDirective(ProjectResource: Resources.IProjectResource, $location: ng.ILocationService, $sanitize: ng.sanitize.ISanitizeService, $sce: ng.ISCEService): ng.IDirective
    {
        return {
            templateUrl: '/Views/Home/projects.html',
            scope : {},
            link  : (scope: IProjectsScope) =>
            {
                var projectMap: { [key: number]: IProject; } = {};

                scope.projects = [];

                ProjectResource.query((data: IProject[]) =>
                {
                    data.sort(ProjectSort);

                    var pathname = $location.path();

                    var activeSet = false;
                    data.forEach((project: IProject) =>
                    {
                        project.active = pathname == '/' + project.id;
                        activeSet = activeSet || project.active;

                        project.name        = $sanitize(project.name);
                        project.description = $sanitize(project.description);
                        project.url         = $sce.trustAsUrl(project.url);
                        project.readme      = $sce.trustAsHtml(project.readme);

                        project.title = project.name + (project.fork ? ' (fork)' : ' (repo)');

                        scope.projects.push(project);

                        projectMap[project.id] = scope.projects[scope.projects.length - 1];
                    });

                    if (!activeSet)
                    {
                        data[0].active = true;
                    }
                },
                (data: any) =>
                {
                    throw new Error(data);
                });

                // toggle which tab and tab detail is visible when a link is clicked
                scope.$on('$locationChangeStart', (event, next, current) =>
                {
                    var a = <HTMLAnchorElement>document.createElement('A');

                    a.href = current;
                    var pathname = (<string>(a.pathname.match(/^\/(\d+)/) || [,0]))[1];
                    var currentId = pathname == undefined ? 0 : parseInt(pathname, 10);

                    a.href = next;
                    pathname = (<string>(a.pathname.match(/^\/(\d+)/) || [,0]))[1];
                    var nextId = pathname == undefined ? 0 : parseInt(pathname, 10);

                    currentId && (projectMap[currentId].active = false);
                    nextId    && (projectMap[nextId].active    = true);
                });
            }
        };
    }

    ProjectsDirective['$inject'] = ['ProjectResource', '$location', '$sanitize', '$sce'];
}
The issues with this approach
  • Because the exported function does not utilize a class structure, it's necessary to either use prototypal inheritance or methods exposed in the exported functions scope. ProjectSort is a function that would be better served as a private method in a class.

  • The link method is much larger than it needs to be and could be slimmed down by moving the $locationChangeStart and Query handler methods into the outer function scope. However, this becomes cumbersome to manage with many enclosed methods outside of the link function body and when you need to expose variables like scope, and $location. You then have to manage those variables in the outer scope as well.

  • Due to the length of ProjectsDirective, the minification-safe list of dependencies (ProjectsDirective['$inject']) is quite removed from the function signature. It would be easy to forget to include this, or to update it if your dependencies change.

  • I've never been a huge fan of returning an object from a function to define my directive, and I would simply like to avoid it.

What can be done instead

Thankfully, it's possible to write directives as a class with a bit of a shift in thinking about how you would organize TypeScript, as opposed to how you would organize JavaScript.

The key point to keep in mind is that AngularJS still expects a function that returns an object. It turns out it's simple and clean to do this with a static Factory method on your class.

That first example of a TypeScript directive looks like this as a class.

module MyModule.Directives  
{
    export interface IMyScope extends ng.IScope
    {
        name: string;
    }

    export class MyDirective
    {
        public link: (scope: IMyScope, element: ng.IAugmentedJQuery, attrs: ng.IAttributes) => void;
        public template = '<div>{{name}}</div>';
        public scope = {};

        constructor()
        {
            MyDirective.prototype.link = (scope: IMyScope, element: ng.IAugmentedJQuery, attrs: ng.IAttributes) =>
            {
                scope.name = 'Aaron';
            };
        }

        public static Factory()
        {
            var directive = () =>
            {
                return new MyDirective();
            };

            directive['$inject'] = [''];

            return directive;
        }
    }
}
What this accomplishes
  • We now have proper properties, fields, and methods on our class instance. link, template, and scope are exposed in JavaScript as function properties. If I extend this class, my subclass can override these properties and still utilize the base class functionality.

  • The link method is now another property on the class where its initialization can utilize the class instances scope for property access.

  • The factory function is very short, and so the list of dependencies is immediately in front of the developer. While not perfect, it makes it a little more obvious that the directive function and its $inject property are related.

  • This completely avoids having to return an object from a function because your class instance is the object that Factory returns to angular.

A real-world example with a class

Now let's take a look at how I refactored my original ProjectsDirective to utilize a class structure. You can see here how I take advantage of exposing public properties as the same properties the directive method would normally set in the object it returns. You can also see the private methods and properties I've made available to the class instance in order to avoid relying on function scoping.

module AaronholmesNet.Directives  
{
    'use strict';

    export interface IProject extends Resources.IProject
    {
        title: string;
        active: boolean;
    }

    export interface IProjectsScope extends ng.IScope
    {
        [key: string] : any;

        projects: Interfaces.IListInterface<IProject>
    }

    export class ProjectsDirective
    {
        // #region Angular directive properties, fields, and methods
        public templateUrl = '/Views/Home/projects.html';
        public scope       = {};
        public link: (scope: IProjectsScope, element: ng.IAugmentedJQuery, attrs: ng.IAttributes) => void;
        // #endregion

        // #region Initialization and destruction
        constructor(ProjectResource: Resources.IProjectResource, $location: ng.ILocationService, $sanitize: ng.sanitize.ISanitizeService, $sce: ng.ISCEService)
        {
            this._$location = $location;
            this._$sanitize = $sanitize;
            this._$sce      = $sce;

            ProjectsDirective.prototype.link = (scope: IProjectsScope, element: ng.IAugmentedJQuery, attrs: ng.IAttributes) =>
            {
                scope.projects = [];

                ProjectResource.query(this._handleProjectQuerySuccess.bind(this), this._handleProjectQueryError.bind(this));

                // toggle which tab and tab detail is visible when a link is clicked
                scope.$on('$locationChangeStart', this._handleLocationChangeStart.bind(this));

                scope.$on('$destroy', this.destruct);

                this._scope = scope;
            }
        }

        public static Factory()
        {
            var directive = (ProjectResource: Resources.IProjectResource, $location: ng.ILocationService, $sanitize: ng.sanitize.ISanitizeService, $sce: ng.ISCEService) =>
            {
                return new ProjectsDirective(ProjectResource, $location, $sanitize, $sce);
            };

            directive['$inject'] = ['ProjectResource', '$location', '$sanitize', '$sce'];

            return directive;
        }

        private destruct()
        {
            this._projectMap = null;
            this._$location  = null;
            this._$sanitize  = null;
            this._$sce       = null;
            this._scope      = null;
        }
        // #endregion

        // #region Private class properties, fields, and methods
        private _projectMap : { [key: number]: IProject; } = {};
        private _$location  : ng.ILocationService;
        private _$sanitize  : ng.sanitize.ISanitizeService;
        private _$sce       : ng.ISCEService;
        private _scope      : IProjectsScope;
        // #endregion

        // #region Private event handlers
        // return my repositories first, and forks second.
        // from there, sort by last change time.
        private _projectSort(a: Resources.IProject, b: Resources.IProject): number
        {
            if (a.fork === false && b.fork === true) return -1;

            if (a.fork === true && b.fork === false) return 1;

            if (a.updated_at > b.updated_at) return -1;

            if (a.updated_at < b.updated_at) return 1;

            return 0;
        }

        private _handleProjectQuerySuccess(data: IProject[]): void
        {
            data.sort(this._projectSort);

            var pathname = this._$location.path();

            var activeSet = false;
            data.forEach((project: IProject) =>
            {
                project.active = pathname == '/' + project.id;
                activeSet      = activeSet || project.active;

                project.name        = this._$sanitize(project.name);
                project.description = this._$sanitize(project.description);
                project.url         = this._$sce.trustAsUrl(project.url);
                project.readme      = this._$sce.trustAsHtml(project.readme);

                project.title = project.name + (project.fork ? ' (fork)' : ' (repo)');

                this._scope.projects.push(project);

                this._projectMap[project.id] = this._scope.projects[this._scope.projects.length - 1];
            });

            if (!activeSet)
            {
                data[0].active = true;
            }
        }

        private _handleProjectQueryError(data: any): void
        {
            throw new Error(data);
        }

        private _handleLocationChangeStart(event: ng.IAngularEvent, next: string, current: string): void
        {
            var a = <HTMLAnchorElement>document.createElement('A');

            a.href = current;
            var pathname = (<string[]>(a.pathname.match(/^\/(\d+)/) || [, 0]))[1];
            var currentId = pathname == undefined ? 0 : parseInt(pathname, 10);

            a.href = next;
            pathname = (<string[]>(a.pathname.match(/^\/(\d+)/) || [, 0]))[1];
            var nextId = pathname == undefined ? 0 : parseInt(pathname, 10);

            currentId && (this._projectMap[currentId].active = false);
            nextId && (this._projectMap[nextId].active = true);
        }
        // #endregion
    }
}

Takeaways and wrap up

This approach is not perfect, however I feel it has real strength when focusing heavily on object-oriented programming. I don't demonstrate it here, but the ability to extend base class directives has been very helpful in another project. I also believe the encapsulation is much more clear, and lends itself to avoiding many of the issues we're all familiar with in regards to prototypal inheritance and JavaScript's strange function scoping rules.

Gotchas
  • It's important to note that you may have to bind contexts for event handlers. For example, with this call scope.$on('$locationChangeStart', this._handleLocationChangeStart.bind(this)); we must bind _handleLocationChangeStart to the class instance context because scope.$on will call it within the context of window. If someone knows of a way to handle this in TypeScript without bind, I'd love to hear your input.

  • The scope property is public, and is the same property that is returned from a directive function. _scope is private and is the actual directive's scope object, not the isolate scope definition.

  • It sucks that many parts of the directive function signature are duplicated in the function returned from Factory, the instantiation call, and the constructor signature. I would love to hear alternate ways to accomplish this.

    • b091 discovered a way to avoid both the redundancies and the Factory method by using decorators. See this comment for more information.

  • It is possible to unintentially create only a single instance of your directive by binding functions and variables in the constructor. For any data members that need to be unique between instances, ensure that they are added to the classes prototype rather than the instance itself. See this comment for more information.

Back to the basics

To summarize, here are the basic pieces you need to get this working.

  • A static factory method and a constructor.
class MyDirective  
{
    constructor(/*list of dependencies*/)
    {
    }

    public static Factory()
    {
    }
}
  • A public link method that accepts the same parameters any AngularJS directive accepts, and returns void. Include any other directive properties you need, such as template and scope.
class MyDirective  
{
    public link: (scope: ng.IScope, element: ng.IAugmentedJQuery, attrs: ng.IAttributes) => void;
    public template = '<div>{{name}}</div>';
    public scope = {};

    constructor(/*list of dependencies*/)
    {
    }

    public static Factory()
    {
    }
}
  • The initialization of the link method.
class MyDirective  
{
    public link: (scope: ng.IScope, element: ng.IAugmentedJQuery, attrs: ng.IAttributes) => void;
    public template = '<div>{{name}}</div>';
    public scope = {};

    constructor(/*list of dependencies*/)
    {
        // It's important to add `link` to the prototype or you will end up with state issues.
        // See http://blog.aaronholmes.net/writing-angularjs-directives-as-typescript-classes/#comment-2111298002 for more information.
        MyDirective.prototype.link = (scope: ng.IScope, element: ng.IAugmentedJQuery, attrs: ng.IAttributes) =>
        {
            /*handle all your linking requirements here*/
        };
    }

    public static Factory()
    {
    }
}
  • The instantiation call from your Factory method.
class MyDirective  
{
    public link: (scope: ng.IScope, element: ng.IAugmentedJQuery, attrs: ng.IAttributes) => void;
    public template = '<div>{{name}}</div>';
    public scope = {};

    constructor(/*list of dependencies*/)
    {
        // It's important to add `link` to the prototype or you will end up with state issues.
        // See http://blog.aaronholmes.net/writing-angularjs-directives-as-typescript-classes/#comment-2111298002 for more information.
        MyDirective.prototype.link = (scope: ng.IScope, element: ng.IAugmentedJQuery, attrs: ng.IAttributes) =>
        {
            /*handle all your linking requirements here*/
        };
    }

    public static Factory()
    {
        var directive = (/*list of dependencies*/) =>
        {
            return new MyDirective(/*list of dependencies*/);
        };

        directive['$inject'] = ['/*list of dependencies*/'];

        return directive;
    }
}
  • And finally, the registration of your directive with AngularJS by calling the Factory method.

It's important to note that Factory is executed here, and its returned value (the directive) is passed to Angular's registration function. Be sure to include the parenthesis!

angular.module('MyModule', [])  
    .directive('myDirective', MyDirective.Factory());
]]>
http://aholmes.azurewebsites.net/writing-angularjs-directives-as-typescript-classes/6ce8b22e-e703-42a3-a1da-f28f37946936Mon, 12 Jan 2015 00:48:40 GMT
<![CDATA[Using Time as a Color Generator]]>The idea

I saw the site What colour is it? and thought the concept was really cool. For whatever reason, visualization generators pique my interest. I wanted to alter the original to see a wider range of colors, and to play with the attr() function in CSS' ::after psuedo-element. I also wanted to add a slider just to allow the user to tweak the generated color.

See the Pen Time color by Aaron Holmes (@aholmes) on CodePen.

The HTML and CSS

First set the attribute on your element. I decided to call it data-text.

<h1 id="time" data-text="00 : 00 : 00"></h1>  

We only need two lines of CSS to get the attribute function to display.

h1::after  
{
  display:block;
  content:attr(data-text);
}

Normally the content attribute is set to a static string, but there's also the attr() function that let's you use an attribute value on your element instead.

You can find more information about attr() on MDN.

NOTE: Browser compatibility is sketchy at best. There are some gotchas to be careful of too.

Updating the content with JavaScript

There are no DOM API methods that let us access ::after or ::before psuedo-elements with JavaScript. We can at least use the attr() function in conjunction with the setAttribute() method or dataset property to change the content of the psuedo-elements.

With the HTML element above, here's how we can change the value of the data-text attribute. This change will then be rendered with our CSS rules to display new text in the psuedo-element.

var timeHeader = document.getElementById('time');

var time = "15:30:25";

if (timeHeader.dataset !== undefined)  
{
    timeHeader.dataset.text = time;
}
else  
{
    timeHeader.setAttribute('data-text', time);
}

Theoretically that should be all we need! With a little more code to set the correct time value on a loop, the site will show a new time every second.

A repaint issue on Chrome version 39.0.2171.95

My experiment didn't go perfectly. I discovered that changing the attribute value does not always trigger a repaint, and thus the new time would not display. I have not figured out exactly what caused this; it was sporadic, and I wonder if it's partly related to how codepen works.

Thankfully there's an easy way to trigger a repaint. It's not exactly the prettiest solution, but it does ensure the new time is displayed each second.

timeHeader.style.display='none';  
timeHeader.offsetHeight;  
timeHeader.style.display='';  

 

A little extra

The original code uses the time values as the hexidecimal values for the background color. A time of 9 hours, 23 minutes, and 40 seconds give you the hex color #092340.
Given that this will increment the 0th digit for each red, green, and blue hex value, we end up with a similar color for each second, minute, and hour.

If the time value is 09 23 40, then our RGB values are as follows.

HexDecConversion
Red0x099(0 * 16^1) + (9 * 16^0)
Green0x2335(2 * 16^1) + (3 * 16^0)
Blue0x4064(4 * 16^1) + (0 * 16^0)

After 1 second, blue becomes 65, then 66, 67, 68, and so on. This is a very slow increase!
Additionally, because there are only 24 hours in a day, 60 minutes to an hour, and 60 seconds to a minute, our scale of colors is limited. Red ranges from 0 - 23, green 0 - 59, and blue 0 - 59.

Here's a visualization of all possible red, green, and blue values individually.

To get a wider range of colors, each hexidecimal string value can be flipped. For example, 9 is "09" as a string, and "90" flipped. Here's what our example above looks like with the values flipped.
HexDecFlipped String
Red0x09990
Green0x233553
Blue0x406446

And here's the range of colors and the pattern in which they occur.

]]>
http://aholmes.azurewebsites.net/using-time-as-a-color-generator/64920f94-8323-4a5d-b9b7-fe5823da9494Sat, 20 Dec 2014 06:48:45 GMT
<![CDATA[Speech Synthesis on Windows Phone 8.1]]>I recently wrote an application to make my phone report current Los Angeles traffic conditions. I used the Windows.Media.SpeechSynthesis namespace to read in either a plain-text string, or an SSML-formatted string, and to speak it until the end. It turns out that speech synthesis with .NET libraries is incredibly simple, but some information takes a little effort to find. For me, searching for "text-to-speech windows phone 8.1" shows me a bunch of results for how to accomplish this with Silverlight! Definitely not what I want.

The setup

Because this was for a Windows Phone application, I needed a way to access a MediaElement object to play, pause, and stop the speaking if I pressed a button to do this. I opted to create a private object on my MainPage instance.

namespace PhoneTraffic  
{
    public sealed partial class MainPage : Page
    {
        private MediaElement media;

        public MainPage()
        {
            this.InitializeComponent();
            this.NavigationCacheMode = NavigationCacheMode.Required;
            media = new MediaElement();
        }
    }

Synthesizing some sentences

From here, we instantiate a SpeechSynthesizer object.

using(var synth = new SpeechSynthesizer())  

Then we need to pass a plain-text string into the synthesizer, and store the outputted stream so we can set it on the media object.

var stream = await synth.SynthesizeTextToStreamAsync("Hello, World!");  

Then set the stream source on our media object.

media.SetSource(stream, stream.ContentType);  

Now we're ready to tell the phone to play, pause, or stop the speaking of our sentence. Here's how it looks in my application.

Using plain-text
private async void GetTrafficButton_Click(object sender, RoutedEventArgs e)  
{
    var incidents = await Task.Run(() => JsonConvert.DeserializeObject<TrafficIncident[]>(trafficJson));

    if (incidents.Length == 0)
    {
        using(var synth = new SpeechSynthesizer())
        {
            var stream = await synth.SynthesizeTextToStreamAsync("There are no incidents right now.");
            media.SetSource(stream, stream.ContentType);
            media.Play();
        }
    }
    else
    {
        using(var synth = new SpeechSynthesizer())
        {
            var toSay = String.Empty;

            for(var i = 0; i < incidents.Length; i++)
            {
                var incident = incidents[i];

                toSay += " At " + incident.Time + " there was a " + incident.Incident + " incident at " + incident.Location;
                toSay += (i < incidents.Length - 1) ? " and another " : ".";
            }

            var stream = await synth.SynthesizeTextToStreamAsync(toSay);
            media.SetSource(stream, stream.ContentType);
            media.Play();
        }
    }
}

My pause and stop methods are simpler:

private void PausedSpeechButton_Click(object sender, RoutedEventArgs e)  
{
    media.Pause();
}

private void StopSpeechButton_Click(object sender, RoutedEventArgs e)  
{
    media.Stop();
}
Using SSML

If you want to use SSML, use the method SynthesizeSsmlToStreamAsync instead of SynthesizeTextToStreamAsync and pass an SSML-formatted string to it.

My application supports both modes. I create the SSML string on my API server, and the phone consumes it. Here's what the code looks like (replaces the "else" block in the plain-text example).

using(var synth = new SpeechSynthesizer())  
{
    var stream = await synth.SynthesizeSsmlToStreamAsync(ssml);
    media.SetSource(stream, stream.ContentType);
    media.Play();
}

Here are some resources I used.

]]>
http://aholmes.azurewebsites.net/speech-synthesis-on-windows-phone-8-1/d0de652f-d037-49e5-978e-19803f3af176Sun, 07 Dec 2014 01:19:46 GMT