Windows 8 Store App Crash Logs

I was recently working on a Windows 8 app, and the application was crashing occasionally.  When resuming the application, the app would crash and close immediately without providing any feedback or information on what went wrong.  The crash was very difficult to reproduce, and I could never get the crash to occur when I was debugging through Visual Studio.  My app was crashing, and I had no idea what was going wrong!  HELP!!!

After doing some digging, I found that when a Windows 8 Store App crashes, an error is logged in Windows Administrative Events.  You can view the details of any app crash by launching the Event Viewer and selecting Administrative Events under Custom Views.  The Source of the error will be listed as AppHost.  AppHost is the process that runs your Windows 8 Store App.  The error details contain all the information you would expect to find, including a stack trace and line numbers.

 

Windows 8 Tip:  A shortcut for launching the Event Viewer in Windows 8.  Right click on the bottom left corner of your desktop (where you normally click to go to the Start Screen).  A menu will appear with shortcuts to a number of common system tasks such as Event Viewer, Task Manager, Command Prompt, and Device Manager.

Where'd My Data Go? (and/or...How Do I Get Rid of It?)

Want to get a better idea of how cascade deletes work in Entity Framework Code First scenarios? Want to see it in action? Stick with us as we quickly demystify what happens when you tell your data context to nuke a parent entity. This post is authored by Calgary .NET User Group Leader David Paquette with help from Microsoft MVP in Asp.Net James Chambers.
We got to spend a great week back in March at Prairie Dev Con West, chalk full of sessions, presentations, workshops, conversations and, of course, questions. One of the questions that came up during my session: “How does Entity Framework Code First deal with cascading deletes?”. James and I had different thoughts on what the default was, if it was different from SQL server, if it was the same as EF proper and if there was a way to override whatever the default was.

So we built a set of examples and figured out that the answer is simple: it depends. (Download Samples)

Consider the example of a hockey league. You have several different entities in the league including games, teams that play the games and players that make up the teams. Each team also has a mascot. If you delete a team, we need a couple of things to happen:

  1. The team, games and mascot will be deleted, and
  2. The players for that team will remain in the league (and therefore the database) but they should no longer be assigned to a team.
    So, let’s make this start to come together with a look at the default behaviour in SQL when using an EDMX-driven project.

The Reference – Understanding EF’s Behaviour with an EDMX/DB First Approach

First up let’s take a look at the DB first approach. In the database, we defined 4 tables: Teams, Players, Mascots, and Games. We also defined 4 foreign keys as follows:

Players.TeamId (NULL)_ –> Teams.Id

Mascots.Id (NOT NULL) –> Teams.Id (ON DELETE CASCADE)

Games.HomeTeamId (NOT NULL)_ –> Teams.Id

Games.AwayTeamId (NOT NULL)_ –> Teams.Id
Note that by specifying ON DELETE CASCADE for the Mascots –> Teams foreign key, the database will automatically delete the team’s mascot when the team is deleted. While we want the same behaviour for the Games –> Teams foreign keys, it is not possible to accomplish this using ON DELETE CASCADE in SQL Server. Specifying a ON DELETE CASCADE on these foreign keys would cause a circular reference error:
The series of cascading referential actions triggered by a single DELETE or UPDATE must form a tree that contains no circular references. No table can appear more than one time in the list of all cascading referential actions that result from the DELETE or UPDATE – MSDN
When we create an entity data model from the above database, we get the following:

 

In order to get the Games to be deleted when the Team is deleted, we need to specify End1 OnDelete action of Cascade for the HomeGames and AwayGames associations.

 

Now, we have an Entity Data Model that accomplishes what we set out to do. One caveat here is that Entity Framework will only properly handle the cascading delete when the the players and games for the team have been loaded into memory. For a more detailed look at Cascade Delete in EF Database First, take a look at this blog post by Alex James.

 

Building The Same Sample with EF Code First

Next, we’re going to build up the model with the code first approach. EF Code First is defined on the Ado.Net team blog as such:

Code First allows you to define your model using C# or VB.Net classes, optionally additional configuration can be performed using attributes on your classes and properties or by using a Fluent API. Your model can be used to generate a database schema or to map to an existing database.
Entity Framework Code First follows some conventions to determine when to cascade delete on a relationship. More details can be found on MSDN.aspx):
If a foreign key on the dependent entity is not nullable, then Code First sets cascade delete on the relationship. If a foreign key on the dependent entity is nullable, Code First does not set cascade delete on the relationship, and when the principal is deleted the foreign key will be set to null. The multiplicity and cascade delete behavior detected by convention can be overridden by using the fluent API. For more information, see Configuring Relationships with Fluent API (Code First).aspx).
Our DbContext consists of 4 DbSets:

public DbSet Teams { get; set; }
public DbSet Players { get; set; }
public DbSet Mascots { get; set; }
public DbSet Games { get; set; }

When we set the Mascot –> Team relationship to required, Entity Framework will automatically delete the Mascot when the Team is deleted. This can be done either using the [Required] data annotation attribute, or by overriding the OnModelCreating method of your DbContext and using the fluent API.

Data Annotations:

public class Mascot
{
public int Id { get; set; }
public string Name { get; set; }

[Required]
public virtual Team Team { get; set; }

}
Fluent API:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity().HasRequired(m => m.Team);
}

The Player –> Team relationship is automatically handled by the Code First conventions. When a Team is deleted, the Team property for all the players on that team will be set to null. No additional configuration is required, however all the Player entities must be loaded into memory for the cascading to work properly.

The Game –> Team relationship causes some grief in our Code First example. If we try setting the HomeTeam and AwayTeam relationships to required, Entity Framework will attempt to set On Cascade Delete for the HomeTeam and AwayTeam foreign keys when creating the database tables. As we saw in the database first example, this causes a circular reference error and throws the following SqlException:

Introducing FOREIGN KEY constraint ‘FK_Games_Teams_AwayTeam_Id’ on table ‘Games’ may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints. Could not create constraint.
To solve this problem, we need to disable the default cascade delete behaviour using the fluent API:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity().HasRequired(m => m.Team);

modelBuilder.Entity()
                    .HasMany(t => t.HomeGames)
                    .WithRequired(g => g.HomeTeam)
                    .WillCascadeOnDelete(false);

modelBuilder.Entity()
                    .HasMany(t => t.AwayGames)
                    .WithRequired(g => g.AwayTeam)
                    .WillCascadeOnDelete(false);

base.OnModelCreating(modelBuilder);

}
Unfortunately, this means we need to manually manage the cascade delete behaviour. When a Team is deleted, we need to manually delete all the home and away Games for that Team.

foreach (Game awayGame in jets.AwayGames.ToArray())
{
entities.Games.Remove(awayGame);
}

foreach (Game homeGame in homeGames)
{
entities.Games.Remove(homeGame);
}

entities.Teams.Remove(jets);

entities.SaveChanges();
Overriding the Defaults – When and How To

As you have seen, the default behaviour of Entity Framework Code First can be overridden using the fluent API. This can be done by overriding the OnModelCreating method of your DbContext, or by creating separate model override files for each entity. More information is available on MSDN.aspx).

Going Further

These were simple examples but they helped us illustrate a couple of points. First of all, we were able to demonstrate the default behaviour of Entity Framework when dealing with cascading deletes, specifically how entity relationships affect the outcome. Secondly, we showed you how to modify the code and control the behaviour to get the outcome you’re looking for.

Finally, we showed you how easy it is to explore this kind of thing, and we’re hoping that you get a chance to experiment even further. For example, did you know that:

  • Entity Framework Code First also works seamlessly with SQL Azure (MSDN)
  • Database creation defaults can be overridden using a variety of IDatabaseInitializers (Understanding Database Initializers)
  • You can use Code Based migrations to manage database upgrades as your model continues to evolve (MSDN)

Next Steps

There’s no time like the present to start the learning, so here’s what you need to do:

  1. Get up-to-date in Visual Studio 2010 (VS2010 | SP1) or Visual Studio 2012 (VS2012)
  2. Build yourself a project to try these concepts out (or download the sample project)
  3. Get into the community and ask questions! There are a ton of great resources out there and community members willing to help you out (like these two guys!).
    Good luck!

About the Authors

David Paquette works as a lead developer at P2 Energy Solutions in Calgary, Alberta where he builds commercial software products for the energy industry. Outside of work, David enjoys outdoor camping, fishing, and skiing. David is also active in the software community giving presentations both locally and at conferences. David also serves as the President of Calgary .Net User Group.

James Chambers crafts software awesomeness with an incredible team at LogiSense Corp, based in Cambridge, Ontario. A husband, father and humanitarian, he is currently residing in the province of Manitoba where he resists the urge to cheer for the Jets and maintains he allegiance to the Calgary Flames. When he’s not active with the family, outdoors or volunteering, you can find James speaking at conferences and user groups across the country about web development and related technologies.

The Iron Bird Approach

It turns out that designing software is not so different than designing commercial aircraft.  I just finished watching a video that talked about the approach that Bombardier is taking in designing the new C Series aircraft.  I was struck by the similarities to agile approaches to software design.  In the video, Bombardier describes how they are using an Iron Bird to work through a number of design questions in advance of ever having a version of the aircraft that can ever be flown.  The Iron Bird is a life size replica of the plane.  Based on the name, I would assume the plane is built in a very heavy material that could never fly.  Using this replica, Bombardier is able to valid certain assumptions such as the length of each wire in the electric system.  They are also able to confirm that some parts are working properly (like the rudders).  They even go as far as to have a complete replica of the cockpit.  This allows Bombardier to put pilots in the cockpit to run through simulated take-off and landing sequences.

The basic tenant of the approach seems to be

Validate your design early with working prototypes

Get feedback from users early, well in advance of finishing the end product

 

In software development, we tend to think of ourselves as special.  I often tell people that it is difficult to draw comparisons to building items in the physical world (“Building software is nothing like building a sky scraper”).  After watching this video, I am wondering if designing/building software is actually a lot like designing/building commercial aircraft.

 

Watch the video here (http://www.theglobeandmail.com/report-on-business/video/video-selling-the-c-series/article4400616/)

Think before you animate

Animations are becoming more and more common in our applications.  With technologies like WPF, Silverlight and jQuery, animations are becoming easier for developers to use (and abuse).  When used properly, animation can augment the user experience.  When used improperly, animation can degrade the user experience.  Sometimes, the differences can be very subtle.

I have recently made use of animations in a few projects and I very quickly realized how easy it is to abuse animation techniques.  Here are a few things I have learned along the way.

1) Don’t animate for the sake of animating

We’ve all seen the PowerPoint slides with annoying slide transitions that animate 20 different ways.  It’s distracting and tacky.  The same holds true for your application.  While animations are fun and becoming easy to implement, resist the urge to use the technology just because you think the technology is amazing.

 

2) Animations should (and do) have meaning

I recently built a simple Windows Phone 7 (WP7) application, Steeped (download it here).  The application has 2 pages.  The first page lists a number of tea types.  When the user taps on one of the tea types, the application navigates to the second page with information about that tea type and some options for the user to choose from. 

Screenshot1     Screenshot2

One of the last things I did before submitting Steeped to the marketplace was add a page transition between the 2 pages.  I choose the Slide / Fade Out transition.  When the user selects a tea type, the main page slides to the left and fades out.  At the same time, the details page slides in from the right and fades in.  I tested it and thought it looked great so I submitted the app.  A few days later, I asked a friend to try the app.  He selected a tea type, and I was a little surprised by how he used the app.  When he wanted to navigate back to the main page, instead of pressing the back button on the phone, he tried to use a swiping gesture.  Of course, the swiping gesture did nothing because I had not implemented that feature. 

After thinking about it for a while, I realized that the page transition I had chosen implied a particular behaviour.  As a user, if an action I perform causes an item (in this case the page) to move, then my expectation is that I should be able to move it back.  I have since added logic to handle the swipe gesture and I think the app flows much better now.

When using animation, it pays to ask yourself:  What story does this animation tell my users?

 

3) Watch the replay

Some animations might seem great initially but can get annoying over time.  When you use an animation in your application, make sure you try using it over and over again to make sure it doesn’t get annoying.  When I add an animation, I try watch it at least 25 times in a row.  After watching the animation repeatedly, I can make a more informed decision whether or not I should keep the animation.  Often, I end up shortening the length of the animations.

 

4) Don’t get in the users way

An animation should never slow the user down.  When implemented properly, an animation can give a perceived bump in performance.  A good example of this is a the page transitions in most of the built in apps on WP7.  Obviously, these page animations don’t make the phone any faster, but they do provide a more responsive user experience.  Why?  Because most of the animations begin as soon as the user has performed some action.  The destination page might not be fully loaded yet, but the system responded immediately to user action, giving the impression that the system is more responsive.  If the user did not see anything happen until after the destination page was fully loaded, the application would feel clumsy and slow.  Also, it is important to make sure the animation does not degrade the performance (or perceived performance) of the application.

 

Jut a few things to consider when using animations.  As is the case with many technologies, we often learn how to misuse it before we learn how to use it effectively.

Deal Groupie – Learning WP7 and ASP.NET MVC 3

Lately, I have been taking some time to learn some new technologies.  For me, the best way to learn a new technology is to jump head first into a project:

Daily deal websites such as GroupOn, LivingSocial, DealFind, etc. have really taken off over the last 6 months.  With so many sites out there, my inbox was being flooded with emails from all these daily deal websites.  This seemed like it might be a fun project,  so I set out to build a daily deal aggregator.

First, I built a Windows Phone 7 app.  I built this app using Visual Studio 2010. Silverlight for WP7, the silverlight toolkit for WP7 and WCF.  Overall, I was pleased with the developer tools for Windows Phone 7 and I am looking forward to building more apps for WP7

ScreenShot5

The app conveniently presents deals for your city in a format very similar to the email client for Windows Phone 7.  Users can flag deals, share deals with friends, and buy deals from over 20 daily deal websites.  If you have a Windows Phone, you can download the Deal Groupie App here.

 

Next, I set out to learn some new web technologies.  I had recently attended a Microsoft Web Camp in Calgary (presented by Jonathan McCracken) and I was impressed with what I saw.  I decided to build a web version of Deal Groupie using ASP.NET MVC3.  I also made use of jQuery, jQuery UI, SQL Server CE 4 and WCF.  Since I had most of the backend already built, the web version did not take me nearly as long to build as the WP7 version did.  I spent more time tweaking the css than anything else.  The website provides daily deals for the selected city in 3 ways: a simple webpage listing all the active deals, a free daily email, and an RSS feed.  The RSS feed was exceptionally easy to implement using Syndication mechanism built in to WCF.

DealGroupieSite

Find deals in your city – http://www.mydealgroupie.com/

Currently, Deal Groupie is finding more than 2000 deals per day in over 300 cities in the USA, Canada, UK, and Australia.

Overall, building the Deal Groupie app and website has been a really good learning experience.  What’s next?  I’m thinking of building an Android version of the app and adding some filtering options to the website.

WF4 Asynchronous Workflows

If you are like me, you may have been surprised when you read the MSDN documentation for System.Activities.Statements.Parallel.

A Parallel activity operates by simultaneously scheduling each Activity in its Branches collection at the start. It completes when all of its Branches complete or when its CompletionCondition property evaluates to true. While all the Activity objects run asynchronously, they do not execute on separate threads, so each successive activity only executes when the previously scheduled activity completes or goes idle. If none of the child activities of this activity go idle, this activity execute in the same way that a **Sequence** activity does.

-MSDN (http://msdn.microsoft.com/en-us/library/system.activities.statements.parallel.aspx)

While the name implies that each branch of activities would be executed on a separate thread, the Parallel activity does not execute activities on separate threads.  In fact, all activities in a workflow execute on the same thread.  This is very similar to how in Windows Forms and WPF, all code that manipulates the user interface must be executed on the UI thread.  You might be asking yourself:  What is the point of this parallel activity?

It is possible for some activity to execute work on a background thread.  When combined with the Parallel activity (or the ParallelForEach activity), this allows the workflow runtime to schedule other activities to be executed while it is waiting for the background thread to complete.  WF4 comes with a number of asynchronous activities that can be used in this way.  Some examples are the Delay, InvokeMethod (when RunAsynchronously is set to true).  If you are creating custom activities, you can also create activities that execute asynchronously.  If you are implementing a code-based activity, you can inherit from AsyncCodeActivity.  If you are implementing more complex activities that need to make use of the workflow runtime, there are a couple strategies for implementing asynchronous activities.  One option is to use the parallel extensions introduced in .NET 4 (Workflow and Parallel Extensions).   Another option is to use bookmarks.

However, if you want to compose a workflow in XAML and have that workflow executed in parallel, your options are more limited.  Here’s an example:

In this example, I would like the 2 workflows to execute on a separate thread.  The output, however, shows that both activities are executed on the same thread:

Luckily, there is a way to accomplish this using a dynamic activity to execute a child activity on a background thread.  The child activity can be any activity (including Sequence or FlowChart), so this allows us to execute any portion of a workflow on a background thread. 


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Activities;
using System.Threading.Tasks;
using System.ComponentModel;
using Microsoft.VisualBasic.Activities;

namespace ParallelActivities
{
[Designer(typeof(AsyncActivityWrapperDesigner))]
public class AsyncActivityWrapper : AsyncCodeActivity
{
public AsyncActivityWrapper()
{
Body = new ActivityAction();
}

    [Browsable(false)]
    public ActivityAction Body { get; set; }

    protected override IAsyncResult BeginExecute(AsyncCodeActivityContext context, AsyncCallback callback, object state)
    {        
         Activity activity = CreateDynamicActivity(context);
        IDictionary inputs = GetArgumentsAndVariables(context);
        Task task = Task.Factory.StartNew((ignore) =>
        {
            WorkflowInvoker.Invoke(activity, inputs);

        }, state);
        task.ContinueWith((t) => callback(t));
        return task;
    }

    protected override void EndExecute(AsyncCodeActivityContext context, IAsyncResult result)
    {            
    }

    private Activity CreateDynamicActivity(AsyncCodeActivityContext context)
    {
        DynamicActivity result = new DynamicActivity();
        //Create a DynamicActivityProperty for each argument / variable in the current context
        foreach (PropertyDescriptor property in context.DataContext.GetProperties())
        {
            DynamicActivityProperty dynamicActivityProperty = new DynamicActivityProperty();

            dynamicActivityProperty.Name = property.Name;
            dynamicActivityProperty.Type = typeof(InArgument<>).MakeGenericType(property.PropertyType);
            dynamicActivityProperty.Value = Activator.CreateInstance(dynamicActivityProperty.Type);
            result.Properties.Add(dynamicActivityProperty);
        }

        //Copy impors to dynamic activity;
        VisualBasic.SetSettings(result, VisualBasic.GetSettings(this));
        result.Implementation = () => Body.Handler;
        return result;
    }

    private IDictionary GetArgumentsAndVariables(AsyncCodeActivityContext context)
    {
        IDictionary result = new Dictionary();

        foreach (PropertyDescriptor property in context.DataContext.GetProperties())
        {
            result.Add(property.Name, property.GetValue(context.DataContext));
        }

        return result;
    }
}

}

Using the AsyncActivityWrapper inside a Parallel activity accomplishes the desired behavior by executing activities inside the AsyncActivityWrapper as shown here:

With the AsyncActivityWrapper, we can see that each branch of the Parallel activity is executed on a separate thread:

The designer for this activity is actually very simple.  It contains a single WorkfowItemPresenter which allows us to drag and drop an activity into the AsyncActivityWrapper.


<sap:ActivityDesigner x:Class="ParallelActivities.AsyncActivityWrapperDesigner"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:sap="clr-namespace:System.Activities.Presentation;assembly=System.Activities.Presentation"
    xmlns:sapv="clr-namespace:System.Activities.Presentation.View;assembly=System.Activities.Presentation">

    <sap:WorkflowItemPresenter Margin="7" Item="{Binding Path=ModelItem.Body.Handler, Mode=TwoWay}" HintText="Drop Activity"/>

</sap:ActivityDesigner>

In conclusion, the AsyncActivityWrapper can be used to execute portions of a workflow on a separate thread.  When combined with the Parallel or ParallelForEach activities, this allows us to execute multiple activities in parallel.  In situations where a workflow is processing a large amount of data, or doing a large number of complex calculations, the AsyncActivityWrapper can help to improve performance.  The implementation provided here does have some limitations.  As with any parallel programming, you need to make sure that activities that are executing in parallel do not conflict with each other.  If the activities are trying to access and manipulate the same data, you might run into problems.  If the activities have a return value, you may need an alternate implementation of AsyncActivityWrapper that inherits from AsyncCodeActivity<TResult>.  Also, since each activity is being executed as a separate independant workflow, you will lose some workflow functionality such as Persistence and Tracking.