Generating TypeScript documentation generation

There’s a great little tool called TypeDoc that allows us to generate html documentation based in our comments inside our TypeScript files similar to what JavaDoc does. To use this tool follow these steps:

  1. Install nodejs: http://nodejs.org/dist/v0.10.35/node-v0.10.35-x86.msi
  2. Open command line and run nodejs by typing: node
  3. In the nodejs prompt install typedoc by typing: npm install –global typedoc
  4. Type: typedoc -t ES5 –out doc/ references.ts

This will compile all the documentation (classes, namespaces, functions, etc.) that can be referenced by the file references.ts and it will be put under the doc folder in the current directory where that command is ran.

It’s preferred to update your project’s documentation from time to time and TypeDoc has integration with tools like Grunt but if you want this to run after you create a build you can add this command to the post build events list of commands the way I’ve shown in the previous post. For example:

<Exec Command="typedoc -t ES5 --out &quot;$(ProjectDir)/doc/&quot; &quot;$(ProjectDir)/tsDec/references.ts&quot;" />

TypeDoc follows JavaDoc comment tags:

@param <param name> <description>
@returns <description>

Examples:

/**
* This is a function.
* @param arg This is the argument.
* @returns Returns a value.
**/
function func(arg: text): string;

/**
* This is a name.
**/
var name:string = "a name";

You can also use the @preferred tag if you have different comments for the same thing (e.g. a module that is declared in different files and has different comments in both files or an interface and its class implementation) and you want to use a specific comment over the other as TypeDoc will use the first comment that it finds.

Adding pre and post build events in Visual Studio (Windows Store / JavaScript projects)

In Visual Studio you can add pre and post build events, basically these are commands that you can program to run before the build command executes and after it finishes building the solution configuration. To configure these you can easily go to Project -> Properties -> Build Events and write whatever commands you want to run in the Pre and post build events boxes. Of course that this is only true for C# or C++ projects. If you tried to do this in a Windows Store JavaScript application project you most likely noticed that these pre/post build events were missing. Not sure what was the reasoning behind it but I guess the folks at the VS team thought it would be a good idea. Anyway, you can still get access to these by editing you jsproj file and looking for:

<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>

You’ll notice that there’s a whole section that is commented out with this comment:

To modify your build process, add your task inside one of the targets below then uncomment that target and the DisableFastUpToDateCheck PropertyGroup.
Other similar extension points exist, see Microsoft.Common.targets.

So you just need to follow the instructions and add a command inside one or both of the pre/post build event xml nodes. To add a simple copy a file named lib.dll from the output directory to your project directory after building you’d do something like:

<Target Name="AfterBuild">
  <Exec Command="copy &quot;$(OutDir)/lib.dll&quot; &quot;$(ProjectDir)/&quot;" />
</Target>

Note: the &quot; is intentional so that the string gets quoted when it’s used by the copy command.

TypeScript declarations for Player Framework

– Are you programming in JavaScript?
– Yes.
– Are you using TypeScript?
– No.
– Please stop! Do yourself a favour and go learn TypeScript to use it in your project.

I’ve been programming JavaScript for Xbox One projects and since I saw a TypeScript session at Build 2014 that I was completely sold to it.

TypeScript is a language that is a superset of JavaScript compiling the result to plain JavaScript. It makes JavaScript development easier to manage by adding types, classes, modules and interfaces. And because it compiles to JavaScript, you don’t really need to have any TypeScript compiler to run a project.

What if you already have a big JavaScript project?
No problem, you just start slowly converting the code to TypeScript or you can create declarations (similar to a .h file for C/C++ projects) for your utility libraries that work just as well.

My TypeScript contribution to the world is a Player Framework (MMPPF) declaration file available at the DefinitelyTyped GitHub repository.

Enjoy and start using TypeScript!

How to debug a Windows 8 app upgrade in Visual Studio

Some times it’s useful to debug if your new update breaks anything to users who have the previous version of your app. The process to debug this is not very straightforward but here it is:

– Create a package with first version (right click on the project -> store -> create package)
– Install the package.
– Run app and make sure it saves some user data.
– Make a new package with second version.
– Install package.
– On the Start menu, search for Debuggable Package Manager and then start it.
– A PowerShell window properly configured for the AppxDebug cmdlet appears.
– To enable debugging of an app, you must specify the PackageFullName identifier of the app.
– Type Get-AppxPackage at the PowerShell prompt (to view a list all apps that includes the PackageFullName.)
– At the PowerShell prompt, enter Enable-AppxDebug PackageFullName where PackageFullName is the PackageFullName identifier of the app.
– Run app
– Launch Visual Studio
– Go to Debug -> Attach to process…
– In the list of available processes select the one called WWAHost.exe and with the name of your app in the Title column.

“New” technologies (Discovering the TI world)

Today’s post describes my adventure into the world of TI (Texas Instruments) programming. A little bit out of its time but nevertheless interesting to anyone who likes to learn new things and open their horizons.

My cousin is a few months away of completing his Civil engineering degree and is really interested in TI programming, doing scripts that help him solve problems really fast instead of having to do them manually (most useful in exams). He does all the programming in TI-Basic, a language similar to Basic but specific to TI calculators and like most (if not all) of these interpreted languages, they don’t provide any security if you want to sell your programs. Thus he turned to C programming. Now, C is a whole new beast when compared with this TI-Basic language and it’s much harder to start doing some interesting things without your programs crashing all over the place.

He asked me for help but having no knowledge of this TI-Basic or C tools/libraries/APIs available for these calculators and without access to internet and limited documentation and samples I wasn’t able to get complete the program although I did manage to make half of it. This was a 4 hour marathon that started around 22h30 till 2h30 and I had to admit defeat at the time since I was very tired but I promised to help him to finish the program. I don’t have a TI calculator so I needed to find a way to test it in my PC and fortunately there is an IDE along with an emulator and ROM image available for free on the internet. I’ll list what’s needed to be able to run and the debug C programs for TI calculators because it took me a while to get everything up and running due to incompatible versions of software.

  1. Download and install TIGCC 0.96 beta 8 (Unofficial version)
  2. Download and install TiEmu 3.02a
  3. Download TI Voyage 200 ROM image (my cousin’s model)
  4. Create a project in TIGCC
  5. Run the project (Debug –> Run)
  6. When the TiEmu wizard appears select “You have downloaded a FLASH upgrade on the TI website”
  7. Then select the TI Voyage 200 ROM image you’ve downloaded before.

Voilà! If everything went well you should see the program running on the emulator.

If you want to debug your project, follow these steps:

  1. Project –> Options
  2. Select the “Compilation” tab and then the option “Generate debug information”
  3. Run the project (Debug –> Run)

You should see new windows open if you followed these steps. These are the debug windows that will help you find your bugs.

Here are a few snippets I had to discover here and there through samples / documentation:

/* Retrieves strings passed into the program */
ESI argptr;
int argtype;
char *str;
InitArgPtr (argptr);
while ((argtype = GetArgType (argptr)) != END_TAG)
{
  if (argtype == STR_TAG)
  {
    str = GetStrnArg(argptr);
    printf("%s", str);
  }
  else
    break;
}
/* Get a variable from TI-Basic into C */
SYM_ENTRY *sym_entry = SymFindPtr (SYMSTR ("variableName"), 0);
if (!sym_entry)
  return FALSE;
ESI expr = HToESI(sym_entry->handle);
int argType = GetArgType(expr); /* Retrieves the type of the expression */
long num = GetIntArg(expr); /* Retrieves an integer if the expression holds an integer (positive or negative) */
/* Directly from TIGCC documentation: Run a TI-Basic program or statement from C */
char fname[25];
HANDLE h;
strcpy (fname, name);
strcat (fname, "()");
push_parse_text (fname);
h = HS_popEStack ();
TRY
  NG_execute (h, FALSE);
FINALLY
  HeapFree (h);
ENDFINAL

Including tigcclib.h will make sure that you have all the TI library functions available in C. For the last snippet you need to follow these steps if you have an error regarding push_parse_text function:

  1. go to Project->Options
  2. select the “Compilation” tab
  3. click on “Program Options…”
  4. select the “Operating System” tab
  5. and set the “Minimum AMS Version” as 1.01

Kinect Calibration

This program adjusts Kinect to better see the user, this way the user doesn’t have to move back or forward (unless Kinect’s angles aren’t enough to see the user). I think this is a useful thing to have when you start your Kinect application.

The code is very simple to follow. Use Kinect’s elevation angle to change the Kinect’s “view” and track the user in sight. For each angle count how many joints Kinect is tracking and save that angle as the best if we reach a new maximum number of tracked joints.

void KinectSkeletonFrameReady(object sender, SkeletonFrameReadyEventArgs e)
{
	// Get skeleton information
	using (SkeletonFrame skeletonFrame = e.OpenSkeletonFrame())
	{
		if (skeletonFrame != null && m_skeletonData != null)
		{
			skeletonFrame.CopySkeletonDataTo(m_skeletonData);
		}
	}

	m_curTime = m_watch.ElapsedMilliseconds;

	if (m_calibrationState == CalibrateState.GoingDown)
	{
		// If the sensor reach its lowest angle, let's do a full scan from min angle to max angle.
		if (m_curTime >= WaitTime)
		{
			m_watch.Reset();
			m_watch.Start();

			m_bestAngle = m_kinect.MinElevationAngle;
			m_maxNumTracked = 0;

			m_calibrationState = CalibrateState.GoingUp;
			m_kinect.ElevationAngle = m_angles[m_curAngleIndex++];
		}
	}
	else if (m_calibrationState == CalibrateState.GoingUp)
	{
		if (m_curTime >= WaitTimeGoingUp)
		{
			m_watch.Reset();
			m_watch.Start();

			// If we scanned all the angles, lets adjust kinect to the best angle.
			if (m_curAngleIndex > m_angles.Length - 1)
			{
				m_calibrationState = CalibrateState.GoingBest;
				m_kinect.ElevationAngle = m_bestAngle;
				return;
			}

			m_kinect.ElevationAngle = m_angles[m_curAngleIndex++];
		}

		// For each skeleton, count the number of tracked joints and save the best
		// angle when the number of tracked joints is greater than previous values.
		foreach (Skeleton skeleton in m_skeletonData)
		{
			if (skeleton == null)
				continue;

			if (skeleton.TrackingState == SkeletonTrackingState.Tracked)
			{
				//TODO: Improve algorithm by using the number of inferred joints.
				int numTracked = 0;
				int numInferred = 0;
				foreach (Joint joint in skeleton.Joints)
				{
					if (joint.TrackingState == JointTrackingState.Tracked)
						numTracked++;
					else if (joint.TrackingState == JointTrackingState.Inferred)
						numInferred++;
				}

				if (numTracked >= m_maxNumTracked)
				{
					m_maxNumTracked = numTracked;
					m_bestAngle = m_kinect.ElevationAngle;
				}
			}
		}
	}
	else if (m_calibrationState == CalibrateState.GoingBest)
	{
		// Just wait until kinect adjusts itself to match the best angle.
		if (m_curTime >= WaitTime)
		{
			m_watch.Reset();

			m_calibrationState = CalibrateState.Idle;
			m_kinect.SkeletonFrameReady -= KinectSkeletonFrameReady;

			// Reset Kinect state.
			DisableStreams();
			EnableStreams();

			// Signal that we finished the calibration.
			if (OnCalibrationComplete != null)
				OnCalibrationComplete();
		}
	}
}

You may notice two things about the code:

  • First is that I’m using time to control between Kinect movements. The reason for this is that if we try to compare Kinect with the angle we set, we might not get the same value for different reasons (Kinect sensor is not 100% accurate or it couldn’t physically rotate the sensor to that exact angle).
  • And second is the fact that I’m only scanning the skeleton for some angles. I don’t know if this is a Kinect’s limitation or if I did something wrong in the code but I couldn’t track any joints while Kinect was moving. So what I did was move the sensor between some angles and wait there a bit to count the bones for each one of those angles.

Known limitations:

  • it only supports 1 user at this moment;
  • the scanning process is not ideal.

Download:

Kinect Calibration (13Kb)

Visual Studio 2010/11 Utilities

Here is a compilation of very useful utilities for VS 2010 and VS 11.
Note: Utilities with an asterisk (*) beside the name are not available to VS 11 yet.

CLIArgs Made Easy

http://www.ricardosabino.com/?p=214
CLI Args Made Easy (Command Line Arguments Made Easy) is an add-in that allow you to change the command line arguments of the startup project very easily by adding a combobox in the toolbar. It also saves all the arguments you insert for future use.

Debugger Canvas (*)

http://msdn.microsoft.com/en-us/devlabs/debuggercanvas.aspx
Debugger Canvas is a new user experience for the debugger in Visual Studio Ultimate. It pulls together the code you’re exploring onto a single pan-and-zoom display. Visual debugger and multithreading debugging goodies.

Productivity Power Tools (*)

http://visualstudiogallery.msdn.microsoft.com/d0d33361-18e2-46c0-8ff2-4adea1e34fef
A set of extensions to Visual Studio Professional (and above) which improves developer productivity. Very useful enhanced scrollbar, vertical tabs, quick find files, searchable references and editing tools.

ReSharper

http://www.jetbrains.com/resharper/
With unparalleled support for C#, VB.NET, XAML, JavaScript, XML, HTML, CSS, ASP.NET and ASP.NET MVC, including comprehensive cross-language functionality, ReSharper will help Visual Studio users write better code, easily examine and refactor existing code bases. A must have for anyone who’s doing C# code.

Visual Assist X

http://www.wholetomato.com/
Read, write, navigate, and refactor code FAST with more than 50 productivity-boosting features for C++/C, C#, VB, ASP, JavaScript. A must have for anyone who’s doing C++ code.

VisualHG (*)

http://visualhg.codeplex.com/
Mercurial Source Control Plugin for MS Visual Studio.

Kinect Slide Tutorial

Part of my Kinect Portfolio presentation had slides controlled by gestures. This short tutorial explains how I made it work. As I said in the other post, I used a Gesture Library to help with the gesture recognition, Kinect SDK Dynamic Time Warping (DTW) Gesture Recognition. This is a great project that is available on CodePlex and uses a cool algorithm called Dynamic Time Warping which is pretty cool for pattern recognition such as gestures or voice, among others. If you’re curious like me and want to know how this algorithm works, take a look at this link.

But onto the slide tutorial. I started by taking the core files to handle the gesture recognition and plug it in with my project. After a couple of little changes mostly to call an event handler when a gesture is recognized and to work with the final Kinect SDK 1.0., I used the original program to generate the gestures file which contains the information needed to detect gestures. I actually recorded two different gestures for each “SlideLeft” and “SlideRight” gesture just to make sure that different gestures done by different people would be caught by the algorithm.

The next step was to figure out how to animate the slides. I didn’t have experience with WPF animations but I arrived at this solution which works but might not be the best.

VisualStates and their transitions

I created 3 visual states to handle the slide left and slide right: previous (VisualState 1), current (VisualState 2) and next (VisualState 3). There are 2 visual transitions (left and right) between each 2 states and every time we change from one visual state to another we update the “next” target with new slides.

To automatize the transitions I decided to create a SlideManager that starts by reading all the “slides” (Grid elements) under a parent element and initializing the visual states by adding the event handlers. I created a simple structure to keep track of slides and transitions between slides because initially I wanted to include vertical transitions by ended up not doing them.

// Initialize slides.
for (int i = 0; i < mainSlideContainer.Children.Count; i++)
{
	Grid slide = mainSlideContainer.Children[i] as Grid;
	if(slide == null)
		continue;

	Slide s = new Slide()
				            {
				                Name = slide.Name,
				                GUIElement = slide,
				            };

	m_slides.Add(s);
}

for (int i = 0; i < m_slides.Count; i++)
{
	Slide nSlide = null;
	Slide pSlide = null;

	if (i < m_slides.Count - 1)
		nSlide = m_slides[i + 1];
 	if (i > 0)
		pSlide = m_slides[i];

	Slide s = m_slides[i];
	s.Transitions = new Dictionary();
	if(nSlide != null)
		s.Transitions.Add(Transition.RightToLeft, nSlide);
	if (pSlide != null)
		s.Transitions.Add(Transition.LeftToRight, pSlide);
}

There are two other important methods that change slides: MoveToNextSlide() and MoveToPrevSlide(). Each method checks if the current slide has the transition we want to perform, updates the current slide and visual state attribute members and calls the method that actually performs the transition.

public void MoveToNextSlide()
{
	if(m_inTransition)
		return;

	Slide nextSlide;
	if (m_curSlide.Transitions.TryGetValue(Transition.RightToLeft, out nextSlide))
	{
		m_prevSlideIndex = m_curSlideIndex;

		m_curSlideIndex = Math.Min(m_curSlideIndex + 1, m_slides.Count - 1);
		m_curSlide = m_slides[m_curSlideIndex];
		m_curVSIndex = (m_curVSIndex + 1) % m_visualStates.Count;
		m_curVS = m_visualStates[m_curVSIndex];

		m_inTransition = true;
		ExtendedVisualStateManager.GoToElementState(m_vsManagerContainer, m_curVS.Name, true);
	}
}

Another part of the code that is worth mentioning is the two event handlers at the end of this manager: Storyboard_Completed and VSGCurrentStateChanged.

private void Storyboard_Completed(object sender, EventArgs e)
{
	m_slides[m_curSlideIndex].GUIElement.Opacity = 1;
	m_slides[m_curSlideIndex].GUIElement.Visibility = Visibility.Visible;

	if (m_prevSlideIndex != m_curSlideIndex)
	{
		m_slides[m_prevSlideIndex].GUIElement.Opacity = 0;
		m_slides[m_prevSlideIndex].GUIElement.Visibility = Visibility.Collapsed;
	}
}

The visual state transitions do the slide movement and the storyboard controls the opacity and visibility of the element in that state. Whenever we change from one state to the other we have to reset the opacity and visibility properties so that the next time we do the transitions the new slides have the correct properties.

private void VSGCurrentStateChanged(object sender, VisualStateChangedEventArgs e)
{
	VisualState nvs = m_curVS;

	// update the next visual state time line (only if necessary)
	if (m_curSlideIndex < m_slides.Count - 1)
	{
		Timeline tl = FindObjectByName(nvs.Storyboard.Children, nvs.Name + "_next" + TLOpacName);
		if (tl != null)
			tl.SetValue(Storyboard.TargetNameProperty, m_slides[m_curSlideIndex + 1].Name);

		tl = FindObjectByName(nvs.Storyboard.Children, nvs.Name + "_next" + TLVisName);
		if (tl != null)
			tl.SetValue(Storyboard.TargetNameProperty, m_slides[m_curSlideIndex + 1].Name);
	}

	m_inTransition = false;
}

The same goes for the storyboard target name property, whenever we change to a new state we have to update the next slide. I also used a flag to prevent it from starting a new transition while we’re still doing the animation from the current transition.

The KinectManager is a simple class to handle the Kinect’s initialization that I adapted from the samples. It’s far from complete as it is but it serves well for this tutorial.

You may ask yourself why go through all this trouble when there is PowerPoint and Kinect applications to do the slide animation controls? Firstly, because it is fun to explore and learn new things and secondly because there are parts of the complete interactive portfolio that weren’t so easy to do in PowerPoint such as the particle system or the pong game.

Note: The transitions between texts were programmed in a similar way but instead of using 3 Visual States I only used 2, one for display the text and the other and to hide it, then it’s just a matter of setting the right text when you do the transitions.

Download
Kinect Slide Tutorial (requires: .Net4, Kinect SDK 1.0, VS2010 and up)

More movies as code

I must admit that that Movies as Code site got me addicted Smile Here are a few other entries of mine:

Back To The Future

svn merge -r 1985:1955 .

Indiana Jones and the Raiders of the Lost Ark

void RetrieveGoldenIdol()
{
    while(true)
    {
        float dif = bag.Weight - indy.CalculateApproxWeight(idol);
        // 200g of margin should be enough.
        if(dif < -100) bag.AddSand(rand.Next(100, -dif));
        else if(dif > 100) bag.RemoveSand(rand.Next(100, dif));
        else break;
    }
    Swap(bag, idol);
    DeployTraps();
    indy.Run();
}

Jumper

void Jump()
{
    if(Seen("place"))
        goto place;
    return;
place: ;
}

These ones weren’t posted because they were similar to others on the site:

Inception

function goDeeper() {
    if(kick) {
        if(wakeFromKick)
            return;
        else
            Limbo();
    }
    goDeeper();
}

Stargate

void Stargate()
{
earth:
    goto newPlanet;

    // travelling

newPlanet:
    Explore();
    KillGoaulds();

    goto earth;
}

Back To The Future as Code

David Amador twitted about this cool site Movies as Code and I decided to make a simple entry for Back To The Future as C++. Here is my entry: http://moviesascode.net/adventure/back-to-the-future-2/

The code doesn’t appear correctly on that site so here it is the full version:

#include <future>
#include <iostream>

int main()
{
  auto future = std::async([] { return "Future"; });
  std::cout << "Back To The " << future.get() << std::endl;
  return 0;
}

For those who didn’t get it: C++11 added a new feature that is used in the sample called “future” that will hold the result of an async function somewhere in the future. It was just to play around with the name of that feature :)