How to setup your UWP project with Jenkins

Follow these steps to automatically pull your UWP project via Git using Jenkins:

  1. Install Jenkins
  2. In Jenkins (usually http://localhost:8080/ ), create a new item and select Freestyle Project
  3. Once created, in the projects configuration page scroll down to build and click on Add build step -> Execute Windows batch command
  4. Enter the following:
    call “C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\bin\vcvars32.bat”
    msbuild C:\projects\sample\sample.jsproj /t:Clean;Rebuild /p:Configuration=Release
  5. Notes:
    1. The first line is assuming you installed VS 2015 in the default folder.
    2. If you want to compile the whole solution just target the .sln instead of the project in the second line
    3. If you want to target a specific platform, just add “;Platform=x86” (without quotes) in the second line
  6. Click Save
  7. You should be able to run the project by clicking Build now

Jenkins comes with support for source control systems such as CVS or SVN (Subversion). If you want/need Git support you’ll need to install a plugin. Here are the steps add Git integration:

  1. Go to Manage Jenkins
  2. Click on Manage Plugins
  3. Click on Available and search for Git
  4. Install the GitHub plugin
  5. After installing go to Manage Jenkins and click on Configure System
  6. Scroll down until you see Git / Git Installations
  7. Enter your path to Git executable, could be something like: c:\program files (x86)\git\bin\git.exe
  8. Save your changes
  9. Go to your project configuration
  10. Scroll down until you see Source Code Management and select Git.
  11. Enter the repository URL
  12. Add your credentials
  13. Enter branch to build if necessary
  14. Scroll down to Build section and change the msbuild line to
    msbuild sample\sample.jsproj /t:Clean;Rebuild /p:Configuration=Release
  15. Notes:
    1. This is needed so that Jenkins uses the project downloaded from Git
    2. The folder where Jenkins does this work is in: C:\Program Files (x86)\Jenkins\jobs\[project name]\workspace

Every time you click build it will pull the code from Git and make a build.

How to setup Facebook and Google Apps to work with OAuth on UWP applications

Follow these steps to get OAuth working in Windows Store applications (UWP).

Facebook:

  1. Go to Windows Dev Center
  2. Create a new application
  3. Once in app overview click on “App management” -> “App identity
  4. Take note of the Package SID (starts with something like: S-1-15-2-more-numbers)
  5. Open the WebAuthenticationBroker sample from Windows 10 Samples on GitHub
  6. Right click on the project name and select “Store” -> “Associate App with the Store
  7. Follow the steps until you see the application created in your Windows Dev Center to associate it with the current project.
  8. Open scenario1.js and change line 43 where it reads: scope=read_stream to scope=public_profile,email (or any other set of properties you want to access.)
  9. Register as Facebook developer
  10. Create a new application
  11. Go to “Settings” and click “Add Platform” -> “Windows App
  12. In the Windows Store ID field enter the Package SID that you took note before (refer to step 4)
  13. Click “Save changes
  14. Click on “Advanced” – tabs on the top of the page
  15. In the “Client OAuth Settings” make sure that “Client OAuth Login” is checked as “Yes“.
  16. Click on “Teat Apps” on the side menu.
  17. Click on “Create a Test App” and create a test application with the name of your choice.
  18. Once in the dashboard of the newly created application take note of the “App ID“.
  19. Click on “Roles” in the side menu.
  20. Click on “Test Users” -> “Add” -> “Create Test Users“.
  21. In the “Test Users” section click on “Edit” -> “Change the name or password for this user” and enter a password of your choice.
  22. Take note of the Test User’s email and password.
  23. Return to Visual Studio and run the application.
  24. Enter the App ID (refer to step 18) in the “Facebook App ID” field.
  25. Enter ms-app://Package SID (refer to step 4 to get the package SID) on the “Callback URL” field.
  26. Click on “Launch“.
  27. Enter the Facebook’s test user email and password (refer to step 22).

 

Google:

  1. Go to Google Developers Console (https://console.developers.google.com/)
  2. Create a new project
  3. In the “Use Google APIs” section click on “Enable and manage APIs
  4. In the “Social APIs” section click on “Google+ API“.
  5. Click “Enable API“.
  6. Click “Credentials” in the side bar menu.
  7. Click “Add credentials” and then select “OAuth 2.0 client ID“.
  8. Click on “Configure consent screen“.
  9. Enter a product name and click “Save“.
  10. In the “Application type” select “Other” give it a name (e.g. “Windows Store App”) and click “Create“.
  11. Take note of the client ID.
  12. Go to Visual Studio and run the WebAuthenticationBroker application.
  13. Switch to the Google OAuth using the hamburger menu.
  14. Enter the Client ID (refer to step 11).
  15. Enter google credentials.

 

Note: If your project crashes around line 57:

if (Windows.Security.Authentication.Web.WebAuthenticationBroker.authenticateAndContinue)

on desktop or tablet make sure to change it to

if (Windows.Security.Authentication.Web.WebAuthenticationBroker.authenticateAndContinue &&
Windows.System.Profile.AnalyticsInfo.versionInfo.deviceFamily == "Windows.Mobile")

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)