Easy error tracking in your applications

Posted by Filip Ekberg on March 26 2013 11 Comments

Over and over again I see developers re-implementing error tracking, I’ve been there myself. One of the reasons to this I think is because many of the tracking tools out there add too much noise and are just cumbersome to use. In many cases the biggest problem is that you need error logging too late, meaning that you want the logging once the error has already occurred. It’s of course cleaver to say that you should always think about potential errors from the start, because let’s face it we all write applications that may have unexpected exceptions.

Another problem is that if we do decide to log errors in our applications, where do we store them and how do we collect the logs? Luckily there’s tools out there that can help us on the way. One that I most recently came across called Raygun. Raygun is a product from the company Mindscape that have some very interesting products in their family.

Error handling just got awesome!

The punch line of Raygun is quoted above, a tool that makes error handling awesome. Let’s clear something up right before we take a look at Raygun , there are multiple providers supplied for Raygun: JavaScript, .NET, Java, PHP and Cold Fusion. Didn’t find the language you work with? Don’t worry, there’s a REST API for you RESTafarians!

So there are providers for Raygun, but what does it actually do?

Imagine that you have your web application written in PHP, ASP.NET or just something that is using JavaScript. Now you want some centralized place where you can store errors in either of these applications, be it severe exceptions or just notices about something unexpected.

If you’ve found yourself writing an error tracker where you just dump the Stack Trace and the exception message into a database, then this is certainly something for you. Imagine that if your customer calls up and says that he recently got the yellow screen of death but don’t know what he was doing or really exactly what time it was.

Now imagine that you were to access your centralized error tracker and you’d have all of the information that you would need to find the error in the code base including:

  • Time of error
  • How many times the current error have occurred
  • Information about the system the user is using
  • The exception message
  • A Stack Trace

That is Raygun! A way to track your errors in a very easy way and the presentation is just beautiful.

The information you’ll get out of each error report of course depends on the data that you supply Raygun with. Take a look at the REST API to get an idea of all the data that you possibly could supply Raygun with.

Enough with what, let’s look at the how! Let’s look at some code!

For this demo I’m going to setup 2 things an ASP.NET MVC 4 Application and a Class Library that will simulate a data store where I can search for people. The web front will allow me to search for people inside my collection and when I wrote this example Raygun actually helped me detect one of the errors I were getting, let’s call this “TrackCeption”.

First of all let’s look at the library. There’s a very easy class that represents the person, it simply has a property called “Name” inside it.

public class Person
{
    public string Name { get; set; }
}

Secondly there’s a class that handles the search requests, I call this RequestHandler. To set this up we need to create a new list of people, in this case it’s just going to be a static collection of people as you can see here:

private static IEnumerable<Person> _people;
public RequestHandler()
{
    _people = new Person[] {  
            new Person { Name = "Filip" },
            new Person { Name = "Sofie" },
            new Person { Name = "Johan" },
            new Person { Name = "Anna" },
        };
}

Now we need a way to retrieve all these people and I like creating asynchronous methods where the operations might be time consuming and in this case I know that it will take 2 seconds to retrieve the list of people:

public Task<IEnumerable<Person>> GetPeopleAsync()
{
    return Task<IEnumerable<Person>>.Factory.StartNew(() => {

        Thread.Sleep(2000);

        return _people;
    });
}

This leaves us with implementing a method that lets us search for people in the collection. So far we don’t care if the list has been empty or not but when we search we want to report an error when there’s no people in the list. Let’s just assume that this is an exception in the application and the end user will always search for people that are in the list.

Let’s install Raygun!

Installing Raygun is as easy as saying “I’ll soon blast all my errors with this Raygun!”; simply bring up the NuGet package manager and write the following:

PM> Install-Package Mindscape.Raygun4Net

This will install Raygun into your class library! There’s a couple of more things that we need to do in order to get Raygun up and running:

  • Create an account and an application at Raygun.io
  • Add the API Key to your application

Creating a Raygun account is free for 30 days and you’ll need to do it in order to start tracking your errors. Once you’ve setup an application on Raygun you can retrieve the API Key from the “Application Settings” menu like you can see in the following image:

RaygunAPIKey

We don’t need to add the API Key just yet, we’ll add that in the application configuration file of the project that will use our library later on (in this case the MVC 4 project).

Now, bringing in Raygun into our application using NuGet will allow us to write the following:

new RaygunClient().Send(new Exception(string.Format("People with name `{0}` not found", name)));

That will create a Raygun client and send a new exception with the message you can see to the Raygun servers and passing it the API Key that we will provide later on. So let’s take a look at how the method that will find people in the colleciton will look like. This one also takes 2 seconds to execute so we will have this one asynchronous as well, we don’t need to do it but I take every chance I got to play with asynchronous programming.

public Task<IEnumerable<Person>> FindPeopleAsync(string name)
{
    return Task<IEnumerable<Person>>.Factory.StartNew(() =>
    {
        Thread.Sleep(2000);

        var people = _people.Where(x => x.Name.Contains(name)).ToList();

        if (people == null || !people.Any())
        {
            new RaygunClient().Send(new Exception(string.Format("People with name `{0}` not found", name)));
        }

        return people;
    });
}

The method will look for people with the name of the value that we passed to the method and if there’s no people found it will send this notice to Raygun. You might think to yourself that this isn’t really a good exception at all, but for the purpose of the demo, let’s just look pass that. Also a bird whispered into my ears that Mindscape is working on adding other message types than exceptions to Raygun, but that’s in the future.

This leaves us with a structure looking like the following:

RaygunDemoLibrary

We are now ready to use our library!

Create a new ASP.NET MVC 4 Application, I named mine RaygunDemo. The first thing that we are going to do is to add Raygun to this project as well, install it into the ASP.NET MVC 4 project using NuGet as we did before and open up web.config once this is done.

In order for us to get Raygun working we need to add our API Key. To do this we first need to add an element inside <configSections>:

<section name="RaygunSettings" type="Mindscape.Raygun4Net.RaygunSettings, Mindscape.Raygun4Net"/>

This will allow us to add a configuration like this:

<RaygunSettings apikey="YOUR_API_KEY_HERE" />

It should look something like this in your web.config, with a lot of extra stuff as well of course:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <section name="RaygunSettings" type="Mindscape.Raygun4Net.RaygunSettings, Mindscape.Raygun4Net"/>
  </configSections>
  <RaygunSettings apikey="YOUR_API_KEY_HERE" />
</configuration>

Remember I said that Raygun helped me find an exception in my application when setting up the demo application? This is because I told Raygun to submit all the application errors. In the ASP.NET MVC 4 project, open up Global.asax and add the following method, this one will be run every time there’s an error in the application:

protected void Application_Error()
{
    var exception = Server.GetLastError();
    new RaygunClient().Send(exception);
}

This means that every time that we get an application error Raygun will be noticed of this and the entire Stack Trace, Computer info and such will be passed into Raygun!

All there’s left to add now is the Home controller and the view, the Home controller consists of two asynchronous actions that will use the library we just created. One will return a view and the other will return a Json result:

public async Task<ActionResult> Index()
{
    var requestHandler = new RequestHandler();
    var people = await requestHandler.GetPeopleAsync();

    return View(people);
}
public async Task<JsonResult> Search(string search)
{
    var requestHandler = new RequestHandler();
    var people = await requestHandler.FindPeopleAsync(search);
           
    return Json(people);
}

The view is equally simple, it only has a text box that allows us to search for names and then it has a list that shows all the people. Once a key is pressed inside the text box an event is fired that requests the people that have a name containing that part:

@model IEnumerable<RaygunDemoLibrary.Person>

<div>
    <span>Search: </span>
    <span><input id="search" type="search" /></span>
</div>
<h2>People</h2>
<div id="people">
    @foreach (var person in Model)
    {
        <div class="person">
            <span>@person.Name</span>
        </div>
    }
</div>

@section scripts{
    <script>
        $("#search").keyup(function () {
            searchValue = $("#search").val();
            $.post("/Home/Search", { search:  searchValue}, function (data) {
                var peopleDiv = $("#people");
                peopleDiv.html("");
                data.forEach(function (person) {
                    name = person.Name.replace(searchValue, "<strong>" + searchValue + "</strong>");
                    peopleDiv.append("<div class='person'><span>" + name + "</span></div>");
                });
            });
        });
    </script>
}

If I start this and search for a name that exists and one that doesn’t it will look like the following:

RaygunReportError

Funny thing is that we didn’t actually notice anything when we searched for something that didn’t exist. So how do we know that this worked?

Raygun comes with an Amazing dashboard that will give you an overview of everything including all the recent errors, how many errors/ignored errors you have and much more like you see in this image (click to enlarge):

RaygunReport

Finally this is what it looks like when you go into details about an exception, you’ll have a graph over how many times and when it occurred and then you have very much details that will help you Raygun the errors!

RaygunStackTrace

If you’re unable to add code to your current website you can simply add a HTTP Module and a config value! Which means you could simply add this in your web.config provided you have the dll as well of course!

<httpModules>
  <add name="RaygunErrorModule" type="Mindscape.Raygun4Net.RaygunHttpModule"/>
</httpModules>

I really recommend giving Raygun a try! Let me know what you think of it and if you have any alternatives that are equally awesome!

Vote on HN

2012 was an amazing year, here’s a summary!

Posted by Filip Ekberg on January 8 2013 1 Comment

Saying that a lot happened in 2012 is probably an understatement. At least both on this blog and in my personal life, a bunch of amazing things have happened. I really hope that your previous year was good and let’s hope for an even better 2013. To start this year off I want to summarize all the great posts that were shared on this blog in 2012.

Personally the two biggest achievements of last year was me getting engaged to my lovely Sofie and publishing my book C# Smorgasbord. As you might have seen already this year has already started very good as I have been awarded Microsoft MVP in Visual C#!

Let me know what you found most interesting on this blog from the collection of posts below! Here is the 2012 summary!

Architecture

Tips & Tricks

Screencasts

Software & Tool information

Windows 8, Windows RT, WinRT and Surface

C# Smorgasbord and Self-publishing

Other

I hope you found this collection of posts useful and that you’ve learnt a lot in 2012! Enjoy 2013 and let me know what you think of the posts! Before we take part for this time, I want to share with you an image that describes the feeling I got when I held the first printed copy of C# Smorgasbord:

Vote on HN

Introduction to SignalR – Creating a Cross-Platform game

Posted by Filip Ekberg on November 29 2012 5 Comments

Have you had a chance to play with SignalR yet? If not, you’re really missing out! While preparing for a Swedish .NET User Group presentation, I did a test screencast on all my content that was going into the presentation. This screencast is uploaded to youtube so go check it out! It’s a bit over 1 hour long but well worth it if you want to get started with SignalR or just get some new inspiration!

Vote on HN

Microsoft delivers at BUILD 2012

Posted by Filip Ekberg on November 1 2012 1 Comment

Yesterday was the first day of //BUILD/ at Microsoft Campus in Redmond, Seattle. There has been a lot of expectations on Microsoft for this event and boy did they deliver! The past year has been all about Windows 8, Windows Phone 8 and the very awesome updates to Windows Azure. //BUILD/ this year follows in its predecessor´s footsteps and deliver information about how we can write awesome applications for both Windows 8 and Windows Phone 8.

Me and my colleague from Star Republic arrived in Seattle a couple of days before the conference started to avoid being jetlagged during the session and be able to see a bit of Seattle. Despite all the rain in Seattle we have had a very nice visit so far. We’ve been able to see the Space Needle, the underground (which is awesome by the way), the harbor and much more. I really enjoy Seattle, maybe it is because it feels pretty much like Gothenburg. What’s best about it though is that it is flooded (not with water despite the rain) with geeks.

The days before the conference I had a chance to meet up with Scott Hanselman and a lot of the other amazing guys working on the ASP.NET team. If you haven’t seen the Day 2 Keynote the next part of this sentence is going to be a spoiler; I’m somewhat in the keynote! When I met Scott he needed material for his presentation, me and some other guys’ danced Gangnam style for him which was recorded and put in his and Scott Guthrie’s presentation. I don’t have the video available at the moment, it’s going to be available on C9 as soon as the keynote is uploaded. I recorded a little with my compact camera, but I forgot to bring a cable for it and unfortunately the Surface RT don’t accept an SD card!

All that was day two, besides for the actual recording, so up until now everything has been awesome. The sessions were all similar to the ones that we have seen over the year since last //BUILD/ but now that everything is shipped it’s more hands-on examples. I attended a couple of sessions about Windows 8 development with HTML and Javascript (and of course CSS). The most interesting session was the one about optimizing your web application by thinking about CPU usage. There are some very interesting tools in the Windows SDK that you can use to analyze the performance of a web application. Basically in most applications on the web, time is spent on waiting for resources to be downloaded which means it could be done asynchronously if possible and the other thing that is common is slow javascript with lots of DOM access.

As an attendee the highlight of the day was when Ballmer announced that everyone is getting 100GB of SkyDrive! I am actually going to swap from DropBox for a while to see if it is better or not. However that awesome present wasn’t enough for Ballmer so he also announced that everyone attending would get a Surface RT 32GB! When everyone calmed down and promised to write awesome apps for Windows RT, the VP for Nokia comes out on stage and gives away a Lumina 920 to everyone attending the confidence. At this time I wanted to lay down on the floor and cry of happiness. This was announced in the morning so we had to wait for our awesome devices for the entire day!

As soon as we picked up our stuff we went back to the hotel and I recorded an unboxing (I know most people hate those!) and hands-on.

Are you planning on getting a Surface?

I’m having high hopes for the ASP.NET session and hoping to see some things that will help me in my daily work. So far the Azure upgrades with Mobile Services and Add-Ons are Very promising and I am really looking forward to playing with it more. What is funny is that Halo 4 that is being release in the next months or so uses Azure a lot which forced them to rethink the server architecture.

Speaking of games, since everyone got a voucher for the company store which has heavy discount, I might grab an xbox controller to use for my next Windows 8 game. Do you have any experience with that? I would love to hear about it!
If you’re at //BUILD/ be sure to look me up and say hello and if not, just ping me!

Before we take part, I just want to say that I wrote this entire post on my Surace with the TouchCover. Takes some time getting used to.

Vote on HN

10 questions about Surface

Posted by Filip Ekberg on October 17 2012 4 Comments

The Microsoft Surface is due to be released October 26, 2012 and this is less than 10 days from now. There’s been a lot of hype around this particular tablet and I’m very happy that the release date is in just 1½ weeks!

Some background

If you’ve somehow missed what the Surface is or what the Surface looks like, below is a very nice picture of it. Basically it’s a powerful and lightweight tablet that runs Windows 8.

Up until today, at least I have always felt that I at least needed 3 devices. One touch optimized tablet (iPad), One laptop to bring in to meetings that I can also code on and last but not least a very powerful workstation that I can work on. With the Microsoft Surface, we’re closing up with the all-in-one device — simply bring the Surface with you to meetings, watch movies with it in the couch or work on it.

How come information about such hardware ends up on a programming blog? Because the programming model is very interesting! If you’re an iOS developer or an Android developer, you’re most likely familiar with the whole “store” life-cycle; which is great. This will (hopefully) lead to much more high quality applications and less bogus software.

Surface comes in two (majorly) different models

The first Surface that is released October 26 will run Windows RT on an ARM architecture. The RT version of Windows 8 is designed for limited use such as:

  • Watching movies, surfing the web, chatting and all that other tabletty stuff
  • Minor work in Office; Word, Excel, Powerpoint, etc.
  • Only run applications from Windows Store

There’s of course a little more to it, but the last point is the most interesting one. You’ll only be able to run applications on the device that comes from Windows Store! Hence that you will not be able to put an application on an USB drive (yes Surface has a fully functional USB 2 port) and run it.

This might not be new information to you, but it’s still pretty interesting. That’s why there’s another Surface version released in January, called Surface Pro. This version runs on an Intel Core i5 and used the full version of Windows 8. This lets you install any applications that you want and use it as any other computer that you are used to. Plus it’s still a tablet!

Below is an overview of the Windows RT Architecture; The RT API is a little bit different (limited).

Now with a little bit of background, let’s take a look at 10 questions and answers about the Surface!

All the following information is based on information given by the SurfaceTeam on reddit.

1. Why doesn’t surface come with 3G/4G

For 3G/4G we looked at several elements when deciding on what features to include. We knew that the primary use was going to be in the home, we looked at tablet sales data 2/3 WiFi, 1/3 Mobile Broadband. Of the 1/3 sold, 1/2 were activated. Phone hotspot / tethering use was also a consideration.

2. Will Surface be available in any other countries than listed at the moment on the release date?

Unfortunately, no.

Of the primary launch Markets we are launching in, we have keyboards specific to those languages
We are not announcing any new markets beyond what we said today. However, we will for sure be expanding to more markets in the future.

3. Why is there no USB3 port, only USB2?

Currently there’s no ARM SoCs that have an USB 3 controller and Surface is based on ARM, which means no USB 3.

USB 2.0 based on capability of the ARM SoCs during our development timeframe.

4. How much will it cost?

There are a couple of different options available (USD prices only).

  • Surface with 64GB Storage and TouchCover – 699 USD
  • Surface with 32GB Storage and TouchCover – 599 USD
  • Surface with 32GB Storage without TouchCover – 499 USD

5. Is there any NFC or GPS on Surface?

There isn’t a NFC feature in Surface RT; We use Wi-Fi based location services, the device doesn’t have a physical GPS sensor.

6. Why is the kickstand angled as it is?

We wanted the screen to be normal to the face. Voila, you then have a 22 degree angle.
Seriously we did a ton of studies around lighting, reflection, ergonomics, table height, etc…. and then made sure it looked perfect and felt perfectly balanced.

7. Will Surface support bluetooth headsets?

Yes, Surface supports Bluetooth 4.0 and will work with Bluetooth headsets.

8. What happens when I flip the touch cover to the back of the device, will there be accidental keystrokes?

Both TouchCover and TypeCover have sensors that understand orientation relative to Surface… in fact the Type and Touch Covers talk to Surface to figure out their relative position no matter the orientation of gravity of the device (pretty neat!). There are 3 positions modes: Closed (keys and mouse are off), Open to 180 degrees (keyboard and mousepad on), beyond 180 degrees to the back (keys and mouse off). That way you can flip back the covers and feel secure you are not pressing keys by mistake.

9. How does the TouchCover work?

Touch Cover has a very special digitizer that we invented.. it senses the impact force of your key presses. We designed super-fast electronics and smart algorithm in the keyboard so that Touch Cover can profile your key press down to a 1ms (1000 times a second). Using that information Touch Cover can infer if the user meant to press the key or not.. It is a smart key. So even though there is no key travel, the user can rest their hands on top of the keyboard and find home position without accidentally triggering keys.. pretty cool! The first time I typed on a full working version of Touch Cover, I typed just as fast as I do on a normal keyboard. I am confident you will be able to type significantly faster on Touch Cover than an onscreen keyboard. And with a little practice you will even do better (maybe even faster!) For folks who really love and really need keys that have travel, then Type Cover is one of the best keyboards I have ever used (desktop or other). It has a super awesome snappy key mechanism that feels great (has a strong hysteresis curve)

10. So there’s no NFC, why?

For the product design experience we were aiming for with Surface, the Mg metal enclosure, including the back case, was critical. This made good antenna design for NFC a trade-off in our development process.

To learn more about Surface, check out the video below!

Personally I can say that I am very excited about the Surface products, both RT and Pro.

How excited are you?

Vote on HN

Creating a Direct2D game for WinRT

Posted by Filip Ekberg on October 1 2012 7 Comments

If you want to write a game for Windows 8 and was thinking of using XNA, think again. When creating games for Windows 8 you’ll have to go back to using DirectX. But don’t worry, with Visual Studio 2012 on Windows 8, you’ll get a lot of help doing so. Let’s have a look on how to create a Direct2D game for WinRT!

The first thing we would have to do is to fire up Visual Studio and create a new Direct2D project. Can’t find it in the C# section for Windows Store applications? That’s because we’ll have to use C++ for this! You’ll find the project template in Other Languages -> Visual C++ -> Windows Store -> Direct2D App (XAML):

When the project is created, we will have a lot of sample files in our solution. As you can see, there are also XAML files in the project! We’ve got the App.xaml that will tell us which the default view is, which in this case will be DirectXPage.xaml. Let’s run it in a simulated mode and see what this default code gives us. With Visual Studio 2012 we get a very handy simulator, to run the application inside it, simply change the target from Local Machine to Simulator:

This will bring up the simulator and the application that we got by default will let us drag around the title and if we right click the surface, we get an app bar that will allow us to change the background:

Here’s a small video on YouTube showing what this looks like when it’s running:

What’s interesting about this demo is that it combines XAML, C++ and Direct2D. The text in the center that says “Hello, XAML!” is actually just a normal XAML TextBox:

<TextBlock x:Name="SimpleTextBlock" HorizontalAlignment="Center" FontSize="42" Height="72" Text="Hello, XAML!" Margin="0,0,0,50"/>

The TextBox lives inside a content panel called SwapChainBackgroundPanel and this is something new. According to MSDN, this panel will only be used when we interop with DirectX:

Implements a XAML layout surface target for Microsoft DirectX interoperation scenarios. This panel has some atypical restrictions on its usage within an app window; see Remarks.

MSDN also says that this only applies to Windows Store applications.

We’re getting a lot of DirectX code free here which we don’t have to write ourselves. What we do want to take a look at though is the SimpleTextRenderer. This class handles drawing the text “Hello, DirectX!” on the screen. It inherits from the DirectXBase class which will do all the DirectX magic.

Have a look in the method SimpleTextRenderer::Render(), if we were to add a rectangle instead of the text, like this:

auto rect = D2D1_RECT_F();
rect.bottom = 100.0f;
rect.top = 0.0f;
rect.left = 0.0f;
rect.right = 100.0f;

m_d2dContext->DrawRectangle(rect, m_blackBrush.Get());

We could run the application and it would look like this:

Now, try to move the rectangle around, notice that it moves around just like the text we had before did? That’s magical! Actually, it’s just a transformation going on; the Direct2D context is transformed and the area is moved to wherever the mouse was. These are the lines in that method which changes the transformation:

Matrix3x2F translation = Matrix3x2F::Translation(
    m_windowBounds.Width / 2.0f - m_textMetrics.widthIncludingTrailingWhitespace / 2.0f + m_textPosition.X,
    m_windowBounds.Height / 2.0f - m_textMetrics.height / 2.0f + m_textPosition.Y
    );
m_d2dContext->SetTransform(translation * m_orientationTransform2D);

If we simply comment these out, we’ll see a completely different result. You should now see the rectangle at the top of the screen being 100 pixels wide and 100 pixels high:

Now to make this a bit more interesting, let’s make the box move around a little bit. In order for it not to rely on the point & move event, we need to go back to the DirectXPage and remove something from the event handler DirectXPage::OnRendering. As it is now, it checks if it needs to be rendered by falling back on a boolean variable, but this bool is only set to true when we’ve moved the mouse (or finger) around. That means that the event handler should look like this instead:

void DirectXPage::OnRendering(Object^ sender, Object^ args)
{
    m_timer->Update();
    m_renderer->Update(m_timer->Total, m_timer->Delta);
    m_renderer->Render();
    m_renderer->Present();
    m_renderNeeded = false;
}

In order for the box to actually move around, we need to change a couple of things in SimpleTextRenderer::Render as well as in SimpleTextRenderer::Update. First we need to introduce a couple of global variables, I’ve called them x and y. These two variables will be in charge of telling us where the rectangle should be drawn on the screen. This means that SimpleTextRenderer::Render can look like this:

float x = 0.0f;
float y = 0.0f;
void SimpleTextRenderer::Render()
{
    m_d2dContext->BeginDraw();

    m_d2dContext->Clear(ColorF(BackgroundColors[m_backgroundColorIndex]));

    auto rect = D2D1_RECT_F();
    rect.top = y;
    rect.left = x;
   
    rect.bottom = rect.top + 100.0f;
    rect.right = rect.left + 100.0f;

    m_d2dContext->DrawRectangle(rect, m_blackBrush.Get());

    HRESULT hr = m_d2dContext->EndDraw();
    if (hr != D2DERR_RECREATE_TARGET)
    {
        DX::ThrowIfFailed(hr);
    }

    m_renderNeeded = false;
}

There’s a second pair of global variables that I want to add at this point, these will tell us in which direction the rectangle should be moving. As you might have figured out, I want to make the rectangle bounce around the window!

float x_direction = 1.0f;
float y_direction = 1.0f;

Last but not least, I want to make some changes to SimpleTextRenderer::Update, since this is where we get information about the delta time, the time since the last frame was updated. Basically I want to increase both x and y with timeDelta * 200 and then multiply that with the current direction of which we’re moving the rectangle.

When bouncing something around, we need to know the bounds of the window so that the rectangle does not exit outside the window. Luckily for us, the class that we’re inheriting from has a member variable called m_windowBounds which is a rectangle that tells us the current window bounds.

We can use this rectangle to check if we’re outside of the bounds and then we also need to check that we don’t reach below 0 in either x or y direction. This leaves us with a method looking like this:

float x_direction = 1.0f;
float y_direction = 1.0f;
void SimpleTextRenderer::Update(float timeTotal, float timeDelta)
{
    x += (timeDelta * 200) * x_direction;
    y += (timeDelta * 200) * y_direction;

    if(x > m_windowBounds.Width - 100.0f || x <= 0) {
        y_direction *= 1.0f;
        x_direction *= -1.0f;
    }
    if(y > m_windowBounds.Height - 100.0f || y <= 0) {
        y_direction *= -1.0f;
        x_direction *= 1.0f;
    }
}

Side note: The global variables need to be defined before they’re used, add the floats to the top of the file

Here’s a video of what this looks like when the application is running inside the Windows 8 Simulator:

Combining XAML with C++ and DirectX will let us create very nice applications and games. Go ahead and great your cool game today and play around with the DirectX samples that come with Visual Studio 2012!

Vote on HN