Most Popular Posts

  • There has not been recent blog activity

Most Commented On

  • There has not been recent blog activity

Current Bloggers

Sponsors

Wikis

  • You have not yet contributed to any pages.

Where to put custom Knockout Binding Implementations

Posted by Derik Whittaker, Sunday, March 17, 2013 (4,854 views)

The other day I was creating my first Knockout Custom Binding which was pretty straight forward.  But I was a bit stumped as to what was the ‘best’ practice for where to put this custom binding.  Of course I did not want to put it in my view model as that would defeat the purpose/idea behind creating a custom binding, which is to provide a global, reusable way to perform an action.  My gut told me to put the binding in its own file but I thought I would ask twitter for its advice and below are some of the responses I received, this told me I was on the right path.

image

Since the conclusion was to put all custom Knockout bindings in their own file the only thing left to do was to implement this.  Here is what I did.

Create CustomKnockoutBindings.ts file

In my case I am using Typescript (in case .ts extension threw you off) So I needed to implement the code below:

image

If you look at the implemented code you should understand 2 things

  1. We are going to create our bindings within the jQuery Document Ready method.  This will allow for our bindings to be created when the page loads.  This also prevents us from having to ‘call an init’ method from any of our view models
  2. We are extending the KnockoutBindingHandlers interface (this is found in knockout.d.ts).  We need to extend this interface otherwise you will get a compile error from Typescript saying that bindingHandlers.strikeThroughCompleted does not exist on KnockoutBindingHandlers

Once you have the above implemented you should be good to go, only thing left to do now is to implement this in side your HTML.

Implement my custom binding in HTML

image

In the code above you can see that I am using our strikeThroughCompleted binding in the same manor as the ‘text’ binding immediately to its left.

Till next time,

Discuss (7)

0 to 60 with Web API Slide Deck from Columbia Enterprise Guild

Posted by Derik Whittaker, Friday, March 15, 2013 (4,670 views)

The other night I had the opportunity to head down to Columiba SC to speak at their Enterprise Guild about Web API.  First I would like to thank everyone who showed up, I had a great time and I hope everyone found the information useful.

Below is the content from the session:

 

Have fun w/ the content and hope to see the group in the future.

Till next time,

Filed under: , ,
Discuss (6)

Building a Game With JavaScript: Making Things Move

Posted by Christopher Bennage, Wednesday, March 13, 2013 (5,553 views)

This is a continuation from the previous post.

Setting The Stage

The game we’re building will have waves of enemy ships fly in to attack the player’s units. Let’s begin by making a simple enemy as well as some dummy targets for them to attack. I’m going to keep the graphics very simple for the moment. Likewise we are going to focus on the enemy behavior and not worry about any player interaction just yet.

Here’s a demo of what we’ll make. Click on the start screen to transition into the game. The little yellow rectangles are our enemy ships. Each one projects its own target as a little red circle. Once it touches its target, it projects a new one and then flies toward it.

Let’s start from the top down. Our enemy units will “live” in our main screen for the game. (At least for the time being.) This screen needs to expose the same interface that we had for the start screen we made in the last post. We’ll also add a start method that we’ll call just once in order to initialize things.

Implementation

Here’s the implementation:

Explanation

The entities array will contain a list of the enemies we’re tracking. I used the name “entity” because this is a common term in game development. In general, it means something that has behavior and is drawn to the screen. Thus, you can expect entities to have update and draw methods. This is not a hard and fast definition though. You’ll find that the specifics of the definition can vary among engines, frameworks, and developers.

In our start function we populate entities by invoking our (as yet undefined) makeEnemyShip function. I’m passing in two numbers that makeEnemyShip will use to set the x and y position of the ship. I could have used random numbers or even hard coded values, however deriving from the loop’s controls makes it easy to cluster all the ships in the upper left corner of the screen.

The draw and update functions for the screen are very similar. They both iterate over entities and invoke the corresponding function on each entity. They also pass along the necessary context. For draw, this is the 2D drawing context of the canvas and for update it’s the elapsed time since the last frame.

Notice how the loop is structured differently from the loop in start. This is a performance optimization; though it has little consequence with so small an array. On some browsers, the call to length is a bit expensive. (Especially in cases when the array isn’t an array, but something that is array-like.) This adds up when you make the call once per iteration of the loop. We move it out of the loop so that we only call it once. Check out this test. Performance optimizations are tricky and change every time new browsers are released. It’s easy to get confused, and I recommend profiling your code frequently to look for hot spots rather than just guessing about optimizations. I hope to talk more about them later, but if you want more now check out the book High Performance JavaScript by Nicholas C. Zakas.

I had originally written my loops using the newer Array.forEach to iterate over entities. However, this proved to be significantly slower than a for loop.

The screen’s draw method also resets the canvas at the beginning of each iteration. If we did not do this, then every thing we drew on previous frames would still be present. For the start screen, I used clearRect however here I used fillRect with a solid color.

Here’s a function that will produce a simple enemy. It follows the same structure we’ve been using, update to handle the behavior and draw to actually draw it on the screen.

Some Bad Guys

Our enemy ships are a little more complicated than the screen they live on. Visually, they appear to have two components. The little yellow rectangle that moves about the screen and the phantom target that they project as a little red circle. In the final game, they will target one of the player’s units. However, the logic is very similar. In fact, it may become useful in debugging to how each enemy ship render something over it’s actual target.

Implementation

Explanation

Each enemy ship will be responsible for tracking its own state. In this code, the state is captured in a closure. In later code, we’ll track the track in a more traditional way. (I haven’t ran tests yet but I think that using a closure may have a performance impact.)

All of these variables represent the enemy ship’s state.

position is the location on the screen where we will render our ship.

Technically, the is the position in “world space”. World space is the logical space that entities in your game “live in”. This is distinct from “screen space”, which corresponds to the actual pixels on the screens. You can think of it this way: in your game you might have a circle with a radius of 10 and located at (100,100). However, where you draw it on the screen will depend upon where the player is viewing it from. If the player zooms in, the circle will grow larger but this doesn’t change the logical position or radius of the circle. We use the term “projection” to describe this. We project from world space into screen space based upon how the player is viewing the game world. The simplest project of course is just 1:1. Which means that there is no difference between world space and screen space. That’s what will stick with for the moment.

orientation is the direction the ship is currently facing. Our ship will always travel in the direction of its orientation. This constraints causes the ship travel in smooth arcs as opposed to abruptly changing its course.

turnSpeed and speed represent how quickly the ship can turn and how fast it can travel respectively. We won’t be modifying these values after setting them, which means the ship will turn and travel at constant rates. These values represent the rates of change for orientation and position. Note also, we defined turnSpeed in terms of fullCircle. This is an alias for Math.PI * 2; we are dealing in radians and not degrees.

target is a value with the shape { x: Number, y: Number }. The ship will always attempt to move towards this value by adjusting its orientation.

Update

The update function is the real meat of the enemy ship. First, we check to see if we are close to our target. If we are close enough, we consider our goal accomplished and we set a new target. Otherwise, we change our orientation so that we are flying toward our current target.

Here, x and y are really the distance between target and position along the respective axises. We want to know these values in order to calculate the distance between them. In general, you use the Pythagorean theorum to calculate distance. For deeper dive into the math, watch Distance Formula on Khan Academy. Finding the actual real distance uses a square root and calculating a square root is an expensive operation that’s best to avoid whenever you can.

We can bypass the need by working with the distance² (hence the variable name d2). We compare this against the hard-coded value of 16 (that’s 4²). In other words, if the distance between the ship and its target is less than 4 units we find a new target.

Once we’ve established what the ship’s target should be, we want the ship to move toward the target. As I’ve just mentioned, I’ve chosen to have the ship move at a constant speed. This means that it does not slow down or speed up. The only thing it can do is to change the direction it’s facing (orientation). These sort of constraints determine the personality and character of your game. Bear in mind, you don’t need to simulate the physics to have a fun game. Instead, you need to establish behaviors for your game entities that are merely fun. Fortunately, fun behaviors can often be easier to implement that the actual physics. I recommend taking a look at the demo and tweaking the turnSpeed and speed values to get a small taste for how the behavior can affect the game’s character.

In order to change the ship’s orientation we need to first determine where the ship ought to be facing. The values of x and y we just calculated can be interpreted as a vector. Meaning, it represents the direction and distance (magnitude) from the ship to the current target. To extract the actual angle (in radian) we use Math.atan2(x,y).

So now we have the direction the ship wants to face, angle, and the direction that it is facing, orientation. We calculate the difference between them and store it as delta.

The basic idea is that add the value of turnSpeed to orientation once each invocation of udpate until delta is 0 (meaning that the ship is flying directly at the target). However, some values of delta will cause the ship to “turn the wrong way”. For example, imagine that the ship is facing the top of the screen and that we’ve defined that as orientation === 0. Now, imagine that the target is directly to its right. The value of angle would be π/2 (or 90°). Adding turnSpeed to orientation each frame increments the value from 0 to π/2. However, if the target is directly to the left, then the value of angle would be 3π/2 (or 270°). Simply incrementing orientation would cause the ship to turn right and keep turning right. This is unintuitive behavior; we expect the ship to turn the shorted distance. In order to accomplish this, we translate any value of delta higher than π (180°) by subtracting fullCircle. This normalizes the value of delta between -π and π (or between -180° and 180°).

We take the absolute value of delta because otherwise we’d have to check for delta < -Math.PI as well. Also, we’ll use delta_abs again.

If delta is 0, we don’t need to change orientation. When it is different we need to modify the value of orientation.

First, we decide how much to change it using Math.min(turnSpeed, delta_abs). We could just use turnSpeed. However if we did it’s likely that delta would never quite be 0 and (depending on the size of turnSpeed) it could result is jittery motion. Secondly, we want to decided which direction to turn: positive values to the right and negative values to the left. We multiply the amount direction to change the sign, because direction will only ever be 1 or -1. Finally, we modulo orientation to ensure that it stays within a range of -2π to 2π. Otherwise, the calculation of delta would be off.

Our last step in update is to modifiy the actual position using the latest orientation and speed.

Some basic trigonometry is fairly fundamental for most game development. If you’re mathematically lost at this point, I recommend reviewing over at Khan Academey.

Here’s the geometric interpretation of the code. We want the ship to move a distance of speed in the direction of orientation. To do this, we need to project this vector (distance and direction) on the x and y axises. Since the distance is the length of the hypothenuse of right triangle, cosine gives us the x part and sine gives us the y part. We can then add these values to the current position.

Draw

Drawing the ship to the screen is a bit easier to follow. Here’s the flow of the logic:

  • Save the state of the drawing context.
  • Transform the context to make it easier to draw our ship.
  • Draw the ship.
  • Restore the context back to its original state.
  • Draw the target

Recall that ctx is the drawing context for the canvas. The context provide a useful API that allows us to move it around before we draw on it. This is analgous to having a sheet of paper that you might shift and rotate in order to make it easier to draw something complicated. This is the purpose of the translate and rotate methods.

First, we use ‘save’ to establishing a checkpoint for the drawing context that we can easily revert back to using ‘restore.’ The calls to translate and rotate modify the state of the drawing context. This modified state is very specific to the drawing of our enemy ship. If we didn’t translate and rotate the canvas, we’d have to do a lot more work to figure out where to draw the four corners of the rectangle.

I decided that I want my ship to be 6px long and 2px wide. Since I want the middle of the middle of my ship to be the point where it rotates, I shift by half the length and half the width. Hence, the values passed to ctx.fillRect(-3, -1, 6, 2). This point the new origin (0,0) at the middle of the rectangle, and it makes our call to rotate behave intuitively. If we used ctx.fillRect(0, 0, 6, 2) instead, then the ship would appear to rotate around its upper left corner. We’ll use these same techniques once we switch to using sprites.

After we restore the context’s state, we draw the target. We don’t bother using rotate because it’s meaningless to rotate a simple circle. Likewise, we don’t bother translate since the drawing logic is so simple.

The canvas is a broad topic in itself. I recommend taking a look at the tutorials over at MDN. A handy reference for the APIs themselves can be found on MSDN.

Comment on this post at dev.bennage.com
Discuss ()

Working on my first Pluralsight course – Html for the XAML Developer

Posted by Derik Whittaker, Friday, March 08, 2013 (3,851 views)

It’s official, I have been commissioned to author my first Pluralsight course and I am pretty excited.  My first course is going to be ‘Html for the XAML Developer’.  The objective for this course is to walk a XAML developer (Sliverlight, WPF, WP7, etc) through the process of porting a Silverlight application over to HTML.  I will accomplish this by breaking our reference application down into bit size chunks and rebuilding it in HTML.  In each step along the way I am going to compare our XAML code to our new HTML code in order to allow the view to understand how their existing knowledge can be applied to HTML.

In the course I am going to use the following tools:

  • jQuery
  • Knockout
  • Typescript
  • ASP.Net MVC
  • ASP.Net Web Api
  • Many, many others

 

Here is a screenshot of part of our reference XAML application

image

 

Here is what we expect to build via HTML

image

 

I am planning to have this course go live sometime in May so if your a pluralight subscriber please be sure to check it out when it does.

Till next time,

Discuss (11)

Knockout JS and mapping from Json to a custom object type

Posted by Derik Whittaker, Wednesday, March 06, 2013 (7,887 views)

One of the really cool features of Knockout js is the ability to take a raw json object, say from a web endpoint, and map it to an observable.  This is done via the mapping plug-in.

Take a look at the code below for an example

The magic above is the line ko.mapping.fromJS(item), this is what will take my json object and convert it to an observable.  Proof is below.

Below is the output via the Chrome Dev tools of our ‘item’ prior to mapping.  Notice we have raw properties.

image

 

Here is the output after the mapping, notice how now we have functions rather than properties.  This tells me I have a knockout observable.

image

There is one little issue here in the mapping above.  The issue is that the resulting type from the mapping is ‘object’.  Now this could be 100% ok but what if you want to custom object type for your binding.  Maybe you have computed properties you want to use as well.  Fortunately you can accomplish this via Knockout as well.

Assume I have this custom type as seen below (this is using TypeScript

How could I use Knockout mapping to returned a typed observable?

Turns out it is really simple.  The code below shows how

The ONLY difference in this code is in the ko.mapping.fromJs line.  Notice how I am passing in 2 extra arguments.  The 2nd argument is the one I want and this is the ‘target’ output type.

Now when I look at the output in the debugging tools I get what I want, a typed object being returned

image

So the trick to returned a typed observable is to use the overload of the .fromJS method.

Till next time,

Filed under: ,
Discuss (10)

Nuget Packages for Typescript Definition Files

Posted by Derik Whittaker, Sunday, February 24, 2013 (4,714 views)

If you have been using TypeScript you should be aware the definition file repository maintained by Boris Yankov called DefinitelyTyped.  This repository is awesome because it saves so much time and effort when working with 3rd party libraries with Typescript.

However, as great as this repository is it has always been painful getting the actual d.ts files for each library.  You would have to go to the site, navigate to the file, save the file and add it to your solution…. this sucked. 

If only there was a tool to help automate this?  Oh wait there is, it is called Nuget

I got the bright idea to start creating some Nuget packages around the d.ts files I am using so I posted them here.  The only problem with this is I was only creating the packages I cared about but more importantly I was creating these by hand and that is time consuming and I am lazy.

But yesterday I received some awesome news from Jason Jarret (aka @staxmanade) on twitter as seen below

image

This is awesome news.  Now all the d.ts files hosted in the DefinitelyTyped repository now have Nuget pacakges… w00t!

To see the list of Nuget packages follow this link.

Awesome work Jason,

Till Next Time,

P.S. I will be taking my nuget packages offline very shortly as they should not be used anymore.

Discuss (6)

Introducing Durandal

Posted by Rob Eisenberg, Monday, February 18, 2013 (8,230 views)

Today I'm very excited to officially bring to you Durandal!

Durandal is a new open source JavaScript library for rich client application development. It focuses on providing an enjoyable and productive developer experience centered around simple conventions and standard patterns like MVC, MVP and MVVM. Durandal is built on libs you know and love like jQuery, Knockout and RequireJS, so there's little to learn and building apps feels comfortable and familiar.

Here's a short list of it's features:

  • Clean MV* Architecture
  • JS & HTML Modularity
  • Simple App Lifecycle
  • Eventing, Modals, Message Boxes, etc.
  • Navigation & Screen State Management
  • Consistent Async Programming w/ Promises
  • App Bundling and Optimization
  • Use any Backend Technology
  • Built on top of jQuery, Knockout & RequireJS
  • Integrates with other libraries such as SammyJS & Bootstrap
  • Make jQuery & Bootstrap widgets templatable and bindable (or build your own widgets).

I'm also pleased to announce that I've been working with the ASP.NET team to bring Durandal to you as an ASP.NET MVC Template, released today and compatible with the new Web Tools 2012.2 release. You can grab the VSIX, install it and get started very quickly building rich web apps now. If using the VSIX isn’t your style, we’ve got several nuget packages available too. Finally, if you just love NodeJS, you might be interested in using our Mimosa skeleton.

To  learn more, please visit the official site, where you will find the getting started guide, documentation, videos, training and commercial support options.

Stay tuned. There's lots to say about Durandal and I look forward to sharing it with you in the coming weeks and months.

Discuss (22)

Entity Frame Performance Gotcha

Posted by Derik Whittaker, Tuesday, February 12, 2013 (7,380 views)

I was doing some profiling of our Entity Framework stuff via EFProfiler the other day and noticed something really odd.  When I was watching the profiler I noticed that I had a query returning back over 1300 results and that was NOT right, I had expected only 1 result.  I looked the resulting sql and immediately I ‘thought’ I knew the issue.  I thought the issue was that I had not setup my where clause correctly in my EF… Turns out I was both right and wrong at the same time.

Below is a sample of my EF code

** note that I replaced the dynamic variables w/ static for testing inside of LinqPad **

image

When I run these statements above and look at the resulting sql in LinqPad I would expect to see 2 queries.  Sure enough I did have 2 of them.  What shocked me was that the 2nd query ONLY did a where clause filter on ClientID (see below)

image

This had a resulting output of below, which is the expected result

image

But if you run the sql generated above (2nd statement) you actually get 1327 results.  This tells me that indeed the ENTIRE result for a client was being pull out of the DB, pulled over the wire and filtered down on the client…This is not good.

Now I tried a few different things to see if I could get different results such as doing a .FirstOrDefault rather than a .Where… No dice

Finally one of my coworkers found this Stack Overflow link which talks directly to this issue.

Turns out this behavior is by design and I had never noticed it before.  I (and 3 of my coworkers mind you) had just assumed that when EF did a lazy load off of a previously fetched IQueryable it would include any filter statements and pass those to the SERVER.  But because the .Images is NOT a IQuerable but rather an EntitySet<T> it did not work as expected.

To solve this issue I simply just changed my statement to go directly at my EF context for the ONE row I wanted w/ both keys (client and type).  This solved my issue as well as give me a pretty significant performance enhancement.

image

Long story short is that if you are going to lazy gather data in EF make sure you are doing your filtering on the server rather than the client and make sure you understand that an EntitySet does NOT do this only an IQuerable does this.

Till next time,

Filed under: , ,
Discuss (14)

Help I am getting an XMLHttpRequest exception of Access-Control-Allow-Orig

Posted by Derik Whittaker, Sunday, February 10, 2013 (4,460 views)

When working on a demo application recently I was trying to get an ajax call to hit one of my Web API routes and I was immediately hit with the following exception.

XMLHttpRequest cannot load http://localhost:33884/api/ToDo/. Origin http://localhost:3462 is not allowed by Access-Control-Allow-Orig

Of course this sucked because I KNEW what the issue was but not exactly how to solve it.  Well solve it the way I wanted.  Of course i could have just put both my sites (MVC project and WebAPI project) under the same web application in IIS to remove this but that was not an acceptable answer for my needs.

After a bit of searching online I thought I came across an solution that would work.  I thought that I could just set the crossDomain switch in my ajax call as below to get it to work, but no dice.

I found another suggestion telling me to change the dataType of request form json to jsonp as below, but as you may have guessed that did not work.

Finally at a bit more searching I found more information which suggested I needed to add a response header on the server side to allow ‘Access-Control-Allow-Origin’ and this Stack Overflow answer gave me all the details needed to make this happen in Web API.  Once I implemented the solution inside my WebApi endpoints and REMOVED the 2 un-needed attributes in my .ajax call the world was a happy place and I was able to make cross domain calls to my other services.

Till next time,

Discuss (10)

How to use the Accelerometer in Windows 8 C#/XAML Applications

Posted by Derik Whittaker, Sunday, January 27, 2013 (5,665 views)

This post is part of a mulit-part posting series on how to use some of the onboard device sensors in Windows 8 applications.  Other posts are:

Most tablets and laptops these days have an array of sensors onboard the device that developers can use and take advantage of. One of the sensors which is on most tables and laptops is the Accelerometer Sensor.  The Accelerometer sensor can be used to get a acceleration force of the device on the x y and z axis, or basically measure how fast it is moving in any given direction.  With the Accelerometer you could build interesting augmented reality applications which react to the forces of the device.  In this post we are going to take a look at how to use the Accelerometer Sensor from within your C#/XAML Windows 8 application.

How to get access to the Inclinometer

In the above code what we are doing is making the call to get the Default sensor, this is the sensor on the device.  If there is NO sensor on the users device it will return a NULL instance which is why we are checking for null.  Make sure you do the same in your code

Register to receive event updates when the Accelerometer values change

In the above I am either registering for an event or unregistering.  The event is what will give us the updated values as they change based on the movement of the users device.

Doing something useful with the sensor readings

In the above I am doing 2 things of note:

  1. I am using a CoreDispatcher (you can get this from Window.Current.Dispatcher) in order to message the results back onto the UI thread.  If you do not need to message back to the UI thread you will NOT need this
  2. I am getting the current reading for each axis via the .Reading property of the event argument.  It is here you could do something useful with the reading.

Apart from being able to get the changed events for the Accelerometer you can also detect if the device has been shaking by listing to those events as well.

Register to receive event updates when the Accelerometer shaek change

In the above code I am wiring an event to tell me each time the Accelerometer notices the device has been shaken.

Handle the Shaken Event and do something.

In the above code I have received the Shaken Event and I am simply updating a counter.  Of course in a real world app you would want to do something a bit more exciting, but this gets the point across.

As you can see working with the Accelerometer sensor is not too hard and can lead to some pretty useful features in your application.

Till next time,

Filed under: , , ,
Discuss (11)

Handling Resuming in your Windows 8 Applications

Posted by Derik Whittaker, Saturday, January 26, 2013 (5,483 views)

Windows 8 applications (aka Windows Store applications) have 3 different life cycle states they can go through:

  1. Launching
  2. Suspending
  3. Resuming

Handling both Launching and Suspending is pretty much covered out of the box but what if you need to resume from a suspended state?  In most normal scenarios you should not have to do too much here because the built in SuspensionManager (this is generated code, not framework code) will handle putting your application back together in terms of what page your user was on and how the page/screen was populated when it was suspended.

However, if you are using data which is gathered from a remote source such as a web service you may want to refresh your application when it is resuming from suspension.  But how exactly can we accomplish this?

Hooking up the Resuming Event

You need to wire up the .Resuming event inside your App.cs class.  By default the template only wires the Suspending event as it is used in almost every application.

Handling the Resuming Event

As you can see above it does take some effort to get to your underlying viewmodel in order to make the Resume() call but it is well worth it.

We first need to get the current frame.  Once we have the frame we want to check to ensure it is of the correct type in order to further check its underlying data context.  Finally we want to check out data context to ensure it is of the correct type.  Doing this final  check will safe guard us and allow us to only make the resume calls on pages which require it.

Doing something useful in our Resume() call

In the Resume() is where you would need to handle any remote data fetching or updating of existing data.

Defining our IResumable interface

Our above interface is small, but it does the trick.  It allows us to identify which pages need to be resumed and enables a way to make the call

As you can see handling the Resuming event in a Windows 8 application is not hard, however getting to your underlying data context does take a bit of work, but this work is well worth it in my opinion.

Till next time,

Filed under: , , ,
Discuss (6)

How to use the Inclinometer sensor in Windows 8 C#/XAML applications

Posted by Derik Whittaker, Wednesday, January 23, 2013 (4,992 views)

This post is part of a mulit-part posting series on how to use some of the onboard device sensors in Windows 8 applications.  Other posts are:

Most tablets and laptops these days have an array of sensors onboard the device that developers can use and take advantage of. One of the sensors which is on most tables and laptops is the Inclinometer Sensor.  The Inclinometer is a sensor which allows you to measure the movement of the device in terms of Pitch, Roll and Yaw, or more simply rotation of the device on the X, Y and Z axis.  With the Inclinometer you could build interesting augmented reality applications which react to the movement of the device.  In this post we are going to take a look at how to use the inclinometer Sensor from within your C#/XAML Windows 8 application.

How to get access to the Inclinometer

In the above code what we are doing is making the call to get the Default sensor, this is the sensor on the device.  If there is NO sensor on the users device it will return a NULL instance which is why we are checking for null.  Make sure you do the same in your code

Register to receive event updates when the Inclinometer values change

In the above I am either registering for an event or unregistering.  The event is what will give us the updated values as they change based on the movement of the users device.

Doing something useful with the sensor readings

In the above I am doing 2 things of note:

  1. I am using a CoreDispatcher (you can get this from Window.Current.Dispatcher) in order to message the results back onto the UI thread.  If you do not need to message back to the UI thread you will NOT need this
  2. I am getting the current reading for each axis via the .Reading property of the event argument.  It is here you could do something useful with the reading.

As you can see working with the Inclinometer sensor is not too hard and can lead to some pretty useful features in your application.

Till next time,

Filed under: , , ,
Discuss (9)

How to use the Gyrometer Sensor in Windows 8 C#/XAML applications

Posted by Derik Whittaker, Monday, January 21, 2013 (18,022 views)

This post is part of a mulit-part posting series on how to use some of the onboard device sensors in Windows 8 applications.  Other posts are:

  • Light Sensor
  • Gyrometer Sensor (this post)
  • Inclinometer Sensor (future post)
  • Accelerometer Sensor (future post)

Most tablets and laptops these days have an array of sensors onboard the device that developers can use and take advantage of. One of the sensors which is on most tables and laptops is the Gyrometer Sensor.  The Gyrometer sensor can be used to get a angular velocity of the device on the X, Y and Z axis.  In this post we are going to take a look at how to use the Gyrometer Sensor from within your C#/XAML Windows 8 application.

How to get access to the Gyrometer

In the above code what we are doing is making the call to get the Default sensor, this is the sensor on the device.  If there is NO sensor on the users device it will return a NULL instance which is why we are checking for null.  Make sure you do the same in your code

Register to receive event updates when the Gyrometer values change

In the above I am either registering for an event or unregistering.  The event is what will give us the updated values as they change based on the movement of the users device.

Doing something useful with the sensor readings

In the above I am doing 2 things of note:

  1. I am using a CoreDispatcher (you can get this from Window.Current.Dispatcher) in order to message the results back onto the UI thread.  If you do not need to message back to the UI thread you will NOT need this
  2. I am getting the current reading for each axis via the .Reading property of the event argument.  It is here you could do something useful with the reading.

As you can see working with the Gyrometer sensor is not too hard and can lead to some pretty useful features in your application.

Till next time,

Filed under: , , ,
Discuss (8)

Caliburn.Micro v1.4.1 Released

Posted by Rob Eisenberg, Sunday, January 20, 2013 (8,574 views)

I’m labeling this the  Thomas Ibel/Nigel Sampson release. Why? Because these two hardworking gentlemen have put great effort into bringing you the most mature version of Caliburn.Micro yet. In the two months since our 1.4 release they’ve dealt with almost every outstanding issue on our list. Great work guys! In addition to bug fixes, there’s been some minor enhancements, we’ve synced up the latest WUI library and added official support for WPF 4.5. You can get it on Nuget now. Enjoy!

On Testing: Why write tests?

Posted by Krzysztof Koźmic, Saturday, January 19, 2013 (6,181 views)

This post is secod part of my Back to basics: on testing series.

Developers writing tests

People new to software, or coming from organizations where all testing is done by dedicated people often find the idea of developers doing testing bizarre.

After all, we're the highly trained, educated professionals. We get payed to do the hard bits. Clicking around the UI to see if a label is misaligned or an app crashed surely should be delegated to somebody else, outsourced even.

Truth is, there are various kinds of tests, and while there is value in UI tasting (automated or not) we'll concetrate at somethig else first.

You write the tests for your future self

The idea of developers writing tests came not from academia but from the field. From people who spent years developing successful software. And as you get out there, and start working with teams of people, on real life big systems that solve real problems, you realise that some things you belived (or in fact were taught) to be true, are not.

We'll get into the details as we progress with this series, but let's start with the biggest one:

The code is written, and read, and read, and read and read some more and modified, and read, and modified again, and read some more again and then few months later read yet again and again

You may notice there's much more reading than writing there. That is true for most code - you don't just write and forget it, like is the case with coding assignments at unversity. Real-life code is long lived, often expanded and modified and commonly the person doing the expanding is not the person who originally wrote the code. In fact the original author may have already moved on to work elsewhere.

  • How do you know what the code does?

  • How do you know where to make the change?

  • How do you know your change didn't break any of the assumptions that code interacting with the bit you changed makse about it?

  • How do you know the change you made works the way you wanted it to?

  • How do you know the API you created (in other words the public methods) are easy to use and will make sense to the other developers using it (that may also be you few weeks from now!).

These are the reasons for writing tests. Tests are the most economical way of ensuring the change you will make two months from now fit in the design constrants you designed today. Tests are the fastest way for other developers (or again, future you) to get a feel of how a piece of code works; what it does, and how you're supposed to use it.

Don't just take my word for it

In the next part of the series we'll start looking at actual code, writing some tests, and explaining the concepts around them.

Until then, if you have any questions, or suggestions as to what to cover in future posts of the series, feel free to leave a comment.

Filed under: ,
Discuss (0)
More Posts « Previous page - Next page »

About The CodeBetter.Com Blog Network
CodeBetter.Com FAQ

Our Mission

Advertisers should contact Brendan

Subscribe
Google Reader or Homepage

del.icio.us CodeBetter.com Latest Items
Add to My Yahoo!
Subscribe with Bloglines
Subscribe in NewsGator Online
Subscribe with myFeedster
Add to My AOL
Furl CodeBetter.com Latest Items
Subscribe in Rojo

Member Projects
DimeCasts.Net - Derik Whittaker

Friends of Devlicio.us
Red-Gate Tools For SQL and .NET

NDepend

SlickEdit
 
SmartInspect .NET Logging
NGEDIT: ViEmu and Codekana
LiteAccounting.Com
DevExpress
Fixx
NHibernate Profiler
Unfuddle
Balsamiq Mockups
Scrumy
JetBrains - ReSharper
Umbraco
NServiceBus
RavenDb
Web Sequence Diagrams
Ducksboard<-- NEW Friend!

 



Site Copyright © 2007 CodeBetter.Com
Content Copyright Individual Bloggers

 

Community Server (Commercial Edition)